Compare commits

..
5 Commits
Author SHA1 Message Date
cheney 1821ba1f2c 我还是习惯写 js 2026-05-25 18:08:11 +08:00
cheney e02c1f2b16 简单可用,复杂不可用 2026-05-25 14:29:42 +08:00
cheney acbe2d07bf 似乎首页能访问,其他的不行 2026-05-25 11:35:45 +08:00
cheney f73419e3eb AI 自测结束 2026-05-25 11:13:40 +08:00
cheney cfc009f60d 修改 proxy 方案 2026-05-25 10:28:57 +08:00
6 changed files with 923 additions and 232 deletions
+285
View File
@@ -0,0 +1,285 @@
# 代理通信协议设计文档
## 1. 架构概述
### 1.1 设备角色
| 设备 | 角色 | 能力 | 限制 |
|------|------|------|------|
| 电脑A | 代理客户端 | 可访问内网网站,作为HTTP客户端 | 无法监听端口 |
| 电脑B | 代理服务器 | 可监听端口,转发HTTP请求 | 无法直接访问内网 |
### 1.2 网络拓扑
```
浏览器 <--(端口8081)--> 电脑B <--(端口8080)--> 电脑A <--(HTTP)--> 目标网站
```
### 1.3 核心设计原则
1. **电脑A作为纯HTTP客户端**:不保存cookie、session等状态信息
2. **请求头替换**:电脑A强制替换Origin、Referer等参数
3. **日志对应**:server端每一条请求日志,client端对应一条请求日志
4. **目标网站硬编码**:目标网站地址写死在配置中
---
## 2. 端口分配
| 端口号 | 用途 | 连接方向 |
|--------|------|----------|
| 8080 | 设备A连接端口 | 电脑A → 电脑B |
| 8081 | 浏览器访问端口 | 浏览器 → 电脑B |
---
## 3. 通信协议
### 3.1 协议类型
采用 **自定义HTTP代理协议**,电脑B将浏览器请求转发给电脑A,电脑A作为HTTP客户端访问目标网站。
### 3.2 协议流程
#### 阶段1:设备A连接到设备B
```
电脑A → 电脑B: TCP连接建立
电脑B → 电脑A: "PROXY_CONNECTED\r\n"
电脑A → 电脑B: "READY\r\n"
```
#### 阶段2:浏览器发起请求
```
浏览器 → 电脑B: 完整HTTP请求
GET /max/js/jquery/lib.js HTTP/1.1
Host: localhost:8081
Origin: http://localhost:8081
Referer: http://localhost:8081/
[其他请求头...]
[请求体(如有)]
```
#### 阶段3:电脑B转发请求
```
电脑B → 电脑A: 完整HTTP请求(透传)
```
#### 阶段4:电脑A处理请求
1. **修改请求头**:替换Origin、Referer为目标网站地址
2. **修改Host头**:设置为目标网站地址
3. **移除不必要的头**:如Connection、Keep-Alive等
#### 阶段5:电脑A访问目标网站
```
电脑A → 内网目标: 修改后的HTTP请求
GET /max/js/jquery/lib.js HTTP/1.1
Host: zentao.sunyard.com.cn:9788
Origin: http://zentao.sunyard.com.cn:9788
Referer: http://zentao.sunyard.com.cn:9788/
[其他请求头...]
[请求体(如有)]
```
#### 阶段6:电脑A返回响应
```
内网目标 → 电脑A: HTTP响应
电脑A → 电脑B: HTTP响应(透传)
电脑B → 浏览器: HTTP响应(透传)
```
#### 阶段7:连接保持
- 电脑A与电脑B保持长连接
- 支持同一连接上的多个HTTP请求
- 连接空闲超时时间:300秒
---
## 4. 请求头处理规则
### 4.1 强制替换的请求头
| 请求头 | 替换值 |
|--------|--------|
| Origin | `http://{TARGET_HOST}:{TARGET_PORT}` |
| Referer | `http://{TARGET_HOST}:{TARGET_PORT}/` |
| Host | `{TARGET_HOST}:{TARGET_PORT}` |
### 4.2 移除的请求头
| 请求头 | 原因 |
|--------|------|
| Connection | 由电脑A管理连接 |
| Keep-Alive | 由电脑A管理连接 |
| Proxy-Connection | 不需要代理标识 |
| X-Forwarded-For | 不需要转发标识 |
### 4.3 保留的请求头
所有其他请求头保持不变,包括:
- Accept
- Accept-Encoding
- Accept-Language
- User-Agent
- Cookie(如果有)
- Content-Type
- Content-Length
---
## 5. 数据格式
### 5.1 请求格式
电脑B转发给电脑A的请求格式为**完整的HTTP请求**:
```
{HTTP_METHOD} {REQUEST_PATH} HTTP/1.1\r\n
{HEADER_NAME}: {HEADER_VALUE}\r\n
...
\r\n
{REQUEST_BODY}
```
### 5.2 响应格式
电脑A返回给电脑B的响应格式为**完整的HTTP响应**:
```
HTTP/1.1 {STATUS_CODE} {STATUS_MESSAGE}\r\n
{HEADER_NAME}: {HEADER_VALUE}\r\n
...
\r\n
{RESPONSE_BODY}
```
---
## 6. 日志规范
### 6.1 日志格式
| 字段 | 格式 | 示例 |
|------|------|------|
| 时间戳 | `YYYY-MM-DD HH:MM:SS` | `2024-01-15 10:30:45` |
| 级别 | `[INFO]` / `[ERROR]` | `[INFO]` |
| 来源 | `[Browser]` / `[DeviceA]` / `[System]` | `[Browser]` |
| 行号 | `(line N)` | `(line 45)` |
| 内容 | 描述信息 | 请求详情 |
### 6.2 请求日志(电脑B)
```
[时间戳] [INFO] [Browser] (line N) Request: {METHOD} {PATH} - Body: {BYTES} bytes
```
### 6.3 请求日志(电脑A)
```
[时间戳] [INFO] [System] (line N) Request: {METHOD} {PATH} - Body: {BYTES} bytes
```
### 6.4 响应日志(电脑B)
```
[时间戳] [INFO] [Browser] (line N) Response: {METHOD} {PATH} - Status: {CODE} - Time: {MS}ms
```
### 6.5 响应日志(电脑A)
```
[时间戳] [INFO] [System] (line N) Response: {METHOD} {PATH} - Status: {CODE} - Time: {MS}ms
```
### 6.6 日志对应原则
**server端有一条请求日志,client端必须有一条对应的请求日志**:
```
电脑B: [2024-01-15 10:30:45] [INFO] [Browser] (line 45) Request: GET /max/js/jquery/lib.js - Body: 0 bytes
电脑A: [2024-01-15 10:30:45] [INFO] [System] (line 35) Request: GET /max/js/jquery/lib.js - Body: 0 bytes
```
---
## 7. 错误处理
### 7.1 设备A未连接
当浏览器请求时设备A未连接:
```
HTTP/1.1 503 Service Unavailable
Content-Type: text/plain
Device A not connected
```
### 7.2 目标不可达
当电脑A无法连接目标网站:
```
HTTP/1.1 502 Bad Gateway
Content-Type: text/plain
Cannot connect to target: zentao.sunyard.com.cn:9788
```
### 7.3 重复连接
当已有设备A连接时,拒绝新连接:
```
ERROR: Another A device is already connected
```
### 7.4 请求超时
当请求处理超时:
```
HTTP/1.1 504 Gateway Timeout
Content-Type: text/plain
Request timeout
```
---
## 8. 超时设置
| 操作 | 超时时间 |
|------|----------|
| 设备A连接超时 | 10秒 |
| 目标网站连接超时 | 30秒 |
| 请求处理超时 | 60秒 |
| 连接空闲超时 | 300秒 |
---
## 9. 配置参数
### 9.1 电脑A配置
| 参数 | 说明 | 默认值 |
|------|------|--------|
| TARGET_HOST | 目标内网网站主机 | zentao.sunyard.com.cn |
| TARGET_PORT | 目标内网网站端口 | 9788 |
| B_HOST | 电脑B地址 | localhost |
| B_PORT | 电脑B端口 | 8080 |
### 9.2 电脑B配置
| 参数 | 说明 | 默认值 |
|------|------|--------|
| A_PORT | 设备A连接端口 | 8080 |
| BROWSER_PORT | 浏览器访问端口 | 8081 |
+28
View File
@@ -0,0 +1,28 @@
@echo off
echo ================================================
echo 清理8080端口进程脚本
echo ================================================
echo.
:: 查找并终止使用8080端口的进程
for /f "tokens=5" %%a in ('netstat -ano ^| findstr ":8080" ^| findstr LISTENING') do (
echo 终止进程: PID %%a
taskkill /F /PID %%a
)
for /f "tokens=5" %%a in ('netstat -ano ^| findstr ":8080" ^| findstr ESTABLISHED') do (
echo 终止进程: PID %%a
taskkill /F /PID %%a
)
:: 查找并终止Python代理进程
for /f "tokens=2" %%a in ('tasklist ^| findstr python.exe') do (
taskkill /F /PID %%a
echo 终止Python进程: PID %%a
)
echo.
echo ================================================
echo 清理完成
echo ================================================
pause
+27
View File
@@ -0,0 +1,27 @@
@echo off
echo ================================================
echo 清理8080端口进程脚本
echo ================================================
echo.
:: 查找并终止使用8080端口的进程
for /f "tokens=5" %%a in ('netstat -ano ^| findstr ":8080" ^| findstr LISTENING') do (
echo 终止进程: PID %%a
taskkill /F /PID %%a
)
for /f "tokens=5" %%a in ('netstat -ano ^| findstr ":8080" ^| findstr ESTABLISHED') do (
echo 终止进程: PID %%a
taskkill /F /PID %%a
)
:: 查找并终止Python代理进程
for /f "tokens=2" %%a in ('tasklist ^| findstr python.exe') do (
taskkill /F /PID %%a
echo 终止Python进程: PID %%a
)
echo.
echo ================================================
echo 清理完成
echo ================================================
+258 -58
View File
@@ -1,80 +1,280 @@
# -*- coding: utf-8 -*-
import socket
import threading
import time
import sys
TARGET_HOST = 'superstar.geelytravel.com'
TARGET_PORT = 443
# Configuration
TARGET_HOST = "zentao.sunyard.com.cn"
TARGET_PORT = 9788
B_HOST = "localhost"
B_PORT = 8080
# Global lock for socket write operations
socket_write_lock = threading.Lock()
def get_thread_id():
"""Get thread identifier for logging"""
return threading.current_thread().getName()
def log_info(source, message):
"""Log info message with thread ID"""
thread_id = get_thread_id()
log_line = "[%s] [INFO] [%s] [Thread:%s] %s" % (
time.strftime("%Y-%m-%d %H:%M:%S"),
source,
thread_id,
message
)
print(log_line)
sys.stdout.flush()
def log_error(source, message):
"""Log error message with thread ID"""
thread_id = get_thread_id()
log_line = "[%s] [ERROR] [%s] [Thread:%s] %s" % (
time.strftime("%Y-%m-%d %H:%M:%S"),
source,
thread_id,
message
)
print(log_line)
sys.stdout.flush()
def extract_request_id(request_data):
"""Extract X-Proxy-Request-ID from request headers"""
if "\r\n\r\n" in request_data:
headers_end = request_data.find("\r\n\r\n")
headers = request_data[:headers_end]
for line in headers.split("\r\n"):
if line.lower().startswith("x-proxy-request-id:"):
return line.split(":", 1)[1].strip()
return None
def modify_request_headers(request_data):
"""Modify request headers: replace Origin, Referer, Host; remove Connection headers"""
lines = request_data.split("\r\n")
new_lines = []
method = ""
path = ""
if lines:
first_line = lines[0]
parts = first_line.split()
if len(parts) >= 2:
method = parts[0]
path = parts[1]
for line in lines:
line_str = line
if line_str.startswith("Origin:"):
new_lines.append("Origin: http://%s:%d" % (TARGET_HOST, TARGET_PORT))
elif line_str.startswith("Referer:"):
new_lines.append("Referer: http://%s:%d/" % (TARGET_HOST, TARGET_PORT))
elif line_str.startswith("Host:"):
new_lines.append("Host: %s:%d" % (TARGET_HOST, TARGET_PORT))
elif line_str.lower().startswith("connection:"):
continue
elif line_str.lower().startswith("keep-alive:"):
continue
elif line_str.lower().startswith("proxy-connection:"):
continue
elif line_str.lower().startswith("x-forwarded-for:"):
continue
elif line_str.lower().startswith("x-proxy-request-id:"):
continue
else:
new_lines.append(line_str)
modified_data = "\r\n".join(new_lines)
if path.startswith("/"):
new_path = "http://%s:%d%s" % (TARGET_HOST, TARGET_PORT, path)
if method and modified_data:
modified_data = modified_data.replace(path, new_path, 1)
return modified_data, method, path
def handle_request(request_data):
"""Handle a single request from device B - completely independent thread"""
request_id = extract_request_id(request_data)
modified_data, method, path = modify_request_headers(request_data)
body_size = 0
if "\r\n\r\n" in modified_data:
body_size = len(modified_data) - modified_data.find("\r\n\r\n") - 4
log_info("System", "Request: %s %s - Body: %d bytes - ID: %s" % (method, path, body_size, request_id))
target_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
target_sock.settimeout(30)
def handle_request(sock):
"""处理从A设备收到的请求,转发到目标网站"""
try:
# 接收来自A设备的请求
request = b""
while True:
data = sock.recv(4096)
if not data:
break
request += data
if b"\r\n\r\n" in request:
break
target_sock.connect((TARGET_HOST, TARGET_PORT))
log_info("System", "Connected to target: %s:%d" % (TARGET_HOST, TARGET_PORT))
if not request:
target_sock.sendall(modified_data)
response = ""
while True:
chunk = target_sock.recv(8192)
if not chunk:
break
response += chunk
if "\r\n\r\n" in response:
headers_end = response.find("\r\n\r\n")
headers = response[:headers_end]
content_length = 0
for line in headers.split("\r\n"):
if line.lower().startswith("content-length:"):
content_length = int(line.split(":", 1)[1].strip())
break
body_start = headers_end + 4
if len(response) - body_start >= content_length:
break
if request_id:
if "\r\n\r\n" in response:
headers_end = response.find("\r\n\r\n")
status_line = response[:headers_end].split("\r\n")[0]
rest = response[headers_end:]
response = status_line + "\r\nX-Proxy-Request-ID: " + request_id + rest
status_code = "500"
if "\r\n\r\n" in response:
headers_end = response.find("\r\n\r\n")
headers = response[:headers_end]
for line in headers.split("\r\n"):
if line.startswith("HTTP/"):
status_code = line.split()[1]
break
log_info("System", "Response: %s %s - Status: %s - ID: %s" % (method, path, status_code, request_id))
return response
except socket.error as e:
if e.errno == 111 or e.errno == 10061:
log_error("System", "Cannot connect to target: %s:%d" % (TARGET_HOST, TARGET_PORT))
error_response = "HTTP/1.1 502 Bad Gateway\r\nX-Proxy-Request-ID: " + (request_id if request_id else "") + "\r\nContent-Type: text/plain\r\n\r\nCannot connect to target: %s:%d\r\n" % (TARGET_HOST, TARGET_PORT)
return error_response
else:
log_error("System", "Socket error: %s" % str(e))
error_response = "HTTP/1.1 502 Bad Gateway\r\nX-Proxy-Request-ID: " + (request_id if request_id else "") + "\r\nContent-Type: text/plain\r\n\r\nSocket error\r\n"
return error_response
except socket.timeout:
log_error("System", "Target connection timeout")
error_response = "HTTP/1.1 504 Gateway Timeout\r\nX-Proxy-Request-ID: " + (request_id if request_id else "") + "\r\nContent-Type: text/plain\r\n\r\nConnection timeout\r\n"
return error_response
except Exception as e:
log_error("System", "Error handling request: %s" % str(e))
error_response = "HTTP/1.1 500 Internal Server Error\r\nX-Proxy-Request-ID: " + (request_id if request_id else "") + "\r\nContent-Type: text/plain\r\n\r\nInternal error\r\n"
return error_response
finally:
target_sock.close()
def process_request(b_socket, request_data):
"""Process a request in separate thread and send response back"""
response = handle_request(request_data)
with socket_write_lock:
try:
b_socket.sendall(response)
except Exception as e:
log_error("System", "Failed to send response: %s" % str(e))
def listen_for_requests(sock):
"""Listen for requests from device B"""
sock.settimeout(300)
while True:
try:
data = ""
while True:
chunk = sock.recv(8192)
if not chunk:
log_info("System", "Connection closed by device B")
return
data += chunk
if "\r\n\r\n" in data:
headers_end = data.find("\r\n\r\n")
headers = data[:headers_end]
content_length = 0
for line in headers.split("\r\n"):
if line.lower().startswith("content-length:"):
content_length = int(line.split(":", 1)[1].strip())
break
body_start = headers_end + 4
if len(data) - body_start >= content_length:
break
t = threading.Thread(target=process_request, args=(sock, data), name="ReqHandler-%d" % threading.activeCount())
t.daemon = True
t.start()
except socket.timeout:
log_info("System", "Connection idle timeout")
return
except Exception as e:
log_error("System", "Connection error: %s" % str(e))
return
# 连接到目标网站
target_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
target_sock.connect((TARGET_HOST, TARGET_PORT))
# 发送请求
target_sock.send(request)
# 接收响应并转发回A设备
while True:
response = target_sock.recv(4096)
if not response:
break
sock.send(response)
target_sock.close()
except Exception as e:
print(f"处理请求出错: {e}")
try:
sock.send(b"HTTP/1.1 500 Internal Server Error\r\n\r\n")
except:
pass
def connect_to_a_device(a_host, a_port):
"""连接到A设备"""
def connect_to_b_device(b_host, b_port):
"""Connect to device B and handle requests"""
while True:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((a_host, a_port))
print(f"成功连接到A设备: {a_host}:{a_port}")
print(f"准备转发请求到: {TARGET_HOST}:{TARGET_PORT}")
sock.settimeout(10)
log_info("System", "Connecting to device B: %s:%d" % (b_host, b_port))
sock.connect((b_host, b_port))
handle_request(sock)
log_info("System", "Connected to device B, waiting for PROXY_CONNECTED")
response = sock.recv(1024)
log_info("System", "Received from B: %r" % response)
sock.close()
print("与A设备的连接已断开")
except ConnectionRefusedError:
print(f"A设备未就绪,重试中...")
import time
if not response or "PROXY_CONNECTED" not in response:
log_error("System", "Failed to receive connection confirmation")
sock.close()
time.sleep(3)
continue
log_info("System", "Sending READY to device B")
sock.sendall("READY\r\n")
log_info("System", "Successfully connected to device B: %s:%d" % (b_host, b_port))
listen_for_requests(sock)
except socket.error as e:
if e.errno == 111 or e.errno == 10061:
log_info("System", "Device B not ready (%s:%d), retrying in 3 seconds..." % (b_host, b_port))
else:
log_error("System", "Connection error: %s" % str(e))
time.sleep(3)
except Exception as e:
print(f"连接出错: {e}")
import time
log_error("System", "Unexpected error: %s" % str(e))
time.sleep(3)
def main():
if len(sys.argv) < 3:
print("用法: python proxy_client.py <A设备IP> <A设备端口>")
print("示例: python proxy_client.py 192.168.1.50 8080")
sys.exit(1)
print("=" * 60)
print(" Proxy Client (Run on Computer A)")
print("=" * 60)
print("Target website:", TARGET_HOST, ":", TARGET_PORT)
print("Device B address:", B_HOST, ":", B_PORT)
print("=" * 60)
sys.stdout.flush()
a_host = sys.argv[1]
a_port = int(sys.argv[2])
try:
connect_to_b_device(B_HOST, B_PORT)
except KeyboardInterrupt:
print("\nShutting down...")
sys.exit(0)
connect_to_a_device(a_host, a_port)
if __name__ == '__main__':
if __name__ == "__main__":
main()
-112
View File
@@ -1,112 +0,0 @@
import sys
import winreg
def get_current_proxy():
"""获取当前系统代理设置"""
try:
internet_settings = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
r'Software\Microsoft\Windows\CurrentVersion\Internet Settings',
0,
winreg.KEY_READ
)
proxy_server, _ = winreg.QueryValueEx(internet_settings, 'ProxyServer')
proxy_enable, _ = winreg.QueryValueEx(internet_settings, 'ProxyEnable')
winreg.CloseKey(internet_settings)
return {
'enabled': bool(proxy_enable),
'server': proxy_server
}
except FileNotFoundError:
return {'enabled': False, 'server': ''}
except Exception as e:
print(f"获取代理设置失败: {e}")
return {'enabled': False, 'server': ''}
def set_proxy(proxy_host, proxy_port):
"""设置系统代理"""
try:
internet_settings = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
r'Software\Microsoft\Windows\CurrentVersion\Internet Settings',
0,
winreg.KEY_ALL_ACCESS
)
proxy_server = f'{proxy_host}:{proxy_port}'
winreg.SetValueEx(internet_settings, 'ProxyServer', 0, winreg.REG_SZ, proxy_server)
winreg.SetValueEx(internet_settings, 'ProxyEnable', 0, winreg.REG_DWORD, 1)
winreg.CloseKey(internet_settings)
print(f"✅ 系统代理已设置为: {proxy_server}")
return True
except Exception as e:
print(f"❌ 设置代理失败: {e}")
return False
def unset_proxy():
"""取消系统代理"""
try:
internet_settings = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
r'Software\Microsoft\Windows\CurrentVersion\Internet Settings',
0,
winreg.KEY_ALL_ACCESS
)
winreg.SetValueEx(internet_settings, 'ProxyEnable', 0, winreg.REG_DWORD, 0)
winreg.CloseKey(internet_settings)
print("✅ 系统代理已取消")
return True
except Exception as e:
print(f"❌ 取消代理失败: {e}")
return False
def show_status():
"""显示当前代理状态"""
proxy = get_current_proxy()
print("\n当前代理状态:")
print(f" 代理已启用: {'是' if proxy['enabled'] else '否'}")
if proxy['enabled']:
print(f" 代理服务器: {proxy['server']}")
print()
def main():
if len(sys.argv) < 2:
print("=" * 50)
print(" Windows系统代理管理脚本")
print("=" * 50)
print("用法:")
print(f" {sys.argv[0]} status - 查看当前代理状态")
print(f" {sys.argv[0]} set <host> <port> - 设置代理服务器")
print(f" {sys.argv[0]} unset - 取消代理设置")
print(f" {sys.argv[0]} localhost - 快速设置为 localhost:8080")
print("\n示例:")
print(f" {sys.argv[0]} set 192.168.1.50 8080")
print(f" {sys.argv[0]} localhost")
print(f" {sys.argv[0]} unset")
print("=" * 50)
return
command = sys.argv[1].lower()
if command == 'status':
show_status()
elif command == 'set':
if len(sys.argv) < 4:
print("❌ 参数不足,请提供代理服务器地址和端口")
print(f" 示例: {sys.argv[0]} set 192.168.1.50 8080")
return
proxy_host = sys.argv[2]
proxy_port = sys.argv[3]
set_proxy(proxy_host, proxy_port)
elif command == 'unset':
unset_proxy()
elif command == 'localhost':
set_proxy('localhost', '8080')
else:
print(f"❌ 未知命令: {command}")
if __name__ == '__main__':
main()
+329 -66
View File
@@ -1,86 +1,349 @@
# -*- coding: utf-8 -*-
import socket
import threading
import select
import time
import sys
TARGET_HOST = 'superstar.geelytravel.com'
TARGET_PORT = 443
LISTEN_PORT = 8080
# Configuration
A_PORT = 8080
BROWSER_PORT = 8081
b_device_socket = None
client_socket = None
# Global state
a_device_conn = None
a_device_lock = threading.Lock()
a_device_connected = threading.Event()
def handle_b_device(conn):
"""处理B设备的连接"""
global b_device_socket
b_device_socket = conn
print(f"B设备已连接: {conn.getpeername()}")
# Request tracking
request_queue = {}
request_queue_lock = threading.Lock()
request_counter = 0
request_counter_lock = threading.Lock()
def get_thread_id():
"""Get thread identifier for logging"""
return threading.current_thread().getName()
def get_request_id():
"""Generate unique request ID"""
global request_counter
with request_counter_lock:
request_counter += 1
return "REQ-%06d" % request_counter
def log_info(source, message, line_num=0):
"""Log info message with thread ID"""
thread_id = get_thread_id()
log_line = "[%s] [INFO] [%s] [Thread:%s] %s" % (
time.strftime("%Y-%m-%d %H:%M:%S"),
source,
thread_id,
message
)
print(log_line)
sys.stdout.flush()
def log_error(source, message, line_num=0):
"""Log error message with thread ID"""
thread_id = get_thread_id()
log_line = "[%s] [ERROR] [%s] [Thread:%s] %s" % (
time.strftime("%Y-%m-%d %H:%M:%S"),
source,
thread_id,
message
)
print(log_line)
sys.stdout.flush()
def handle_a_device(conn, addr):
"""Handle device A connection - just store and hold"""
global a_device_conn
with a_device_lock:
if a_device_conn:
conn.send("ERROR: Another A device is already connected\r\n")
conn.close()
log_info("DeviceA", "Rejected connection from %s:%d" % addr)
return
a_device_conn = conn
log_info("DeviceA", "Sending PROXY_CONNECTED to %s:%d" % addr)
conn.send("PROXY_CONNECTED\r\n")
try:
while True:
data = conn.recv(4096)
if not data:
print("B设备断开连接")
b_device_socket = None
break
conn.settimeout(30)
log_info("DeviceA", "Waiting for READY from %s:%d" % addr)
response = conn.recv(1024)
log_info("DeviceA", "Received from %s:%d: %r" % (addr[0], addr[1], response))
if client_socket:
try:
client_socket.send(data)
except:
pass
if response and "READY" in response:
a_device_connected.set()
log_info("DeviceA", "Connected: %s:%d" % addr)
else:
with a_device_lock:
a_device_conn = None
conn.close()
log_info("DeviceA", "Failed to receive READY from %s:%d" % addr)
return
except Exception as e:
print(f"B设备连接出错: {e}")
b_device_socket = None
def handle_client(conn):
"""处理用户请求"""
global client_socket
client_socket = conn
print(f"用户连接: {conn.getpeername()}")
log_error("DeviceA", "Error receiving READY from %s:%d: %s" % (addr[0], addr[1], str(e)))
with a_device_lock:
a_device_conn = None
conn.close()
return
try:
while True:
data = conn.recv(4096)
if not data:
print("用户断开连接")
client_socket = None
break
event = threading.Event()
event.wait()
except:
pass
finally:
with a_device_lock:
if a_device_conn == conn:
a_device_conn = None
a_device_connected.clear()
conn.close()
log_info("DeviceA", "Disconnected")
if b_device_socket:
try:
b_device_socket.send(data)
except:
conn.send(b"HTTP/1.1 503 Service Unavailable\r\n\r\nDevice B not connected")
break
def process_response_from_a():
"""Process responses from device A and store in request queue"""
global a_device_conn
while True:
sock = None
try:
a_device_connected.wait()
with a_device_lock:
if not a_device_conn:
time.sleep(0.1)
continue
sock = a_device_conn
response = ""
while True:
chunk = sock.recv(8192)
if not chunk:
log_info("System", "Device A connection closed in response processor")
with a_device_lock:
a_device_conn = None
a_device_connected.clear()
return
response += chunk
if "\r\n\r\n" in response:
headers_end = response.find("\r\n\r\n")
headers = response[:headers_end]
request_id = None
for line in headers.split("\r\n"):
if line.lower().startswith("x-proxy-request-id:"):
request_id = line.split(":", 1)[1].strip()
break
content_length = 0
for line in headers.split("\r\n"):
if line.lower().startswith("content-length:"):
content_length = int(line.split(":", 1)[1].strip())
break
body_start = headers_end + 4
if len(response) - body_start >= content_length:
break
if request_id:
with request_queue_lock:
if request_id in request_queue:
request_queue[request_id]['response'] = response
log_info("System", "Response received for request %s" % request_id)
else:
log_error("System", "No waiting browser for request %s" % request_id)
else:
conn.send(b"HTTP/1.1 503 Service Unavailable\r\n\r\nDevice B not connected")
break
except Exception as e:
print(f"用户连接出错: {e}")
client_socket = None
log_error("System", "Response without request ID")
def run_server():
except socket.timeout:
continue
except Exception as e:
log_error("System", "Error in response processor: %s" % str(e))
time.sleep(0.1)
def handle_browser_request(browser_conn, browser_addr):
"""Handle a request from browser"""
try:
browser_conn.settimeout(30)
data = ""
while True:
chunk = browser_conn.recv(8192)
data += chunk
if "\r\n\r\n" in data:
headers_end = data.find("\r\n\r\n")
headers = data[:headers_end]
content_length = 0
for line in headers.split("\r\n"):
if line.lower().startswith("content-length:"):
content_length = int(line.split(":", 1)[1].strip())
break
body_start = headers_end + 4
if len(data) - body_start >= content_length:
break
elif chunk == "":
break
if not data:
return
request_lines = data.split("\r\n")
if request_lines:
first_line = request_lines[0]
parts = first_line.split()
if len(parts) >= 2:
method = parts[0]
path = parts[1]
body_size = len(data) - data.find("\r\n\r\n") - 4 if "\r\n\r\n" in data else 0
request_id = get_request_id()
log_info("Browser", "Request: %s %s - Body: %d bytes - ID: %s" % (method, path, body_size, request_id))
with a_device_lock:
if not a_device_conn:
error_response = "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\n\r\nDevice A not connected\r\n"
browser_conn.sendall(error_response)
log_error("Browser", "Device A not connected for request %s" % request_id)
return
with request_queue_lock:
request_queue[request_id] = {
'browser_conn': browser_conn,
'timestamp': time.time()
}
modified_data = "X-Proxy-Request-ID: " + request_id + "\r\n" + data
with a_device_lock:
try:
a_device_conn.sendall(modified_data)
log_info("Browser", "Request %s forwarded to Device A" % request_id)
except Exception as e:
log_error("Browser", "Failed to send to Device A for request %s: %s" % (request_id, str(e)))
with request_queue_lock:
if request_id in request_queue:
del request_queue[request_id]
error_response = "HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/plain\r\n\r\nFailed to forward request to Device A\r\n"
browser_conn.sendall(error_response)
return
timeout = 30
start_time = time.time()
response = None
while time.time() - start_time < timeout:
with request_queue_lock:
if request_id in request_queue and 'response' in request_queue[request_id]:
response = request_queue[request_id]['response']
del request_queue[request_id]
break
elif request_id not in request_queue:
break
time.sleep(0.1)
if response:
browser_conn.sendall(response)
log_info("Browser", "Response sent for request %s" % request_id)
else:
with request_queue_lock:
if request_id in request_queue:
del request_queue[request_id]
log_error("Browser", "Response timeout for request %s" % request_id)
error_response = "HTTP/1.1 504 Gateway Timeout\r\nContent-Type: text/plain\r\n\r\nResponse timeout\r\n"
browser_conn.sendall(error_response)
except socket.timeout:
log_error("Browser", "Request timeout from %s:%d" % browser_addr)
error_response = "HTTP/1.1 504 Gateway Timeout\r\nContent-Type: text/plain\r\n\r\nRequest timeout\r\n"
browser_conn.sendall(error_response)
except Exception as e:
log_error("Browser", "Error handling request: %s" % str(e))
with request_queue_lock:
if request_id in request_queue:
del request_queue[request_id]
def handle_browser_client(conn, addr):
"""Handle browser client connection"""
log_info("Browser", "Connected from: %s:%d" % addr)
handle_browser_request(conn, addr)
log_info("Browser", "Disconnected: %s:%d" % addr)
def run_a_server():
"""Start device A listening port"""
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('0.0.0.0', LISTEN_PORT))
server.listen(5)
print(f"A设备代理服务器已启动,监听端口 {LISTEN_PORT}")
print(f"等待B设备连接和用户请求...")
server.bind(('0.0.0.0', A_PORT))
server.listen(1)
log_info("System", "Device A port started on %d" % A_PORT)
while True:
conn, addr = server.accept()
print(f"新连接: {addr}")
# 判断是B设备还是用户(简单判断:先连接的是B设备)
if b_device_socket is None:
# 第一个连接作为B设备
t = threading.Thread(target=handle_b_device, args=(conn,))
t.start()
else:
# 后续连接作为用户
t = threading.Thread(target=handle_client, args=(conn,))
try:
conn, addr = server.accept()
t = threading.Thread(target=handle_a_device, args=(conn, addr), name="DeviceA")
t.daemon = True
t.start()
except:
break
if __name__ == '__main__':
run_server()
server.close()
def run_browser_server():
"""Start browser listening port"""
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('0.0.0.0', BROWSER_PORT))
server.listen(5)
log_info("System", "Browser port started on %d" % BROWSER_PORT)
while True:
try:
conn, addr = server.accept()
t = threading.Thread(target=handle_browser_client, args=(conn, addr), name="Browser-%d" % threading.activeCount())
t.daemon = True
t.start()
except:
break
server.close()
def main():
print("=" * 60)
print(" Proxy Server (Run on Computer B)")
print("=" * 60)
print("Device A port:", A_PORT)
print("Browser port:", BROWSER_PORT)
print("=" * 60)
print("Waiting for connections...")
print()
sys.stdout.flush()
t1 = threading.Thread(target=run_a_server)
t1.daemon = True
t1.start()
t2 = threading.Thread(target=run_browser_server)
t2.daemon = True
t2.start()
t3 = threading.Thread(target=process_response_from_a, name="ResponseProc")
t3.daemon = True
t3.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\nShutting down...")
sys.exit(0)
if __name__ == "__main__":
main()