切换配置
This commit is contained in:
parent
d11390e453
commit
cdfdd9b7e4
16
proxy/config.ini
Normal file
16
proxy/config.ini
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
[proxy]
|
||||||
|
# 目标服务器配置
|
||||||
|
# 协议支持: http, https
|
||||||
|
# protocol = https
|
||||||
|
# target_host = zentao.sunyard.com.cn
|
||||||
|
# target_port = 9788
|
||||||
|
|
||||||
|
# 备用配置示例(取消注释即可使用)
|
||||||
|
protocol = https
|
||||||
|
target_host = superstar.geelytravel.com
|
||||||
|
target_port = 443
|
||||||
|
|
||||||
|
# 另一个备用配置
|
||||||
|
# protocol = http
|
||||||
|
# target_host = 192.168.1.100
|
||||||
|
# target_port = 8080
|
||||||
@ -1,297 +1,128 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
import socket
|
import socket
|
||||||
import threading
|
import threading
|
||||||
import time
|
|
||||||
import sys
|
import sys
|
||||||
|
import configparser
|
||||||
|
import os
|
||||||
|
|
||||||
# Configuration
|
def load_config(config_path='config.ini'):
|
||||||
TARGET_HOST = "zentao.sunyard.com.cn"
|
"""加载配置文件"""
|
||||||
TARGET_PORT = 9788
|
config = configparser.ConfigParser()
|
||||||
B_HOST = "localhost"
|
|
||||||
B_PORT = 8080
|
|
||||||
|
|
||||||
# Global lock for socket write operations
|
# 如果配置文件不存在,创建默认配置
|
||||||
socket_write_lock = threading.Lock()
|
if not os.path.exists(config_path):
|
||||||
|
print(f"配置文件 {config_path} 不存在,使用默认配置")
|
||||||
|
return {
|
||||||
|
'protocol': 'https',
|
||||||
|
'target_host': 'zentao.sunyard.com.cn',
|
||||||
|
'target_port': 9788
|
||||||
|
}
|
||||||
|
|
||||||
def get_thread_id():
|
config.read(config_path)
|
||||||
"""Get thread identifier for logging"""
|
|
||||||
return threading.current_thread().getName()
|
|
||||||
|
|
||||||
def log_info(source, message):
|
if 'proxy' not in config:
|
||||||
"""Log info message with thread ID"""
|
print(f"配置文件格式错误,使用默认配置")
|
||||||
thread_id = get_thread_id()
|
return {
|
||||||
log_line = "[%s] [INFO] [%s] [Thread:%s] %s" % (
|
'protocol': 'https',
|
||||||
time.strftime("%Y-%m-%d %H:%M:%S"),
|
'target_host': 'zentao.sunyard.com.cn',
|
||||||
source,
|
'target_port': 9788
|
||||||
thread_id,
|
}
|
||||||
message
|
|
||||||
)
|
|
||||||
print(log_line)
|
|
||||||
sys.stdout.flush()
|
|
||||||
|
|
||||||
def log_error(source, message):
|
protocol = config['proxy'].get('protocol', 'https').lower()
|
||||||
"""Log error message with thread ID"""
|
target_host = config['proxy'].get('target_host', 'zentao.sunyard.com.cn')
|
||||||
thread_id = get_thread_id()
|
target_port = config['proxy'].getint('target_port', 9788)
|
||||||
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 target_port == 0:
|
||||||
if "\r\n\r\n" in request_data:
|
target_port = 443 if protocol == 'https' else 80
|
||||||
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):
|
return {
|
||||||
"""Modify request headers: replace Origin, Referer, Host; remove Connection headers"""
|
'protocol': protocol,
|
||||||
lines = request_data.split("\r\n")
|
'target_host': target_host,
|
||||||
new_lines = []
|
'target_port': target_port
|
||||||
method = ""
|
}
|
||||||
path = ""
|
|
||||||
|
|
||||||
if lines:
|
def handle_request(sock, target_host, target_port):
|
||||||
first_line = lines[0]
|
"""处理从A设备收到的请求,转发到目标网站"""
|
||||||
parts = first_line.split()
|
try:
|
||||||
if len(parts) >= 2:
|
# 接收来自A设备的请求
|
||||||
method = parts[0]
|
request = b""
|
||||||
path = parts[1]
|
while True:
|
||||||
|
data = sock.recv(4096)
|
||||||
|
if not data:
|
||||||
|
break
|
||||||
|
request += data
|
||||||
|
if b"\r\n\r\n" in request:
|
||||||
|
break
|
||||||
|
|
||||||
for line in lines:
|
if not request:
|
||||||
line_str = line
|
return
|
||||||
|
|
||||||
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"""
|
|
||||||
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 - Body: %d bytes - ID: %s" % (method, "http://" + TARGET_HOST + ":" + str(TARGET_PORT), path, body_size, request_id))
|
|
||||||
|
|
||||||
|
# 连接到目标网站
|
||||||
target_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
target_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
target_sock.settimeout(30)
|
target_sock.connect((target_host, target_port))
|
||||||
|
|
||||||
try:
|
# 发送请求
|
||||||
target_sock.connect((TARGET_HOST, TARGET_PORT))
|
target_sock.send(request)
|
||||||
log_info("System", "Connected to target: %s:%d" % (TARGET_HOST, TARGET_PORT))
|
|
||||||
|
|
||||||
if isinstance(modified_data, str):
|
|
||||||
modified_data = modified_data.encode('utf-8')
|
|
||||||
target_sock.sendall(modified_data)
|
|
||||||
|
|
||||||
response = b""
|
|
||||||
content_length = 0
|
|
||||||
is_chunked = False
|
|
||||||
|
|
||||||
|
# 接收响应并转发回A设备
|
||||||
while True:
|
while True:
|
||||||
chunk = target_sock.recv(8192)
|
response = target_sock.recv(4096)
|
||||||
if not chunk:
|
if not response:
|
||||||
break
|
break
|
||||||
response += chunk
|
sock.send(response)
|
||||||
|
|
||||||
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 request_id:
|
|
||||||
if b"\r\n\r\n" in response:
|
|
||||||
headers_end = response.find(b"\r\n\r\n")
|
|
||||||
headers = response[:headers_end]
|
|
||||||
body = response[headers_end:]
|
|
||||||
response = headers + ("\r\nX-Proxy-Request-ID: " + request_id).encode('utf-8') + body
|
|
||||||
|
|
||||||
status_code = "500"
|
|
||||||
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]
|
|
||||||
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)).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
|
|
||||||
finally:
|
|
||||||
target_sock.close()
|
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:
|
|
||||||
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:
|
except Exception as e:
|
||||||
log_error("System", "Failed to send response: %s" % str(e))
|
print(f"处理请求出错: {e}")
|
||||||
|
|
||||||
def listen_for_requests(sock):
|
|
||||||
"""Listen for requests from device B"""
|
|
||||||
sock.settimeout(300)
|
|
||||||
|
|
||||||
while True:
|
|
||||||
try:
|
try:
|
||||||
data = b""
|
sock.send(b"HTTP/1.1 500 Internal Server Error\r\n\r\n")
|
||||||
while True:
|
except:
|
||||||
chunk = sock.recv(8192)
|
pass
|
||||||
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
|
def connect_to_a_device(a_host, a_port, target_host, target_port):
|
||||||
for line in headers.split("\r\n"):
|
"""连接到A设备"""
|
||||||
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"""
|
|
||||||
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.settimeout(10)
|
sock.connect((a_host, a_port))
|
||||||
log_info("System", "Connecting to device B: %s:%d" % (b_host, b_port))
|
print(f"成功连接到A设备: {a_host}:{a_port}")
|
||||||
sock.connect((b_host, b_port))
|
print(f"准备转发请求到: {target_host}:{target_port}")
|
||||||
|
|
||||||
log_info("System", "Connected to device B, waiting for PROXY_CONNECTED")
|
handle_request(sock, target_host, target_port)
|
||||||
response = sock.recv(1024)
|
|
||||||
log_info("System", "Received from B: %r" % response)
|
|
||||||
|
|
||||||
if not response or b"PROXY_CONNECTED" not in response:
|
|
||||||
log_error("System", "Failed to receive connection confirmation")
|
|
||||||
sock.close()
|
sock.close()
|
||||||
time.sleep(3)
|
print("与A设备的连接已断开")
|
||||||
continue
|
except ConnectionRefusedError:
|
||||||
|
print(f"A设备未就绪,重试中...")
|
||||||
log_info("System", "Sending READY to device B")
|
import time
|
||||||
sock.sendall(b"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)
|
time.sleep(3)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log_error("System", "Unexpected error: %s" % str(e))
|
print(f"连接出错: {e}")
|
||||||
|
import time
|
||||||
time.sleep(3)
|
time.sleep(3)
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
print("=" * 60)
|
# 加载配置
|
||||||
print(" Proxy Client (Run on Computer A)")
|
config = load_config()
|
||||||
print("=" * 60)
|
|
||||||
print("Target website:", TARGET_HOST, ":", TARGET_PORT)
|
|
||||||
print("Device B address:", B_HOST, ":", B_PORT)
|
|
||||||
print("=" * 60)
|
|
||||||
sys.stdout.flush()
|
|
||||||
|
|
||||||
try:
|
# 解析命令行参数
|
||||||
connect_to_b_device(B_HOST, B_PORT)
|
if len(sys.argv) < 3:
|
||||||
except KeyboardInterrupt:
|
print("用法: python proxy_client.py <A设备IP> <A设备端口>")
|
||||||
print("\nShutting down...")
|
print(f"当前配置: {config['protocol']}://{config['target_host']}:{config['target_port']}")
|
||||||
sys.exit(0)
|
print("示例: python proxy_client.py 192.168.1.50 8080")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
if __name__ == "__main__":
|
a_host = sys.argv[1]
|
||||||
|
a_port = int(sys.argv[2])
|
||||||
|
|
||||||
|
# 可选:通过命令行覆盖目标配置
|
||||||
|
if len(sys.argv) >= 4:
|
||||||
|
config['target_host'] = sys.argv[3]
|
||||||
|
if len(sys.argv) >= 5:
|
||||||
|
config['target_port'] = int(sys.argv[4])
|
||||||
|
|
||||||
|
print(f"使用配置: {config['protocol']}://{config['target_host']}:{config['target_port']}")
|
||||||
|
connect_to_a_device(a_host, a_port, config['target_host'], config['target_port'])
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
main()
|
main()
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user