Compare commits

...
13 Commits
Author SHA1 Message Date
cheney 0d0a29a465 30x 支持 2026-05-26 21:53:34 +08:00
cheney 60beb1f363 client 3 次自动退出 2026-05-26 21:50:53 +08:00
cheney 11f0f89727 ssl 支持 2026-05-26 21:46:49 +08:00
cheney 021738a8bb 回滚代码 2026-05-26 21:26:24 +08:00
cheney d11390e453 更新日志 2026-05-26 18:05:05 +08:00
cheney be710920e9 修复图片 2026-05-26 16:03:34 +08:00
cheney 6240e453b0 访问正常 2026-05-26 15:22:43 +08:00
cheney a7172bd3aa 资源类请求成功 2026-05-26 14:59:41 +08:00
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
8 changed files with 1165 additions and 234 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 ================================================
+9
View File
@@ -0,0 +1,9 @@
[proxy]
target_host = superstar.geelytravel.com
target_port = 443
target_protocol = https
; target_host = zentao.sunyard.com.cn
; target_port = 9788
; target_protocol = http
b_host = localhost
b_port = 8080
+424 -55
View File
@@ -1,80 +1,449 @@
# -*- coding: utf-8 -*-
import socket import socket
import threading import threading
import time
import sys import sys
import configparser
import os
import ssl
TARGET_HOST = 'superstar.geelytravel.com' # Configuration from config.ini
TARGET_PORT = 443 CONFIG_FILE = os.path.join(os.path.dirname(__file__), 'config.ini')
def handle_request(sock): def load_config():
"""处理从A设备收到的请求,转发到目标网站""" config = configparser.ConfigParser()
config.read(CONFIG_FILE)
target_host = config.get('proxy', 'target_host', fallback='zentao.sunyard.com.cn')
target_port = config.getint('proxy', 'target_port', fallback=9788)
target_protocol = config.get('proxy', 'target_protocol', fallback='http').lower()
b_host = config.get('proxy', 'b_host', fallback='localhost')
b_port = config.getint('proxy', 'b_port', fallback=8080)
return target_host, target_port, target_protocol, b_host, b_port
TARGET_HOST, TARGET_PORT, TARGET_PROTOCOL, B_HOST, B_PORT = load_config()
# 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: %s://%s:%d" % (TARGET_PROTOCOL, TARGET_HOST, TARGET_PORT))
elif line_str.startswith("Referer:"):
new_lines.append("Referer: %s://%s:%d/" % (TARGET_PROTOCOL, 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 = "%s://%s:%d%s" % (TARGET_PROTOCOL, 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 send_request_to_target(host, port, protocol, request_data, request_id):
"""Send request to target server and return response"""
target_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
target_sock.settimeout(30)
try: try:
# 接收来自A设备的请求 target_sock.connect((host, port))
request = b"" log_info("System", "Connected to target: %s:%d" % (host, port))
if protocol == 'https':
context = ssl.create_default_context()
target_sock = context.wrap_socket(target_sock, server_hostname=host)
log_info("System", "SSL connection established with target")
if isinstance(request_data, str):
request_data = request_data.encode('utf-8')
target_sock.sendall(request_data)
response = b""
content_length = 0
is_chunked = False
while True: while True:
data = sock.recv(4096) chunk = target_sock.recv(8192)
if not data: if not chunk:
break
request += data
if b"\r\n\r\n" in request:
break break
response += chunk
if b"\r\n\r\n" in response and content_length == 0 and not is_chunked:
headers_end = response.find(b"\r\n\r\n")
headers = response[:headers_end].decode('utf-8', errors='replace')
for line in headers.split("\r\n"):
if line.lower().startswith("content-length:"):
content_length = int(line.split(":", 1)[1].strip())
elif line.lower().startswith("transfer-encoding:"):
if "chunked" in line.lower():
is_chunked = True
if content_length > 0:
body_start = headers_end + 4
if len(response) - body_start >= content_length:
break
elif is_chunked:
if response.endswith(b"0\r\n\r\n"):
break
if not request: if request_id:
return if b"\r\n\r\n" in response:
headers_end = response.find(b"\r\n\r\n")
# 连接到目标网站 headers = response[:headers_end]
target_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) body = response[headers_end:]
target_sock.connect((TARGET_HOST, TARGET_PORT)) response = headers + ("\r\nX-Proxy-Request-ID: " + request_id).encode('utf-8') + body
# 发送请求
target_sock.send(request)
# 接收响应并转发回A设备
while True:
response = target_sock.recv(4096)
if not response:
break
sock.send(response)
return response
finally:
target_sock.close() 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): def parse_location(location):
"""连接到A设备""" """Parse Location header to get protocol, host, port, and path"""
protocol = TARGET_PROTOCOL
host = TARGET_HOST
port = TARGET_PORT
path = "/"
if location.startswith("http://") or location.startswith("https://"):
# Full URL
protocol_end = location.find("://")
protocol = location[:protocol_end]
remaining = location[protocol_end + 3:]
path_start = remaining.find("/")
if path_start == -1:
host_part = remaining
path = "/"
else:
host_part = remaining[:path_start]
path = remaining[path_start:]
port_pos = host_part.find(":")
if port_pos != -1:
host = host_part[:port_pos]
port = int(host_part[port_pos + 1:])
else:
host = host_part
port = 443 if protocol == 'https' else 80
elif location.startswith("/"):
# Absolute path
path = location
else:
# Relative path
path = "/" + location
return protocol, host, port, path
def modify_redirect_request(original_request, new_protocol, new_host, new_port, new_path):
"""Modify request for redirect"""
lines = original_request.split("\r\n")
new_lines = []
first_line = lines[0]
parts = first_line.split()
if len(parts) >= 3:
method = parts[0]
http_version = parts[2]
new_first_line = "%s %s %s" % (method, new_path, http_version)
new_lines.append(new_first_line)
for line in lines[1:]:
if not line:
continue
if line.lower().startswith("host:"):
new_lines.append("Host: %s:%d" % (new_host, new_port))
elif line.lower().startswith("origin:"):
new_lines.append("Origin: %s://%s:%d" % (new_protocol, new_host, new_port))
elif line.lower().startswith("referer:"):
new_lines.append("Referer: %s://%s:%d/" % (new_protocol, new_host, new_port))
elif line.lower().startswith("connection:"):
continue
elif line.lower().startswith("keep-alive:"):
continue
elif line.lower().startswith("proxy-connection:"):
continue
elif line.lower().startswith("x-forwarded-for:"):
continue
elif line.lower().startswith("x-proxy-request-id:"):
continue
else:
new_lines.append(line)
new_lines.append("")
new_lines.append("")
if "\r\n\r\n" in original_request:
body_start = original_request.find("\r\n\r\n") + 4
body = original_request[body_start:]
modified_data = "\r\n".join(new_lines[:-2]) + "\r\n\r\n" + body
else:
modified_data = "\r\n".join(new_lines[:-2]) + "\r\n\r\n"
return modified_data
def handle_request(request_data):
"""Handle a single request from device B - completely independent thread"""
if isinstance(request_data, bytes):
request_data_str = request_data.decode('utf-8', errors='replace')
else:
request_data_str = request_data
request_id = extract_request_id(request_data_str)
modified_data, method, path = modify_request_headers(request_data_str)
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://%s:%d%s - Body: %d bytes - ID: %s" % (method, TARGET_PROTOCOL, TARGET_HOST, TARGET_PORT, path, body_size, request_id))
current_protocol = TARGET_PROTOCOL
current_host = TARGET_HOST
current_port = TARGET_PORT
current_request = modified_data
redirect_count = 0
max_redirects = 5
try:
while redirect_count <= max_redirects:
response = send_request_to_target(current_host, current_port, current_protocol, current_request, request_id)
status_code = "500"
location = None
if b"\r\n\r\n" in response:
headers_end = response.find(b"\r\n\r\n")
headers = response[:headers_end].decode('utf-8', errors='replace')
for line in headers.split("\r\n"):
if line.startswith("HTTP/"):
status_code = line.split()[1]
elif line.lower().startswith("location:"):
location = line.split(":", 1)[1].strip()
log_info("System", "Response: %s %s - Status: %s - ID: %s" % (method, path, status_code, request_id))
if status_code not in ("301", "302") or not location:
return response
redirect_count += 1
log_info("System", "Redirect %d: %s" % (redirect_count, location))
new_protocol, new_host, new_port, new_path = parse_location(location)
current_protocol = new_protocol
current_host = new_host
current_port = new_port
current_request = modify_redirect_request(request_data_str, new_protocol, new_host, new_port, new_path)
path = new_path
log_error("System", "Too many redirects (%d)" % max_redirects)
error_response = ("HTTP/1.1 508 Loop Detected\r\nX-Proxy-Request-ID: " + (request_id if request_id else "") + "\r\nContent-Type: text/plain\r\n\r\nToo many redirects\r\n").encode('utf-8')
return error_response
except socket.error as e:
if e.errno == 111 or e.errno == 10061:
log_error("System", "Cannot connect to target: %s:%d" % (current_host, current_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" % (current_host, current_port)).encode('utf-8')
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").encode('utf-8')
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").encode('utf-8')
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").encode('utf-8')
return error_response
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:
log_info("System", "Sending response back to B, length: %d bytes" % len(response))
b_socket.sendall(response)
log_info("System", "Response sent successfully")
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 = b""
while True:
chunk = sock.recv(8192)
if not chunk:
log_info("System", "Connection closed by device B")
return
data += chunk
if b"\r\n\r\n" in data:
headers_end = data.find(b"\r\n\r\n")
headers = data[:headers_end].decode('utf-8', errors='replace')
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, continuing to wait")
continue
except Exception as e:
log_error("System", "Connection error: %s" % str(e))
return
def connect_to_b_device(b_host, b_port):
"""Connect to device B and handle requests"""
failure_count = 0
max_failures = 3
while True: while True:
try: try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((a_host, a_port)) sock.settimeout(10)
print(f"成功连接到A设备: {a_host}:{a_port}") log_info("System", "Connecting to device B: %s:%d" % (b_host, b_port))
print(f"准备转发请求到: {TARGET_HOST}:{TARGET_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() if not response or b"PROXY_CONNECTED" not in response:
print("与A设备的连接已断开") log_error("System", "Failed to receive connection confirmation")
except ConnectionRefusedError: sock.close()
print(f"A设备未就绪,重试中...") failure_count += 1
import time if failure_count >= max_failures:
log_error("System", "Maximum connection attempts reached (%d), exiting..." % max_failures)
sys.exit(1)
time.sleep(3)
continue
log_info("System", "Sending READY to device B")
sock.sendall(b"READY\r\n")
log_info("System", "Successfully connected to device B: %s:%d" % (b_host, b_port))
failure_count = 0
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))
failure_count += 1
if failure_count >= max_failures:
log_error("System", "Maximum connection attempts reached (%d), exiting..." % max_failures)
sys.exit(1)
time.sleep(3) time.sleep(3)
except Exception as e: except Exception as e:
print(f"连接出错: {e}") log_error("System", "Unexpected error: %s" % str(e))
import time failure_count += 1
if failure_count >= max_failures:
log_error("System", "Maximum connection attempts reached (%d), exiting..." % max_failures)
sys.exit(1)
time.sleep(3) time.sleep(3)
def main(): def main():
if len(sys.argv) < 3: print("=" * 60)
print("用法: python proxy_client.py <A设备IP> <A设备端口>") print(" Proxy Client (Run on Computer A)")
print("示例: python proxy_client.py 192.168.1.50 8080") print("=" * 60)
sys.exit(1) print("Target website:", TARGET_PROTOCOL, "://", TARGET_HOST, ":", TARGET_PORT)
print("Device B address:", B_HOST, ":", B_PORT)
print("=" * 60)
sys.stdout.flush()
a_host = sys.argv[1] try:
a_port = int(sys.argv[2]) connect_to_b_device(B_HOST, B_PORT)
except KeyboardInterrupt:
connect_to_a_device(a_host, a_port) print("\nShutting down...")
sys.exit(0)
if __name__ == '__main__': if __name__ == "__main__":
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()
+359 -67
View File
@@ -1,86 +1,378 @@
# -*- coding: utf-8 -*-
import socket import socket
import threading import threading
import select import time
import sys
TARGET_HOST = 'superstar.geelytravel.com' # Configuration
TARGET_PORT = 443 A_PORT = 8080
LISTEN_PORT = 8080 BROWSER_PORT = 8081
b_device_socket = None # Global state
client_socket = None a_device_conn = None
a_device_lock = threading.Lock()
a_device_connected = threading.Event()
def handle_b_device(conn): # Request tracking
"""处理B设备的连接""" request_queue = {}
global b_device_socket request_queue_lock = threading.Lock()
b_device_socket = conn request_counter = 0
print(f"B设备已连接: {conn.getpeername()}") 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(b"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(b"PROXY_CONNECTED\r\n")
try: try:
while True: conn.settimeout(30)
data = conn.recv(4096) log_info("DeviceA", "Waiting for READY from %s:%d" % addr)
if not data: response = conn.recv(1024)
print("B设备断开连接") log_info("DeviceA", "Received from %s:%d: %r" % (addr[0], addr[1], response))
b_device_socket = None
break if response and b"READY" in response:
a_device_connected.set()
if client_socket: log_info("DeviceA", "Connected: %s:%d" % addr)
try: else:
client_socket.send(data) with a_device_lock:
except: a_device_conn = None
pass conn.close()
log_info("DeviceA", "Failed to receive READY from %s:%d" % addr)
return
except Exception as e: except Exception as e:
print(f"B设备连接出错: {e}") log_error("DeviceA", "Error receiving READY from %s:%d: %s" % (addr[0], addr[1], str(e)))
b_device_socket = None with a_device_lock:
a_device_conn = None
def handle_client(conn): conn.close()
"""处理用户请求""" return
global client_socket
client_socket = conn
print(f"用户连接: {conn.getpeername()}")
try: try:
while True: event = threading.Event()
data = conn.recv(4096) event.wait()
if not data: except:
print("用户断开连接") pass
client_socket = None finally:
break with a_device_lock:
if a_device_conn == conn:
a_device_conn = None
a_device_connected.clear()
conn.close()
log_info("DeviceA", "Disconnected")
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()
if b_device_socket: with a_device_lock:
try: if not a_device_conn:
b_device_socket.send(data) time.sleep(0.1)
except: continue
conn.send(b"HTTP/1.1 503 Service Unavailable\r\n\r\nDevice B not connected")
break sock = a_device_conn
response = b""
content_length = 0
is_chunked = False
request_id = None
headers_found = False
while True:
chunk = sock.recv(8192)
if not chunk:
if response:
break
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 b"\r\n\r\n" in response and not headers_found:
headers_end = response.find(b"\r\n\r\n")
headers = response[:headers_end].decode('utf-8', errors='replace')
headers_found = True
for line in headers.split("\r\n"):
if line.lower().startswith("x-proxy-request-id:"):
request_id = line.split(":", 1)[1].strip()
elif line.lower().startswith("content-length:"):
content_length = int(line.split(":", 1)[1].strip())
elif line.lower().startswith("transfer-encoding:"):
if "chunked" in line.lower():
is_chunked = True
if content_length == 0 and not is_chunked:
break
if content_length > 0:
body_start = headers_end + 4
if len(response) - body_start >= content_length:
break
elif is_chunked:
if response.endswith(b"0\r\n\r\n"):
break
elif headers_found:
if content_length > 0:
headers_end = response.find(b"\r\n\r\n")
body_start = headers_end + 4
if len(response) - body_start >= content_length:
break
elif is_chunked:
if response.endswith(b"0\r\n\r\n"):
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: else:
conn.send(b"HTTP/1.1 503 Service Unavailable\r\n\r\nDevice B not connected") log_error("System", "Response without request ID")
break
except Exception as e: except socket.timeout:
print(f"用户连接出错: {e}") continue
client_socket = None except Exception as e:
log_error("System", "Error in response processor: %s" % str(e))
time.sleep(0.1)
def run_server(): def handle_browser_request(browser_conn, browser_addr):
"""Handle a request from browser"""
try:
browser_conn.settimeout(30)
data = b""
while True:
chunk = browser_conn.recv(8192)
if not chunk:
break
data += chunk
if b"\r\n\r\n" in data:
headers_end = data.find(b"\r\n\r\n")
headers = data[:headers_end].decode('utf-8', errors='replace')
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
if not data:
return
request_lines = data.decode('utf-8', errors='replace').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(b"\r\n\r\n") - 4 if b"\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 = b"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()
}
if b"\r\n\r\n" in data:
headers_end = data.find(b"\r\n\r\n")
headers = data[:headers_end]
body = data[headers_end:]
modified_data = headers + ("\r\nX-Proxy-Request-ID: " + request_id).encode('utf-8') + body
else:
modified_data = data + ("\r\nX-Proxy-Request-ID: " + request_id + "\r\n\r\n").encode('utf-8')
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 = b"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:
if isinstance(response, str):
response = response.encode('utf-8')
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 = b"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 = b"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 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('0.0.0.0', LISTEN_PORT)) server.bind(('0.0.0.0', A_PORT))
server.listen(5) server.listen(1)
log_info("System", "Device A port started on %d" % A_PORT)
print(f"A设备代理服务器已启动,监听端口 {LISTEN_PORT}")
print(f"等待B设备连接和用户请求...")
while True: while True:
conn, addr = server.accept() try:
print(f"新连接: {addr}") conn, addr = server.accept()
t = threading.Thread(target=handle_a_device, args=(conn, addr), name="DeviceA")
# 判断是B设备还是用户(简单判断:先连接的是B设备) t.daemon = True
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,))
t.start() t.start()
except:
break
server.close()
if __name__ == '__main__': def run_browser_server():
run_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()
+33
View File
@@ -0,0 +1,33 @@
# -*- coding: utf-8 -*-
import socket
import threading
def handle_client(conn, addr):
try:
data = conn.recv(8192)
if data:
lines = data.split("\r\n")
if lines:
method, path, _ = lines[0].split()
print("[%s:%d] %s %s" % (addr[0], addr[1], method, path))
response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 48\r\n\r\n<html><body>Hello from test server!</body></html>"
conn.sendall(response)
finally:
conn.close()
def main():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('127.0.0.1', 8888))
server.listen(5)
print("Test server running on 127.0.0.1:8888")
while True:
conn, addr = server.accept()
t = threading.Thread(target=handle_client, args=(conn, addr))
t.daemon = True
t.start()
if __name__ == "__main__":
main()