Compare commits
3
Commits
cd10d0cc1b
...
5bff9df3fc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5bff9df3fc | ||
|
|
45e1dd9f6c | ||
|
|
13c02fe50b |
No files matched your search
@@ -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;
|
||||
- 中继侧/接收侧的日志只能证明「收到的字节是什么」,不能证明「上游是谁写坏的」。
|
||||
|
||||
@@ -8480,10 +8480,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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" />
|
||||
|
||||
@@ -125,11 +125,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" />
|
||||
|
||||
@@ -2331,7 +2331,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);
|
||||
@@ -5854,7 +5854,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 +5883,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 +6285,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 +6312,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 +6417,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 +6445,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 +6522,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 +6599,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 +6608,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);
|
||||
|
||||
@@ -978,6 +978,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
|
||||
|
||||
@@ -982,6 +982,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
|
||||
|
||||
@@ -980,6 +980,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
|
||||
|
||||
@@ -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
Reference in new issue
Block a user