-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttps_proxy.c
More file actions
65 lines (56 loc) · 2.21 KB
/
https_proxy.c
File metadata and controls
65 lines (56 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include "https_proxy.h"
// 解析 CONNECT 请求,提取 target_host 和 target_port
// 请求格式:CONNECT example.com:443 HTTP/1.1\r\n\r\n
int https_parse_connect(const char* req_buf, int req_len, char* target_host, int host_len, uint16_t* target_port) {
char method[16], path[256], version[16];
if (sscanf(req_buf, "%s %s %s", method, path, version) != 3) {
return -1;
}
// 校验是否为 CONNECT 方法
if (strcmp(method, "CONNECT") != 0) {
return -1;
}
// 分割 path 中的 host 和 port(默认 443)
char* colon_pos = strchr(path, ':');
if (colon_pos) {
*colon_pos = '\0';
snprintf(target_host, host_len, "%s", path);
*target_port = atoi(colon_pos + 1);
} else {
snprintf(target_host, host_len, "%s", path);
*target_port = 443;
}
return 0;
}
// 向客户端返回 200 Connection Established 响应
int https_send_200(SOCKET_T client_sock) {
const char* resp = "HTTP/1.1 200 Connection Established\r\n\r\n";
return send(client_sock, resp, strlen(resp), 0);
}
// 解析普通 HTTP 请求(提取 Host 头中的目标地址)
int http_parse_request(const char* req_buf, int req_len, char* target_host, int host_len, uint16_t* target_port) {
// 1. 先提取 Host 头(HTTP 请求的核心,格式:Host: www.baidu.com:80)
const char* host_header = strstr(req_buf, "Host: ");
if (host_header == NULL) {
return -1;
}
host_header += 6; // 跳过 "Host: " 字符串
// 2. 提取 Host 内容(直到 \r 或 \n 结束)
char host_buf[256] = {0};
int i = 0;
while (host_header[i] != '\r' && host_header[i] != '\n' && host_header[i] != '\0' && i < sizeof(host_buf)-1) {
host_buf[i] = host_header[i];
i++;
}
// 3. 分割 host 和 port(HTTP 默认端口 80)
char* colon_pos = strchr(host_buf, ':');
if (colon_pos) {
*colon_pos = '\0';
snprintf(target_host, host_len, "%s", host_buf);
*target_port = atoi(colon_pos + 1);
} else {
snprintf(target_host, host_len, "%s", host_buf);
*target_port = 80; // HTTP 默认端口
}
return 0;
}