diff --git a/Dependencies.md b/Dependencies.md index 8ab54f0..7c62aa4 100644 --- a/Dependencies.md +++ b/Dependencies.md @@ -4,7 +4,7 @@ Prebuilt binaries under `compress/`, linked via `#pragma comment(lib, ...)`. -- [zlib v1.3.2](https://zlib.net) +- [zlib v1.4](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) — GPL-2.0, see note below - [libyuv v190](https://chromium.googlesource.com/libyuv/libyuv) diff --git a/client/IOCPClient.cpp b/client/IOCPClient.cpp index 24e3e68..88bae65 100644 --- a/client/IOCPClient.cpp +++ b/client/IOCPClient.cpp @@ -28,30 +28,46 @@ inline int WSAGetLastError() #include #include #include -#if USING_ZLIB -#include "zlib/zlib.h" -#define Z_FAILED(p) (Z_OK != (p)) -#define Z_SUCCESS(p) (!Z_FAILED(p)) +// 线缆压缩:Windows 客户端同时携带 zlib 与 zstd,运行期由 settings\compress 选择 +// (默认 zstd,配置为 zlib 时使用 zlib)。POSIX 客户端只链接 libzstd。 +#if defined(_WIN32) +# include "zlib/zlib.h" +# define CLIENT_HAS_ZLIB 1 #else +# define CLIENT_HAS_ZLIB 0 +#endif #include "common/zstd_wrapper.h" +#define ZSTD_CLEVEL ZSTD_CLEVEL_DEFAULT + +// ZSTD 库在客户端始终要链接:文件管理器的 ZSTA 归档(common/ZstdArchive.h)、 +// common/zstd_wrapper.c 以及上面的版本日志都无条件引用 ZSTD_*,与线缆压缩 +// 选择 zlib 还是 zstd 无关。此处在两种模式下都生效。 #ifdef _WIN32 # ifdef _WIN64 # pragma comment(lib, "zstd/zstd_x64.lib") # else # pragma comment(lib, "zstd/zstd.lib") # endif +# include "common/iniFile.h" // CLIENT_PATH + settings\compress #endif -#define Z_FAILED(p) ZSTD_isError(p) -#define Z_SUCCESS(p) (!Z_FAILED(p)) -#define ZSTD_CLEVEL ZSTD_CLEVEL_DEFAULT -#if USING_CTX -#define compress(dest, destLen, source, sourceLen) zstd_compress_auto(m_Cctx, dest, *(destLen), source, sourceLen, 1024*1024) -#define uncompress(dest, destLen, source, sourceLen) ZSTD_decompressDCtx(m_Dctx, dest, *(destLen), source, sourceLen) + +// 读取 settings\compress:默认 zstd,值为 "zlib"(大小写不敏感)时使用 zlib。 +// 配置存放在客户端注册表(CLIENT_PATH)。服务端下发 COMMAND_SET_COMPRESS 会写同一个 +// 键并触发重连;新连接在构造函数里重新读取,从而无需重启进程即可生效。 +static bool ClientCompressUsesZlib() +{ +#if defined(_WIN32) && CLIENT_HAS_ZLIB + iniFile cfg(CLIENT_PATH); + std::string mode = cfg.GetStr("settings", "compress", "zstd"); + for (size_t i = 0; i < mode.size(); ++i) { + if (mode[i] >= 'A' && mode[i] <= 'Z') + mode[i] = (char)(mode[i] - 'A' + 'a'); + } + return mode == "zlib"; #else -#define compress(dest, destLen, source, sourceLen) ZSTD_compress(dest, *(destLen), source, sourceLen, ZSTD_CLEVEL_DEFAULT) -#define uncompress(dest, destLen, source, sourceLen) ZSTD_decompress(dest, *(destLen), source, sourceLen) -#endif + return false; #endif +} ////////////////////////////////////////////////////////////////////// // Construction/Destruction @@ -244,6 +260,11 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask, #endif } + // 线缆压缩模式:运行期读取配置(默认 zstd)。每个连接实例只读一次; + // 服务端下发 COMMAND_SET_COMPRESS 后客户端会重启 StartClient 线程,新实例重新读取。 + m_useZlib = ClientCompressUsesZlib(); + Mprintf("[IOCPClient] wire compress: %s\n", m_useZlib ? "zlib" : "zstd"); + m_main = main; m_conn = conn; // 保存 CONNECT_ADDRESS 指针。子连接 auth 在每次连接时通过 // m_conn->clientID 现取主连接 ID(同一指针,主连接登录后填好的最新值)。 @@ -296,7 +317,7 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask, m_Cctx = ZSTD_createCCtx(); m_Dctx = ZSTD_createDCtx(); auto n = ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, 0); - if (Z_FAILED(n)) { + if (ZSTD_isError(n)) { ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, 0); } ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_compressionLevel, ZSTD_CLEVEL); @@ -307,6 +328,74 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask, #endif } +// 线缆压缩/解压:按本连接构造时选定的 m_useZlib 走 zlib 或 zstd。 +// 成功返回 true 并写回实际长度;失败返回 false。 +bool IOCPClient::CompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen) +{ + if (m_useZlib) { +#if CLIENT_HAS_ZLIB + uLongf n = (uLongf)dstLen; + int r = compress(dst, &n, (const Bytef*)src, (uLong)srcLen); + if (r != Z_OK) + return false; + dstLen = (ULONG)n; + return true; +#else + return false; +#endif + } +#if USING_CTX + { + size_t r = zstd_compress_auto(m_Cctx, dst, (size_t)dstLen, src, (size_t)srcLen, 1024 * 1024); + if (ZSTD_isError(r)) + return false; + dstLen = (ULONG)r; + return true; + } +#else + { + size_t r = ZSTD_compress(dst, (size_t)dstLen, src, (size_t)srcLen, ZSTD_CLEVEL_DEFAULT); + if (ZSTD_isError(r)) + return false; + dstLen = (ULONG)r; + return true; + } +#endif +} + +bool IOCPClient::DecompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen) +{ + if (m_useZlib) { +#if CLIENT_HAS_ZLIB + uLongf n = (uLongf)dstLen; + int r = uncompress(dst, &n, (const Bytef*)src, (uLong)srcLen); + if (r != Z_OK) + return false; + dstLen = (ULONG)n; + return true; +#else + return false; +#endif + } +#if USING_CTX + { + size_t r = ZSTD_decompressDCtx(m_Dctx, dst, (size_t)dstLen, src, (size_t)srcLen); + if (ZSTD_isError(r)) + return false; + dstLen = (ULONG)r; + return true; + } +#else + { + size_t r = ZSTD_decompress(dst, (size_t)dstLen, src, (size_t)srcLen); + if (ZSTD_isError(r)) + return false; + dstLen = (ULONG)r; + return true; + } +#endif +} + void IOCPClient::PrepareHeaderEncoderForConnect() { if (!m_EncoderType) { @@ -358,7 +447,7 @@ void IOCPClient::SetMultiThreadCompress(int threadNum) #if USING_CTX BOOL failed = TRUE; if (threadNum > 1) { - failed = Z_FAILED(ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, threadNum)); + failed = ZSTD_isError(ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, threadNum)); } if (failed) { ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, 0); @@ -1007,9 +1096,15 @@ VOID IOCPClient::OnServerReceiving(CBuffer* m_CompressedBuffer, char* szBuffer, m_CompressedBuffer->ReadBuffer(CompressedBuffer, ulCompressedLength); m_Encoder->Decode(CompressedBuffer, ulCompressedLength, (LPBYTE)szPacketFlag); - size_t iRet = uncompress(DeCompressedBuffer, &ulOriginalLength, CompressedBuffer, ulCompressedLength); - if (Z_SUCCESS(iRet)) { //如果解压成功 + // 与发送同一模式:服务端按客户端首个压缩包识别算法,回包使用同一算法, + // 因此这里固定用本连接的 m_useZlib 解压。 + ULONG ulDecompressedLength = ulOriginalLength; + bool decompressed = DecompressData(DeCompressedBuffer, ulDecompressedLength, + CompressedBuffer, ulCompressedLength); + ulOriginalLength = ulDecompressedLength; + + if (decompressed) { //如果解压成功 // 优先看是不是 TOKEN_CONN_AUTH 响应;只有当 PerformConnAuth 正在等待时才消费。 // 不在等待状态时返回 false,包透传给 manager(manager 一般也不识别此 token, // 走 default 路径忽略,无副作用)。 @@ -1058,27 +1153,24 @@ BOOL IOCPClient::OnServerSending(const char* szBuffer, ULONG ulOriginalLength, P std::lock_guard lock(m_Locker); { int cmd = BYTE(szBuffer[0]); - //乘以1.001是以最坏的也就是数据压缩后占用的内存空间和原先一样 +12 - //防止缓冲区溢出// HelloWorld 10 22 - //数据压缩 压缩算法 微软提供 - //nSize = 436 - //destLen = 448 -#if USING_ZLIB - unsigned long ulCompressedLength = (double)ulOriginalLength * 1.001 + 12; + // 线缆压缩:运行期选择 zlib / zstd(默认 zstd)。zlib 用 compressBound 而不是 + // 1.001n+12 —— 后者对小于约 1KB 的包会比 compressBound 少 1 字节,导致 + // compress() 返回 Z_BUF_ERROR、小包(心跳 ACK、控制命令)被静默丢弃。 +#if CLIENT_HAS_ZLIB + unsigned long ulCompressedLength = m_useZlib + ? (unsigned long)compressBound(ulOriginalLength) + : (unsigned long)ZSTD_compressBound(ulOriginalLength); #else - unsigned long ulCompressedLength = ZSTD_compressBound(ulOriginalLength); + unsigned long ulCompressedLength = (unsigned long)ZSTD_compressBound(ulOriginalLength); #endif BYTE buf[1024]; LPBYTE CompressedBuffer = ulCompressedLength>1024 ? new BYTE[ulCompressedLength] : buf; - int iRet = compress(CompressedBuffer, &ulCompressedLength, (PBYTE)szBuffer, ulOriginalLength); - if (Z_FAILED(iRet)) { - Mprintf("[ERROR] compress failed: srcLen %d, dstLen %d \n", ulOriginalLength, ulCompressedLength); + if (!CompressData(CompressedBuffer, ulCompressedLength, szBuffer, ulOriginalLength)) { + Mprintf("[ERROR] compress failed: srcLen %d, dstLen %d, mode=%s\n", + ulOriginalLength, ulCompressedLength, m_useZlib ? "zlib" : "zstd"); if (CompressedBuffer != buf) delete [] CompressedBuffer; return FALSE; } -#if !USING_ZLIB - ulCompressedLength = iRet; -#endif ULONG ulPackTotalLength = ulCompressedLength + m_Encoder->GetHeadLen(); CBuffer m_WriteBuffer; HeaderFlag H = m_Encoder->GetHead(); diff --git a/client/IOCPClient.h b/client/IOCPClient.h index 0c130b8..f4801b1 100644 --- a/client/IOCPClient.h +++ b/client/IOCPClient.h @@ -437,6 +437,12 @@ protected: // ConnectServer 成功后自动 auth 的 opt-in 标志。子连接构造后调 EnableSubConnAuth() 设为 true。 bool m_subConnAuthEnabled = false; uint64_t m_subConnAuthClientID = 0; // 0 表示从 m_conn->clientID 现取 + + // 线缆压缩:运行期由 settings\compress 选择(默认 zstd;配置 zlib 时用 zlib)。 + // 每个连接实例在构造时读取一次;COMMAND_SET_COMPRESS 触发重连后重新读取。 + bool m_useZlib = false; + bool CompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen); + bool DecompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen); #if USING_CTX ZSTD_CCtx* m_Cctx; // 压缩上下文 ZSTD_DCtx* m_Dctx; // 解压上下文 diff --git a/client/KernelManager.cpp b/client/KernelManager.cpp index 44a2623..06809b5 100644 --- a/client/KernelManager.cpp +++ b/client/KernelManager.cpp @@ -1126,6 +1126,33 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength) break; } + case COMMAND_SET_COMPRESS: { + // 线缆压缩切换(zstd / zlib):写本机配置后重启 StartClient 线程。 + // 注意不能只断开当前连接:IOCPClient 的压缩模式在构造时读取,复用旧实例重连 + // 不会重新读配置。置 S_CLIENT_UPDATE 让 StartClientApp 重建连接对象。 + std::string mode; + if (ulLength > 1) + mode.assign((const char*)szBuffer + 1, ulLength - 1); + while (!mode.empty() && (mode.back() == '\0' || mode.back() == ' ' || + mode.back() == '\r' || mode.back() == '\n')) + mode.pop_back(); + for (size_t i = 0; i < mode.size(); ++i) { + if (mode[i] >= 'A' && mode[i] <= 'Z') + mode[i] = (char)(mode[i] - 'A' + 'a'); + } + if (mode != "zlib" && mode != "zstd") { + Mprintf("[compress-switch] unsupported mode '%s', ignored\n", mode.c_str()); + break; + } + if (m_cfg) + m_cfg->SetStr("settings", "compress", mode); + Mprintf("[compress-switch] set to %s, restarting client\n", mode.c_str()); + g_bExit = S_CLIENT_UPDATE; + if (m_ClientObject) + m_ClientObject->Disconnect(); + break; + } + case COMMAND_DOWN_EXEC: { std::thread(DownExecute, std::string((char*)szBuffer + 1), this).detach(); break; diff --git a/client/ScreenManager.cpp b/client/ScreenManager.cpp index 79f2be3..03a2490 100644 --- a/client/ScreenManager.cpp +++ b/client/ScreenManager.cpp @@ -729,11 +729,7 @@ DWORD WINAPI CScreenManager::WorkThreadProc(LPVOID lParam) This->WaitForDialogOpen(); clock_t last = clock(); -#if USING_ZLIB const int fps = 8;// 帧率 -#else - const int fps = 8;// 帧率 -#endif const int sleep = 1000 / fps;// 间隔时间(ms) int c1 = 0; // 连续耗时长的次数 int c2 = 0; // 连续耗时短的次数 diff --git a/client/StdAfx.h b/client/StdAfx.h index 635ee2a..ba9685f 100644 --- a/client/StdAfx.h +++ b/client/StdAfx.h @@ -6,16 +6,12 @@ #if !defined(AFX_STDAFX_H__46CA6496_AAD6_4658_B6E9_D7AEB26CDCD5__INCLUDED_) #define AFX_STDAFX_H__46CA6496_AAD6_4658_B6E9_D7AEB26CDCD5__INCLUDED_ -// 是否使用ZLIB -#define USING_ZLIB 0 - -#if !USING_ZLIB - +// 客户端线缆压缩:Windows 客户端同时编译 zlib 与 zstd,运行期由 settings\compress +// 选择(默认 zstd;配置为 zlib 时使用 zlib)。服务端可通过 COMMAND_SET_COMPRESS +// 写入该配置并触发重连,见 client/IOCPClient.cpp 与 KernelManager 的处理分支。 #define USING_ZSTD 1 #define USING_CTX 1 -#endif - // 是否使用 Opus 音频压缩 (需要 opus 库) // 设为 1 启用 Opus 压缩,设为 0 使用 PCM 无压缩 #define USING_OPUS 1 diff --git a/client/VideoManager.cpp b/client/VideoManager.cpp index 28994cc..fe1294d 100644 --- a/client/VideoManager.cpp +++ b/client/VideoManager.cpp @@ -55,11 +55,7 @@ DWORD CVideoManager::WorkThread(LPVOID lParam) // 等控制端对话框打开 This->WaitForDialogOpen(); -#if USING_ZLIB const int fps = 8;// 帧率 -#else - const int fps = 8;// 帧率 -#endif const int sleep = 1000 / fps;// 间隔时间(ms) timeBeginPeriod(1); diff --git a/common/commands.h b/common/commands.h index 2fad7b7..1753412 100644 --- a/common/commands.h +++ b/common/commands.h @@ -152,6 +152,7 @@ inline int isValid_10s() #define CLIENT_CAP_TERMINAL 0x8000 // 主连接处理 COMMAND_SHELL(PTY 终端子连接:exec_command / terminal_*;Linux 一直支持但不声明,新版 Android 与 macOS 声明) #define CLIENT_CAP_PRIVACY_OVERLAY 0x10000 // 屏幕子连接处理 COMMAND_SCREEN_BLOCK_INPUT / COMMAND_SCREEN_BLANK(Android 用无障碍全屏 overlay 实现;Windows 一直支持锁定键鼠但不声明这个位) #define CLIENT_CAP_PROCESS 0x20000 // 主连接处理 COMMAND_SYSTEM(系统子连接:COMMAND_PSLIST / COMMAND_KILLPROCESS;Linux/macOS 声明,Windows 一直支持但不声明) +#define CLIENT_CAP_COMPRESS_SWITCH 0x40000 // 支持服务端远程切换线缆压缩(COMMAND_SET_COMPRESS,仅 Windows) // TOKEN_WEBCAM_DIB 帧头里的 fccHandler(第 3~6 字节):Android 客户端直接发 JPEG, // 服务端识别这个 FOURCC 后用 turbojpeg 解码,不依赖系统安装 VFW 编解码器。 @@ -385,6 +386,12 @@ enum { COMMAND_MCP_WINDOW_INFO = 179, TOKEN_MCP_WINDOW_INFO = 180, + // 线缆压缩切换(服务端 → 客户端):载荷 [cmd:1]["zlib"|"zstd"]。 + // 客户端写入自己配置的 settings\compress 后重启 StartClient 线程,新连接按新模式 + // 重连;服务端按首包自动识别算法,无需额外握手。只有声明 CLIENT_CAP_COMPRESS_SWITCH + // 的 Windows 客户端认识;老客户端走 default 静默丢弃。 + COMMAND_SET_COMPRESS = 181, + TOKEN_DECRYPT = 199, TOKEN_REGEDIT = 200, // 注册表 COMMAND_REG_FIND, // 注册表 管理标识 @@ -1335,6 +1342,8 @@ typedef struct LOGIN_INFOR { caps |= CLIENT_CAP_C2C_PATHS; // 协议切换(COMMAND_SET_PROTO)只有 Windows 客户端实现了命令处理与入口持久化。 caps |= CLIENT_CAP_PROTO_SWITCH; + // 线缆压缩切换(COMMAND_SET_COMPRESS):Windows 客户端同时携带 zlib/zstd。 + caps |= CLIENT_CAP_COMPRESS_SWITCH; // 多显示器远程控制:抓整个虚拟桌面,截图与注入共用同一坐标系。 caps |= CLIENT_CAP_VIRTUAL_DESKTOP; // 窗口信息 RPC(矩形/z 序/前后台)与窗口激活。 diff --git a/compress/zlib/zconf.h b/compress/zlib/zconf.h index 828ca61..3d308f6 100644 --- a/compress/zlib/zconf.h +++ b/compress/zlib/zconf.h @@ -499,6 +499,10 @@ typedef uLong FAR uLongf; #if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 # define Z_LFS64 +#elif defined(_WIN32) && !defined(__CYGWIN__) && !defined(__BORLANDC__) && \ + !defined(UNDER_CE) && (defined(__MINGW32__) || !defined(__GNUC__)) +# define Z_LFS64 /* native Windows has 64-bit file offsets */ +# define Z_WINLFS #endif #if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) @@ -516,7 +520,7 @@ typedef uLong FAR uLongf; #endif #ifndef z_off_t -# define z_off_t long long +# define z_off_t long #endif #if !defined(_WIN32) && defined(Z_LARGE64) @@ -531,6 +535,11 @@ typedef uLong FAR uLongf; # define z_off64_t z_off_t #endif +#if defined(Z_WINLFS) && defined(Z_WANT64) && !defined(Z_SOLO) +# undef z_off_t +# define z_off_t z_off64_t +#endif + /* MVS linker does not support external names larger than 8 bytes */ #if defined(__MVS__) #pragma map(deflateInit_,"DEIN") diff --git a/compress/zlib/zlib.h b/compress/zlib/zlib.h index a57d336..c7e50b8 100644 --- a/compress/zlib/zlib.h +++ b/compress/zlib/zlib.h @@ -1,5 +1,5 @@ /* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.3.2, February 17th, 2026 + version 1.4, November 4th, 2026 Copyright (C) 1995-2026 Jean-loup Gailly and Mark Adler @@ -41,11 +41,11 @@ extern "C" { #endif -#define ZLIB_VERSION "1.3.2" -#define ZLIB_VERNUM 0x1320 +#define ZLIB_VERSION "1.4" +#define ZLIB_VERNUM 0x1400 #define ZLIB_VER_MAJOR 1 -#define ZLIB_VER_MINOR 3 -#define ZLIB_VER_REVISION 2 +#define ZLIB_VER_MINOR 4 +#define ZLIB_VER_REVISION 0 #define ZLIB_VER_SUBREVISION 0 /* @@ -696,7 +696,9 @@ ZEXTERN int ZEXPORT deflateCopy(z_streamp dest, deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and - destination. + destination. If deflateCopy fails and dest is not Z_NULL, then dest->state + is set to Z_NULL with dest otherwise unchanged, so that deflateEnd(dest) can + be called safely, though dest is not a usable stream. */ ZEXTERN int ZEXPORT deflateReset(z_streamp strm); @@ -769,17 +771,17 @@ ZEXTERN uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen); ZEXTERN z_size_t ZEXPORT deflateBound_z(z_streamp strm, z_size_t sourceLen); /* deflateBound() returns an upper bound on the compressed size after - deflation of sourceLen bytes. It must be called after deflateInit() or - deflateInit2(), and after deflateSetHeader(), if used. This would be used - to allocate an output buffer for deflation in a single pass, and so would be - called before deflate(). If that first deflate() call is provided the - sourceLen input bytes, an output buffer allocated to the size returned by - deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed - to return Z_STREAM_END. Note that it is possible for the compressed size to - be larger than the value returned by deflateBound() if flush options other - than Z_FINISH or Z_NO_FLUSH are used. + deflation of sourceLen bytes. It must be called after deflateInit() or + deflateInit2(), and after deflateSetHeader() or deflateSetDictionary(), if + used. This would be used to allocate an output buffer for deflation in a + single pass, and so would be called before deflate(). If that first + deflate() call is provided the sourceLen input bytes, an output buffer + allocated to the size returned by deflateBound(), and the flush value + Z_FINISH, then deflate() is guaranteed to return Z_STREAM_END. Note that it + is possible for the compressed size to be larger than the value returned by + deflateBound() if flush options other than Z_FINISH or Z_NO_FLUSH are used. - delfateBound_z() is the same, but takes and returns a size_t length. Note + deflateBound_z() is the same, but takes and returns a size_t length. Note that a long is 32 bits on Windows. */ @@ -789,7 +791,7 @@ ZEXTERN int ZEXPORT deflatePending(z_streamp strm, /* deflatePending() returns the number of bytes and bits of output that have been generated, but not yet provided in the available output. The bytes not - provided would be due to the available output space having being consumed. + provided would be due to the available output space having been consumed. The number of bits of output not provided are between 0 and 7, where they await more bits to join them in order to fill out a full byte. If pending or bits are Z_NULL, then those values are not set. @@ -869,8 +871,7 @@ ZEXTERN int ZEXPORT inflateInit2(z_streamp strm, instead. windowBits must be greater than or equal to the windowBits value provided to deflateInit2() while compressing, or it must be equal to 15 if deflateInit2() was not used. If a compressed stream with a larger window - size is given as input, inflate() will return with the error code - Z_DATA_ERROR instead of trying to allocate a larger window. + size is given as input, inflate() may return with a Z_DATA_ERROR. windowBits can also be zero to request that inflate use the window size in the zlib header of the compressed stream. @@ -980,7 +981,9 @@ ZEXTERN int ZEXPORT inflateCopy(z_streamp dest, inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and - destination. + destination. If inflateCopy fails and dest is not Z_NULL, then dest->state + is set to Z_NULL with dest otherwise unchanged, so that inflateEnd(dest) can + be called safely, though dest is not a usable stream. */ ZEXTERN int ZEXPORT inflateReset(z_streamp strm); @@ -1095,9 +1098,10 @@ ZEXTERN int ZEXPORT inflateGetHeader(z_streamp strm, a terminating zero. If any of extra, name, or comment are not present in the header, then that field's pointer is set to Z_NULL. This allows the use of deflateSetHeader() with the returned structure to duplicate the header. - Note that if those fields initially pointed to allocated memory, then the - application will need to save them elsewhere so that they can be eventually - freed. + Though take care that none of the fields were truncated before so using it, + lest havoc ensue. Note that if those fields initially pointed to allocated + memory, then the application will need to save them elsewhere so that they + can be eventually freed. If inflateGetHeader is not used, then the header information is simply discarded. The header is always checked for validity, including the header @@ -1394,8 +1398,8 @@ ZEXTERN gzFile ZEXPORT gzopen(const char *path, const char *mode); errno can be checked to determine if the reason gzopen failed was that the file could not be opened. Note that if 'N' is in mode for non-blocking, the open() itself can fail in order to not block. In that case gzopen() will - return NULL and errno will be EAGAIN or ENONBLOCK. The call to gzopen() can - then be re-tried. If the application would like to block on opening the + return NULL and errno will be EAGAIN or EWOULDBLOCK. The call to gzopen() + can then be re-tried. If the application would like to block on opening the file, then it can use open() without O_NONBLOCK, and then gzdopen() with the resulting file descriptor and 'N' in the mode, which will set it to non- blocking. @@ -1501,9 +1505,12 @@ ZEXTERN z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems, gzfread() returns the number of full items read of size size, or zero if the end of the file was reached and a full item could not be read, or if there was an error. gzerror() must be consulted if zero is returned in - order to determine if there was an error. If the multiplication of size and - nitems overflows, i.e. the product does not fit in a z_size_t, then nothing - is read, zero is returned, and the error state is set to Z_STREAM_ERROR. + order to determine if there was an error. If some data was read before an + error, then that data is returned until exhausted, after which the next call + will return zero and gzerror() will report the error. If the multiplication + of size and nitems overflows, i.e. the product does not fit in a z_size_t, + then nothing is read, zero is returned, and the error state is set to + Z_STREAM_ERROR. In the event that the end of file is reached and only a partial item is available at the end, i.e. the remaining uncompressed data length is not a @@ -1569,7 +1576,7 @@ ZEXTERN int ZEXPORTVA gzprintf(); these possibilities can be determined using zlibCompileFlags(). If a Z_BUF_ERROR is returned, then nothing was written due to a stall on - the non-blocking write destination. + the non-blocking write destination. The operation can be retried. */ ZEXTERN int ZEXPORT gzputs(gzFile file, const char *s); @@ -1677,7 +1684,9 @@ ZEXTERN z_off_t ZEXPORT gzseek(gzFile file, gzseek returns the resulting offset location as measured in bytes from the beginning of the uncompressed stream, or -1 in case of error, in particular if the file is opened for writing and the new starting position - would be before the current position. + would be before the current position, or if the resulting position would + not be representable in the offset type. If gzseek returns -1, the stream + position is unchanged. */ ZEXTERN int ZEXPORT gzrewind(gzFile file); @@ -1778,7 +1787,8 @@ ZEXTERN const char * ZEXPORT gzerror(gzFile file, int *errnum); If errnum is not NULL, *errnum is set to zlib error number. If an error occurred in the file system and not in the compression library, *errnum is set to Z_ERRNO and the application may consult errno to get the exact error - code. + code. The error is reported by gzerror() as soon as it is detected, which + may be before all of the data read prior to the error has been returned. The application must not modify the returned string. Future calls to this function may invalidate the previously returned string. If file is @@ -1972,7 +1982,8 @@ ZEXTERN int ZEXPORT gzgetc_(gzFile file); /* backward compatibility */ * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if * both are true, the application gets the *64 functions, and the regular * functions are changed to 64 bits) -- in case these are set on systems - * without large file support, _LFS64_LARGEFILE must also be true + * without large file support, _LFS64_LARGEFILE must also be true, except on + * native Windows, where 64-bit offsets are always available */ #ifdef Z_LARGE64 ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *); @@ -2029,7 +2040,7 @@ ZEXTERN int ZEXPORT gzgetc_(gzFile file); /* backward compatibility */ #endif /* !Z_SOLO */ -/* undocumented functions */ +/* undocumented functions (not part of the zlib API) */ ZEXTERN const char * ZEXPORT zError(int); ZEXTERN int ZEXPORT inflateSyncPoint(z_streamp); ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table(void); diff --git a/compress/zlib/zlib.lib b/compress/zlib/zlib.lib index 1197f64..c541aa1 100644 Binary files a/compress/zlib/zlib.lib and b/compress/zlib/zlib.lib differ diff --git a/compress/zlib/zlib_x64.lib b/compress/zlib/zlib_x64.lib index 23364d3..d6eca04 100644 Binary files a/compress/zlib/zlib_x64.lib and b/compress/zlib/zlib_x64.lib differ diff --git a/server/2015Remote/2015RemoteDlg.cpp b/server/2015Remote/2015RemoteDlg.cpp index cb0cf78..10d5ce2 100644 --- a/server/2015Remote/2015RemoteDlg.cpp +++ b/server/2015Remote/2015RemoteDlg.cpp @@ -1177,6 +1177,8 @@ 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_EXPERIMENT_COMPRESS_ZSTD, &CMy2015RemoteDlg::OnExperimentCompressZstd) + ON_COMMAND(ID_EXPERIMENT_COMPRESS_ZLIB, &CMy2015RemoteDlg::OnExperimentCompressZlib) ON_COMMAND(ID_PROTO_SWITCH_TCP, &CMy2015RemoteDlg::OnProtoSwitchTcp) ON_COMMAND(ID_PROTO_SWITCH_WS, &CMy2015RemoteDlg::OnProtoSwitchWs) ON_COMMAND(ID_PROTO_SWITCH_WSS, &CMy2015RemoteDlg::OnProtoSwitchWss) @@ -4979,6 +4981,13 @@ void CMy2015RemoteDlg::OnNMRClickOnline(NMHDR *pNMHDR, LRESULT *pResult) pExperimentMenu->DeleteMenu(ID_EXPERIMENT_TLS_ENABLE, MF_BYCOMMAND); if (SHOULD_HIDE_CTX(HIDE_CTX_EXPERIMENT_TLS_DISABLE, CF_EXPERIMENT_TLS_DISABLE)) pExperimentMenu->DeleteMenu(ID_EXPERIMENT_TLS_DISABLE, MF_BYCOMMAND); + // 线缆压缩切换:放在实验功能末尾。仅当该组仍有可见项时追加——被功能位整组 + // 隐藏时既不泄露,也不影响下面「空组摘除」的逻辑。 + if (!IsPopupEmptyOfItems(pExperimentMenu)) { + pExperimentMenu->AppendMenu(MF_SEPARATOR); + pExperimentMenu->AppendMenuL(MF_STRING, ID_EXPERIMENT_COMPRESS_ZSTD, "线缆压缩:ZSTD"); + pExperimentMenu->AppendMenuL(MF_STRING, ID_EXPERIMENT_COMPRESS_ZLIB, "线缆压缩:ZLIB"); + } for (UINT i = 0; i < SubMenu->GetMenuItemCount(); i++) { if (SubMenu->GetSubMenu(i) == pExperimentMenu) { protoInsertPos = (int)i + 1; @@ -5326,6 +5335,36 @@ void CMy2015RemoteDlg::OnExperimentTlsDisable() SendSelectedCommand(&bToken, sizeof(BYTE)); } +// ---- 线缆压缩切换(在线列表右键 → 实验功能 → 线缆压缩:ZSTD / ZLIB)---- +void CMy2015RemoteDlg::OnExperimentCompressZstd() { SwitchSelectedCompression("zstd"); } +void CMy2015RemoteDlg::OnExperimentCompressZlib() { SwitchSelectedCompression("zlib"); } + +VOID CMy2015RemoteDlg::SwitchSelectedCompression(const char* mode) +{ + // 老客户端不认识 COMMAND_SET_COMPRESS,收到只会丢弃;先按能力位过滤。 + int selected = 0, unsupported = 0; + EnterCriticalSection(&m_cs); + for (context* ctx : ResolveCommandTargets()) { + if (!ctx->IsLogin()) continue; + ++selected; + if (!ctx->SupportsCompressSwitch()) ++unsupported; + } + LeaveCriticalSection(&m_cs); + if (selected == 0) return; + if (unsupported > 0) { + MessageBoxL(_T("选中的主机里有客户端版本不支持线缆压缩切换(需要新版 Windows 客户端)"), + _T("提示"), MB_ICONWARNING); + return; + } + + // 载荷 [cmd]["zstd"|"zlib"]。客户端写入 settings\compress 后重启 StartClient 线程, + // 新连接按新模式重连;服务端按每个连接的首包自动识别算法,不影响其它主机。 + std::string pkt(1, (char)COMMAND_SET_COMPRESS); + pkt += mode; + Mprintf("[compress-switch] send %s to %d host(s)\n", mode, selected); + SendSelectedCommand((PBYTE)&pkt[0], (ULONG)pkt.size()); +} + // ---- 协议切换(在线列表右键 → 协议切换 → 直连 TCP / WS / WSS)---- // // 服务端只负责下发目标入口和协议:客户端把入口写进本机配置后断开重连,在线升级换 DLL @@ -10357,6 +10396,15 @@ void CMy2015RemoteDlg::OnListClick(NMHDR* pNMHDR, LRESULT* pResult) {FLAG_WINOS, "WinOS"}, {FLAG_UNKNOWN, "Unknown"}, {FLAG_SHINE, "Shine"}, {FLAG_FUCK, "FUCK"}, {FLAG_HELLO, "Hello"}, {FLAG_HELL, "HELL"}, }; + // 压缩算法标注:服务端按连接自动识别(首个压缩包解压时定型),追加在加密协议后面。 + // 不改 FormatL 的格式串,避免影响多语言翻译 key。 + CString typeText = typMap[type].c_str(); + switch (ctx->GetCompressMethod()) { + case COMPRESS_ZSTD: typeText += " [ZSTD]"; break; + case COMPRESS_ZLIB: typeText += " [ZLIB]"; break; + case COMPRESS_NONE: typeText += " [NONE]"; break; + default: break; // COMPRESS_UNKNOWN:不标注 + } CString processInfo; if (!res[RES_PID].IsEmpty() || !res[RES_FILESIZE].IsEmpty()) { processInfo.FormatL("\r\n进程 PID: %s %s", res[RES_PID].IsEmpty() ? "" : res[RES_PID], res[RES_FILESIZE].IsEmpty() ? "" : res[RES_FILESIZE]); @@ -10377,7 +10425,7 @@ void CMy2015RemoteDlg::OnListClick(NMHDR* pNMHDR, LRESULT* pResult) res[RES_PROGRAM_BITS].IsEmpty() ? "" : res[RES_PROGRAM_BITS] + _L(" 位 "), res[RES_FILE_PATH], res[RES_EXE_VERSION], processInfo, res[RES_SYSTEM_BITS], res[RES_SYSTEM_CPU], res[RES_SYSTEM_MEM], res[RES_RESOLUTION], startTime, expired.c_str(), res[RES_USERNAME], res[RES_ISADMIN] == "1" ? _L("[管理员]") : res[RES_ISADMIN].IsEmpty() ? "" : _L("[非管理员]"), elapsed, - ctx->GetProtocol().c_str(), ctx->GetServerPort(), typMap[type].c_str(), ctx->GetMasterID().c_str(), res[RES_CLIENT_ID]); + ctx->GetProtocol().c_str(), ctx->GetServerPort(), typeText.GetString(), ctx->GetMasterID().c_str(), res[RES_CLIENT_ID]); // 地理信息只在加载了本地 IP 库(QQWry/ip2region)时才查询并展示。 // 未装库时 m_IPConverter 是网络版 GetGeoLocation(同步外网 HTTP,可达数秒), // 且结果不会被显示——跳过可消除双击浮窗的弹出延时。 diff --git a/server/2015Remote/2015RemoteDlg.h b/server/2015Remote/2015RemoteDlg.h index 10ac205..706eb10 100644 --- a/server/2015Remote/2015RemoteDlg.h +++ b/server/2015Remote/2015RemoteDlg.h @@ -597,6 +597,10 @@ public: afx_msg void OnExperimentDrawingBoard(); afx_msg void OnExperimentTlsEnable(); afx_msg void OnExperimentTlsDisable(); + // 线缆压缩切换(实验功能子菜单):写客户端配置并触发立即重连(zstd / zlib) + afx_msg void OnExperimentCompressZstd(); + afx_msg void OnExperimentCompressZlib(); + VOID SwitchSelectedCompression(const char* mode); // 协议切换(在线列表右键菜单,与「实验功能」平级):直连 TCP / WS / WSS afx_msg void OnProtoSwitchTcp(); afx_msg void OnProtoSwitchWs(); diff --git a/server/2015Remote/2015Remote_vs2015.vcxproj b/server/2015Remote/2015Remote_vs2015.vcxproj index b8dfe4f..c8089ef 100644 --- a/server/2015Remote/2015Remote_vs2015.vcxproj +++ b/server/2015Remote/2015Remote_vs2015.vcxproj @@ -107,6 +107,7 @@ /source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions) + server_exports.def Windows true zlib\zlib.lib;%(AdditionalDependencies) @@ -142,6 +143,7 @@ /source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions) + server_exports.def Windows true zlib\zlib_x64.lib;%(AdditionalDependencies) @@ -177,6 +179,7 @@ /source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions) + server_exports.def Windows true true @@ -214,6 +217,7 @@ /source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions) + server_exports.def Windows true true @@ -239,6 +243,7 @@ + diff --git a/server/2015Remote/IOCPServer.cpp b/server/2015Remote/IOCPServer.cpp index 1ae309a..5bd72bc 100644 --- a/server/2015Remote/IOCPServer.cpp +++ b/server/2015Remote/IOCPServer.cpp @@ -1410,8 +1410,10 @@ BOOL WriteContextData(CONTEXT_OBJECT* ContextObject, PBYTE szBuffer, size_t ulOr break; } bool usingZstd = ContextObject->CompressMethod == COMPRESS_ZSTD; + // zlib 用 compressBound:1.001n+12 对小于约 1KB 的包会比 compressBound 少 + // 1 字节,compress() 返回 Z_BUF_ERROR,小包(心跳 ACK、控制命令)被静默丢弃。 unsigned long ulCompressedLength = usingZstd ? - ZSTD_compressBound(ulOriginalLength) : (unsigned long)((double)ulOriginalLength * 1.001 + 12); + ZSTD_compressBound(ulOriginalLength) : compressBound(ulOriginalLength); // 使用预分配缓冲区替代每次 new LPBYTE CompressedBuffer = ContextObject->GetSendCompressBuffer(ulCompressedLength); Buffer tmp(szBuffer, ulOriginalLength); diff --git a/server/2015Remote/Server.h b/server/2015Remote/Server.h index 932cc70..3092dcd 100644 --- a/server/2015Remote/Server.h +++ b/server/2015Remote/Server.h @@ -741,6 +741,10 @@ public: { return Parser.m_nFlagType; } + virtual int GetCompressMethod() const override + { + return CompressMethod; + } // Write compressed buffer. void WriteBuffer(LPBYTE data, ULONG dataLen, ULONG originLen, int cmd = -1) { diff --git a/server/2015Remote/context.h b/server/2015Remote/context.h index 24d4519..47afcdc 100644 --- a/server/2015Remote/context.h +++ b/server/2015Remote/context.h @@ -41,6 +41,7 @@ public: virtual std::string GetProtocol() const = 0; virtual int GetServerPort() const = 0; virtual FlagType GetFlagType() const = 0; + virtual int GetCompressMethod() const = 0; // COMPRESS_ZSTD / COMPRESS_ZLIB / COMPRESS_NONE virtual std::string GetGroupName() const = 0; virtual uint64_t GetAliveTime()const = 0; virtual void SetLastHeartbeat(uint64_t time) = 0; @@ -199,6 +200,14 @@ public: return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_PROTO_SWITCH) != 0; } + // 检查客户端是否支持远程切换线缆压缩(COMMAND_SET_COMPRESS,zstd / zlib)。 + // 只有声明 CLIENT_CAP_COMPRESS_SWITCH 的 Windows 客户端认识。 + bool SupportsCompressSwitch() const { + CString caps = GetClientData(ONLINELIST_CAPABILITIES); + if (caps.IsEmpty()) return false; + return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_COMPRESS_SWITCH) != 0; + } + // 检查客户端是否支持收到 COMMAND_UPDATE 下发的 APK 后拉起系统安装器。 // 只有新版 Android 客户端声明;老 APK 收到命令会走 default 静默丢弃, // 服务端据此提示「先手动装一次新版」。 diff --git a/server/2015Remote/resource.h b/server/2015Remote/resource.h index 64f203f..0678de9 100644 --- a/server/2015Remote/resource.h +++ b/server/2015Remote/resource.h @@ -1123,6 +1123,8 @@ #define ID_PROTO_SWITCH_WSS 33100 // 高级菜单开关:把服务端 TLS 证书内嵌进下发给客户端的 ServerDll #define ID_TOOL_EMBED_TLS_ANCHOR 33101 +#define ID_EXPERIMENT_COMPRESS_ZSTD 33107 +#define ID_EXPERIMENT_COMPRESS_ZLIB 33108 // 高级 → 运行测试程序:把内存里的 ServerDll 在主控进程内加载,本机上线一台测试主机 #define ID_TOOL_RUN_TEST 33106 #define ID_EXIT_FULLSCREEN 40001 @@ -1132,7 +1134,7 @@ #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 418 -#define _APS_NEXT_COMMAND_VALUE 33107 +#define _APS_NEXT_COMMAND_VALUE 33109 #define _APS_NEXT_CONTROL_VALUE 2621 #define _APS_NEXT_SYMED_VALUE 105 #endif diff --git a/server/2015Remote/server_exports.def b/server/2015Remote/server_exports.def new file mode 100644 index 0000000..13bb08f --- /dev/null +++ b/server/2015Remote/server_exports.def @@ -0,0 +1,3 @@ +; Host identity block for auxiliary tooling/diagnostics. +EXPORTS + HostIdentityBlock=?g_MasterID@@3PADA