Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d0a29a465 | ||
|
|
60beb1f363 | ||
|
|
11f0f89727 | ||
|
|
021738a8bb | ||
|
|
d11390e453 | ||
|
|
be710920e9 | ||
|
|
6240e453b0 | ||
|
|
a7172bd3aa |
@@ -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
|
||||||
+233
-64
@@ -3,12 +3,26 @@ import socket
|
|||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
import sys
|
import sys
|
||||||
|
import configparser
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
|
||||||
# Configuration
|
# Configuration from config.ini
|
||||||
TARGET_HOST = "zentao.sunyard.com.cn"
|
CONFIG_FILE = os.path.join(os.path.dirname(__file__), 'config.ini')
|
||||||
TARGET_PORT = 9788
|
|
||||||
B_HOST = "localhost"
|
def load_config():
|
||||||
B_PORT = 8080
|
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
|
# Global lock for socket write operations
|
||||||
socket_write_lock = threading.Lock()
|
socket_write_lock = threading.Lock()
|
||||||
@@ -69,9 +83,9 @@ def modify_request_headers(request_data):
|
|||||||
line_str = line
|
line_str = line
|
||||||
|
|
||||||
if line_str.startswith("Origin:"):
|
if line_str.startswith("Origin:"):
|
||||||
new_lines.append("Origin: http://%s:%d" % (TARGET_HOST, TARGET_PORT))
|
new_lines.append("Origin: %s://%s:%d" % (TARGET_PROTOCOL, TARGET_HOST, TARGET_PORT))
|
||||||
elif line_str.startswith("Referer:"):
|
elif line_str.startswith("Referer:"):
|
||||||
new_lines.append("Referer: http://%s:%d/" % (TARGET_HOST, TARGET_PORT))
|
new_lines.append("Referer: %s://%s:%d/" % (TARGET_PROTOCOL, TARGET_HOST, TARGET_PORT))
|
||||||
elif line_str.startswith("Host:"):
|
elif line_str.startswith("Host:"):
|
||||||
new_lines.append("Host: %s:%d" % (TARGET_HOST, TARGET_PORT))
|
new_lines.append("Host: %s:%d" % (TARGET_HOST, TARGET_PORT))
|
||||||
elif line_str.lower().startswith("connection:"):
|
elif line_str.lower().startswith("connection:"):
|
||||||
@@ -90,93 +104,230 @@ def modify_request_headers(request_data):
|
|||||||
modified_data = "\r\n".join(new_lines)
|
modified_data = "\r\n".join(new_lines)
|
||||||
|
|
||||||
if path.startswith("/"):
|
if path.startswith("/"):
|
||||||
new_path = "http://%s:%d%s" % (TARGET_HOST, TARGET_PORT, path)
|
new_path = "%s://%s:%d%s" % (TARGET_PROTOCOL, TARGET_HOST, TARGET_PORT, path)
|
||||||
if method and modified_data:
|
if method and modified_data:
|
||||||
modified_data = modified_data.replace(path, new_path, 1)
|
modified_data = modified_data.replace(path, new_path, 1)
|
||||||
|
|
||||||
return modified_data, method, path
|
return modified_data, method, path
|
||||||
|
|
||||||
def handle_request(request_data):
|
def send_request_to_target(host, port, protocol, request_data, request_id):
|
||||||
"""Handle a single request from device B - completely independent thread"""
|
"""Send request to target server and return response"""
|
||||||
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 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
target_sock.settimeout(30)
|
target_sock.settimeout(30)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
target_sock.connect((TARGET_HOST, TARGET_PORT))
|
target_sock.connect((host, port))
|
||||||
log_info("System", "Connected to target: %s:%d" % (TARGET_HOST, TARGET_PORT))
|
log_info("System", "Connected to target: %s:%d" % (host, port))
|
||||||
|
|
||||||
target_sock.sendall(modified_data)
|
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
|
||||||
|
|
||||||
response = ""
|
|
||||||
while True:
|
while True:
|
||||||
chunk = target_sock.recv(8192)
|
chunk = target_sock.recv(8192)
|
||||||
if not chunk:
|
if not chunk:
|
||||||
break
|
break
|
||||||
response += chunk
|
response += chunk
|
||||||
|
|
||||||
if "\r\n\r\n" in response:
|
if b"\r\n\r\n" in response and content_length == 0 and not is_chunked:
|
||||||
headers_end = response.find("\r\n\r\n")
|
headers_end = response.find(b"\r\n\r\n")
|
||||||
headers = response[:headers_end]
|
headers = response[:headers_end].decode('utf-8', errors='replace')
|
||||||
|
|
||||||
content_length = 0
|
|
||||||
for line in headers.split("\r\n"):
|
for line in headers.split("\r\n"):
|
||||||
if line.lower().startswith("content-length:"):
|
if line.lower().startswith("content-length:"):
|
||||||
content_length = int(line.split(":", 1)[1].strip())
|
content_length = int(line.split(":", 1)[1].strip())
|
||||||
break
|
elif line.lower().startswith("transfer-encoding:"):
|
||||||
|
if "chunked" in line.lower():
|
||||||
|
is_chunked = True
|
||||||
|
|
||||||
body_start = headers_end + 4
|
if content_length > 0:
|
||||||
if len(response) - body_start >= content_length:
|
body_start = headers_end + 4
|
||||||
break
|
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 request_id:
|
||||||
if "\r\n\r\n" in response:
|
if b"\r\n\r\n" in response:
|
||||||
headers_end = response.find("\r\n\r\n")
|
headers_end = response.find(b"\r\n\r\n")
|
||||||
status_line = response[:headers_end].split("\r\n")[0]
|
headers = response[:headers_end]
|
||||||
rest = response[headers_end:]
|
body = response[headers_end:]
|
||||||
response = status_line + "\r\nX-Proxy-Request-ID: " + request_id + rest
|
response = headers + ("\r\nX-Proxy-Request-ID: " + request_id).encode('utf-8') + body
|
||||||
|
|
||||||
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
|
return response
|
||||||
|
|
||||||
|
finally:
|
||||||
|
target_sock.close()
|
||||||
|
|
||||||
|
def parse_location(location):
|
||||||
|
"""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:
|
except socket.error as e:
|
||||||
if e.errno == 111 or e.errno == 10061:
|
if e.errno == 111 or e.errno == 10061:
|
||||||
log_error("System", "Cannot connect to target: %s:%d" % (TARGET_HOST, TARGET_PORT))
|
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" % (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" % (current_host, current_port)).encode('utf-8')
|
||||||
return error_response
|
return error_response
|
||||||
else:
|
else:
|
||||||
log_error("System", "Socket error: %s" % str(e))
|
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"
|
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
|
return error_response
|
||||||
except socket.timeout:
|
except socket.timeout:
|
||||||
log_error("System", "Target connection 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"
|
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
|
return error_response
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log_error("System", "Error handling request: %s" % str(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"
|
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
|
return error_response
|
||||||
finally:
|
|
||||||
target_sock.close()
|
|
||||||
|
|
||||||
def process_request(b_socket, request_data):
|
def process_request(b_socket, request_data):
|
||||||
"""Process a request in separate thread and send response back"""
|
"""Process a request in separate thread and send response back"""
|
||||||
@@ -184,7 +335,9 @@ def process_request(b_socket, request_data):
|
|||||||
|
|
||||||
with socket_write_lock:
|
with socket_write_lock:
|
||||||
try:
|
try:
|
||||||
|
log_info("System", "Sending response back to B, length: %d bytes" % len(response))
|
||||||
b_socket.sendall(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))
|
log_error("System", "Failed to send response: %s" % str(e))
|
||||||
|
|
||||||
@@ -194,16 +347,16 @@ def listen_for_requests(sock):
|
|||||||
|
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
data = ""
|
data = b""
|
||||||
while True:
|
while True:
|
||||||
chunk = sock.recv(8192)
|
chunk = sock.recv(8192)
|
||||||
if not chunk:
|
if not chunk:
|
||||||
log_info("System", "Connection closed by device B")
|
log_info("System", "Connection closed by device B")
|
||||||
return
|
return
|
||||||
data += chunk
|
data += chunk
|
||||||
if "\r\n\r\n" in data:
|
if b"\r\n\r\n" in data:
|
||||||
headers_end = data.find("\r\n\r\n")
|
headers_end = data.find(b"\r\n\r\n")
|
||||||
headers = data[:headers_end]
|
headers = data[:headers_end].decode('utf-8', errors='replace')
|
||||||
|
|
||||||
content_length = 0
|
content_length = 0
|
||||||
for line in headers.split("\r\n"):
|
for line in headers.split("\r\n"):
|
||||||
@@ -220,14 +373,17 @@ def listen_for_requests(sock):
|
|||||||
t.start()
|
t.start()
|
||||||
|
|
||||||
except socket.timeout:
|
except socket.timeout:
|
||||||
log_info("System", "Connection idle timeout")
|
log_info("System", "Connection idle timeout, continuing to wait")
|
||||||
return
|
continue
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log_error("System", "Connection error: %s" % str(e))
|
log_error("System", "Connection error: %s" % str(e))
|
||||||
return
|
return
|
||||||
|
|
||||||
def connect_to_b_device(b_host, b_port):
|
def connect_to_b_device(b_host, b_port):
|
||||||
"""Connect to device B and handle requests"""
|
"""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)
|
||||||
@@ -239,16 +395,21 @@ def connect_to_b_device(b_host, b_port):
|
|||||||
response = sock.recv(1024)
|
response = sock.recv(1024)
|
||||||
log_info("System", "Received from B: %r" % response)
|
log_info("System", "Received from B: %r" % response)
|
||||||
|
|
||||||
if not response or "PROXY_CONNECTED" not in response:
|
if not response or b"PROXY_CONNECTED" not in response:
|
||||||
log_error("System", "Failed to receive connection confirmation")
|
log_error("System", "Failed to receive connection confirmation")
|
||||||
sock.close()
|
sock.close()
|
||||||
|
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)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
log_info("System", "Sending READY to device B")
|
log_info("System", "Sending READY to device B")
|
||||||
sock.sendall("READY\r\n")
|
sock.sendall(b"READY\r\n")
|
||||||
log_info("System", "Successfully connected to device B: %s:%d" % (b_host, b_port))
|
log_info("System", "Successfully connected to device B: %s:%d" % (b_host, b_port))
|
||||||
|
|
||||||
|
failure_count = 0
|
||||||
listen_for_requests(sock)
|
listen_for_requests(sock)
|
||||||
|
|
||||||
except socket.error as e:
|
except socket.error as e:
|
||||||
@@ -256,16 +417,24 @@ def connect_to_b_device(b_host, b_port):
|
|||||||
log_info("System", "Device B not ready (%s:%d), retrying in 3 seconds..." % (b_host, b_port))
|
log_info("System", "Device B not ready (%s:%d), retrying in 3 seconds..." % (b_host, b_port))
|
||||||
else:
|
else:
|
||||||
log_error("System", "Connection error: %s" % str(e))
|
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:
|
||||||
log_error("System", "Unexpected error: %s" % str(e))
|
log_error("System", "Unexpected 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)
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print(" Proxy Client (Run on Computer A)")
|
print(" Proxy Client (Run on Computer A)")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print("Target website:", TARGET_HOST, ":", TARGET_PORT)
|
print("Target website:", TARGET_PROTOCOL, "://", TARGET_HOST, ":", TARGET_PORT)
|
||||||
print("Device B address:", B_HOST, ":", B_PORT)
|
print("Device B address:", B_HOST, ":", B_PORT)
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
sys.stdout.flush()
|
sys.stdout.flush()
|
||||||
|
|||||||
+58
-29
@@ -60,7 +60,7 @@ def handle_a_device(conn, addr):
|
|||||||
|
|
||||||
with a_device_lock:
|
with a_device_lock:
|
||||||
if a_device_conn:
|
if a_device_conn:
|
||||||
conn.send("ERROR: Another A device is already connected\r\n")
|
conn.send(b"ERROR: Another A device is already connected\r\n")
|
||||||
conn.close()
|
conn.close()
|
||||||
log_info("DeviceA", "Rejected connection from %s:%d" % addr)
|
log_info("DeviceA", "Rejected connection from %s:%d" % addr)
|
||||||
return
|
return
|
||||||
@@ -68,7 +68,7 @@ def handle_a_device(conn, addr):
|
|||||||
a_device_conn = conn
|
a_device_conn = conn
|
||||||
|
|
||||||
log_info("DeviceA", "Sending PROXY_CONNECTED to %s:%d" % addr)
|
log_info("DeviceA", "Sending PROXY_CONNECTED to %s:%d" % addr)
|
||||||
conn.send("PROXY_CONNECTED\r\n")
|
conn.send(b"PROXY_CONNECTED\r\n")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
conn.settimeout(30)
|
conn.settimeout(30)
|
||||||
@@ -76,7 +76,7 @@ def handle_a_device(conn, addr):
|
|||||||
response = conn.recv(1024)
|
response = conn.recv(1024)
|
||||||
log_info("DeviceA", "Received from %s:%d: %r" % (addr[0], addr[1], response))
|
log_info("DeviceA", "Received from %s:%d: %r" % (addr[0], addr[1], response))
|
||||||
|
|
||||||
if response and "READY" in response:
|
if response and b"READY" in response:
|
||||||
a_device_connected.set()
|
a_device_connected.set()
|
||||||
log_info("DeviceA", "Connected: %s:%d" % addr)
|
log_info("DeviceA", "Connected: %s:%d" % addr)
|
||||||
else:
|
else:
|
||||||
@@ -120,10 +120,17 @@ def process_response_from_a():
|
|||||||
|
|
||||||
sock = a_device_conn
|
sock = a_device_conn
|
||||||
|
|
||||||
response = ""
|
response = b""
|
||||||
|
content_length = 0
|
||||||
|
is_chunked = False
|
||||||
|
request_id = None
|
||||||
|
headers_found = False
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
chunk = sock.recv(8192)
|
chunk = sock.recv(8192)
|
||||||
if not chunk:
|
if not chunk:
|
||||||
|
if response:
|
||||||
|
break
|
||||||
log_info("System", "Device A connection closed in response processor")
|
log_info("System", "Device A connection closed in response processor")
|
||||||
with a_device_lock:
|
with a_device_lock:
|
||||||
a_device_conn = None
|
a_device_conn = None
|
||||||
@@ -131,25 +138,39 @@ def process_response_from_a():
|
|||||||
return
|
return
|
||||||
response += chunk
|
response += chunk
|
||||||
|
|
||||||
if "\r\n\r\n" in response:
|
if b"\r\n\r\n" in response and not headers_found:
|
||||||
headers_end = response.find("\r\n\r\n")
|
headers_end = response.find(b"\r\n\r\n")
|
||||||
headers = response[:headers_end]
|
headers = response[:headers_end].decode('utf-8', errors='replace')
|
||||||
|
headers_found = True
|
||||||
|
|
||||||
request_id = None
|
|
||||||
for line in headers.split("\r\n"):
|
for line in headers.split("\r\n"):
|
||||||
if line.lower().startswith("x-proxy-request-id:"):
|
if line.lower().startswith("x-proxy-request-id:"):
|
||||||
request_id = line.split(":", 1)[1].strip()
|
request_id = line.split(":", 1)[1].strip()
|
||||||
break
|
elif line.lower().startswith("content-length:"):
|
||||||
|
|
||||||
content_length = 0
|
|
||||||
for line in headers.split("\r\n"):
|
|
||||||
if line.lower().startswith("content-length:"):
|
|
||||||
content_length = int(line.split(":", 1)[1].strip())
|
content_length = int(line.split(":", 1)[1].strip())
|
||||||
break
|
elif line.lower().startswith("transfer-encoding:"):
|
||||||
|
if "chunked" in line.lower():
|
||||||
|
is_chunked = True
|
||||||
|
|
||||||
body_start = headers_end + 4
|
if content_length == 0 and not is_chunked:
|
||||||
if len(response) - body_start >= content_length:
|
|
||||||
break
|
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:
|
if request_id:
|
||||||
with request_queue_lock:
|
with request_queue_lock:
|
||||||
@@ -172,13 +193,15 @@ def handle_browser_request(browser_conn, browser_addr):
|
|||||||
try:
|
try:
|
||||||
browser_conn.settimeout(30)
|
browser_conn.settimeout(30)
|
||||||
|
|
||||||
data = ""
|
data = b""
|
||||||
while True:
|
while True:
|
||||||
chunk = browser_conn.recv(8192)
|
chunk = browser_conn.recv(8192)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
data += chunk
|
data += chunk
|
||||||
if "\r\n\r\n" in data:
|
if b"\r\n\r\n" in data:
|
||||||
headers_end = data.find("\r\n\r\n")
|
headers_end = data.find(b"\r\n\r\n")
|
||||||
headers = data[:headers_end]
|
headers = data[:headers_end].decode('utf-8', errors='replace')
|
||||||
|
|
||||||
content_length = 0
|
content_length = 0
|
||||||
for line in headers.split("\r\n"):
|
for line in headers.split("\r\n"):
|
||||||
@@ -189,13 +212,11 @@ def handle_browser_request(browser_conn, browser_addr):
|
|||||||
body_start = headers_end + 4
|
body_start = headers_end + 4
|
||||||
if len(data) - body_start >= content_length:
|
if len(data) - body_start >= content_length:
|
||||||
break
|
break
|
||||||
elif chunk == "":
|
|
||||||
break
|
|
||||||
|
|
||||||
if not data:
|
if not data:
|
||||||
return
|
return
|
||||||
|
|
||||||
request_lines = data.split("\r\n")
|
request_lines = data.decode('utf-8', errors='replace').split("\r\n")
|
||||||
if request_lines:
|
if request_lines:
|
||||||
first_line = request_lines[0]
|
first_line = request_lines[0]
|
||||||
parts = first_line.split()
|
parts = first_line.split()
|
||||||
@@ -203,14 +224,14 @@ def handle_browser_request(browser_conn, browser_addr):
|
|||||||
method = parts[0]
|
method = parts[0]
|
||||||
path = parts[1]
|
path = parts[1]
|
||||||
|
|
||||||
body_size = len(data) - data.find("\r\n\r\n") - 4 if "\r\n\r\n" in data else 0
|
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()
|
request_id = get_request_id()
|
||||||
log_info("Browser", "Request: %s %s - Body: %d bytes - ID: %s" % (method, path, body_size, request_id))
|
log_info("Browser", "Request: %s %s - Body: %d bytes - ID: %s" % (method, path, body_size, request_id))
|
||||||
|
|
||||||
with a_device_lock:
|
with a_device_lock:
|
||||||
if not a_device_conn:
|
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"
|
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)
|
browser_conn.sendall(error_response)
|
||||||
log_error("Browser", "Device A not connected for request %s" % request_id)
|
log_error("Browser", "Device A not connected for request %s" % request_id)
|
||||||
return
|
return
|
||||||
@@ -221,7 +242,13 @@ def handle_browser_request(browser_conn, browser_addr):
|
|||||||
'timestamp': time.time()
|
'timestamp': time.time()
|
||||||
}
|
}
|
||||||
|
|
||||||
modified_data = "X-Proxy-Request-ID: " + request_id + "\r\n" + data
|
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:
|
with a_device_lock:
|
||||||
try:
|
try:
|
||||||
@@ -232,7 +259,7 @@ def handle_browser_request(browser_conn, browser_addr):
|
|||||||
with request_queue_lock:
|
with request_queue_lock:
|
||||||
if request_id in request_queue:
|
if request_id in request_queue:
|
||||||
del request_queue[request_id]
|
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"
|
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)
|
browser_conn.sendall(error_response)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -251,6 +278,8 @@ def handle_browser_request(browser_conn, browser_addr):
|
|||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
|
|
||||||
if response:
|
if response:
|
||||||
|
if isinstance(response, str):
|
||||||
|
response = response.encode('utf-8')
|
||||||
browser_conn.sendall(response)
|
browser_conn.sendall(response)
|
||||||
log_info("Browser", "Response sent for request %s" % request_id)
|
log_info("Browser", "Response sent for request %s" % request_id)
|
||||||
else:
|
else:
|
||||||
@@ -258,12 +287,12 @@ def handle_browser_request(browser_conn, browser_addr):
|
|||||||
if request_id in request_queue:
|
if request_id in request_queue:
|
||||||
del request_queue[request_id]
|
del request_queue[request_id]
|
||||||
log_error("Browser", "Response timeout for request %s" % 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"
|
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)
|
browser_conn.sendall(error_response)
|
||||||
|
|
||||||
except socket.timeout:
|
except socket.timeout:
|
||||||
log_error("Browser", "Request timeout from %s:%d" % browser_addr)
|
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"
|
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)
|
browser_conn.sendall(error_response)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log_error("Browser", "Error handling request: %s" % str(e))
|
log_error("Browser", "Error handling request: %s" % str(e))
|
||||||
|
|||||||
@@ -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()
|
||||||
Reference in New Issue
Block a user