Compare commits

..

No commits in common. "be710920e9ee03ceab333149344cb422886fe0f4" and "1821ba1f2c86336ed4519b36d1dd346ffbf414c7" have entirely different histories.

3 changed files with 60 additions and 137 deletions

View File

@ -98,14 +98,9 @@ def modify_request_headers(request_data):
def handle_request(request_data): def handle_request(request_data):
"""Handle a single request from device B - completely independent thread""" """Handle a single request from device B - completely independent thread"""
if isinstance(request_data, bytes): request_id = extract_request_id(request_data)
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)
modified_data, method, path = modify_request_headers(request_data_str)
body_size = 0 body_size = 0
if "\r\n\r\n" in modified_data: if "\r\n\r\n" in modified_data:
@ -120,50 +115,40 @@ def handle_request(request_data):
target_sock.connect((TARGET_HOST, TARGET_PORT)) target_sock.connect((TARGET_HOST, TARGET_PORT))
log_info("System", "Connected to target: %s:%d" % (TARGET_HOST, TARGET_PORT)) 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) target_sock.sendall(modified_data)
response = b"" response = ""
content_length = 0
is_chunked = False
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 b"\r\n\r\n" in response and content_length == 0 and not is_chunked: if "\r\n\r\n" in response:
headers_end = response.find(b"\r\n\r\n") headers_end = response.find("\r\n\r\n")
headers = response[:headers_end].decode('utf-8', errors='replace') headers = response[:headers_end]
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())
elif line.lower().startswith("transfer-encoding:"): break
if "chunked" in line.lower():
is_chunked = True
if content_length > 0: body_start = headers_end + 4
body_start = headers_end + 4 if len(response) - body_start >= content_length:
if len(response) - body_start >= content_length: break
break
elif is_chunked:
if response.endswith(b"0\r\n\r\n"):
break
if request_id: if request_id:
if b"\r\n\r\n" in response: if "\r\n\r\n" in response:
headers_end = response.find(b"\r\n\r\n") headers_end = response.find("\r\n\r\n")
headers = response[:headers_end] status_line = response[:headers_end].split("\r\n")[0]
body = response[headers_end:] rest = response[headers_end:]
response = headers + ("\r\nX-Proxy-Request-ID: " + request_id).encode('utf-8') + body response = status_line + "\r\nX-Proxy-Request-ID: " + request_id + rest
status_code = "500" status_code = "500"
if b"\r\n\r\n" in response: if "\r\n\r\n" in response:
headers_end = response.find(b"\r\n\r\n") headers_end = response.find("\r\n\r\n")
headers = response[:headers_end].decode('utf-8', errors='replace') headers = response[:headers_end]
for line in headers.split("\r\n"): for line in headers.split("\r\n"):
if line.startswith("HTTP/"): if line.startswith("HTTP/"):
status_code = line.split()[1] status_code = line.split()[1]
@ -176,19 +161,19 @@ def handle_request(request_data):
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" % (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') 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 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").encode('utf-8') 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 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").encode('utf-8') 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 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").encode('utf-8') 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 return error_response
finally: finally:
target_sock.close() target_sock.close()
@ -199,9 +184,7 @@ 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))
@ -211,16 +194,16 @@ def listen_for_requests(sock):
while True: while True:
try: try:
data = b"" data = ""
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 b"\r\n\r\n" in data: if "\r\n\r\n" in data:
headers_end = data.find(b"\r\n\r\n") headers_end = data.find("\r\n\r\n")
headers = data[:headers_end].decode('utf-8', errors='replace') headers = data[:headers_end]
content_length = 0 content_length = 0
for line in headers.split("\r\n"): for line in headers.split("\r\n"):
@ -237,8 +220,8 @@ def listen_for_requests(sock):
t.start() t.start()
except socket.timeout: except socket.timeout:
log_info("System", "Connection idle timeout, continuing to wait") log_info("System", "Connection idle timeout")
continue return
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
@ -256,14 +239,14 @@ 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 b"PROXY_CONNECTED" not in response: if not response or "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()
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(b"READY\r\n") sock.sendall("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))
listen_for_requests(sock) listen_for_requests(sock)

View File

@ -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(b"ERROR: Another A device is already connected\r\n") conn.send("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(b"PROXY_CONNECTED\r\n") conn.send("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 b"READY" in response: if response and "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,17 +120,10 @@ def process_response_from_a():
sock = a_device_conn sock = a_device_conn
response = b"" response = ""
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
@ -138,40 +131,26 @@ def process_response_from_a():
return return
response += chunk response += chunk
if b"\r\n\r\n" in response and not headers_found: if "\r\n\r\n" in response:
headers_end = response.find(b"\r\n\r\n") headers_end = response.find("\r\n\r\n")
headers = response[:headers_end].decode('utf-8', errors='replace') headers = response[:headers_end]
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()
elif line.lower().startswith("content-length:"): 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()) content_length = int(line.split(":", 1)[1].strip())
elif line.lower().startswith("transfer-encoding:"): break
if "chunked" in line.lower():
is_chunked = True
if content_length == 0 and not is_chunked: body_start = headers_end + 4
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:
if request_id in request_queue: if request_id in request_queue:
@ -193,15 +172,13 @@ def handle_browser_request(browser_conn, browser_addr):
try: try:
browser_conn.settimeout(30) browser_conn.settimeout(30)
data = b"" data = ""
while True: while True:
chunk = browser_conn.recv(8192) chunk = browser_conn.recv(8192)
if not chunk:
break
data += chunk data += chunk
if b"\r\n\r\n" in data: if "\r\n\r\n" in data:
headers_end = data.find(b"\r\n\r\n") headers_end = data.find("\r\n\r\n")
headers = data[:headers_end].decode('utf-8', errors='replace') headers = data[:headers_end]
content_length = 0 content_length = 0
for line in headers.split("\r\n"): for line in headers.split("\r\n"):
@ -212,11 +189,13 @@ 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.decode('utf-8', errors='replace').split("\r\n") request_lines = data.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()
@ -224,14 +203,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(b"\r\n\r\n") - 4 if b"\r\n\r\n" in data else 0 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() 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 = b"HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\n\r\nDevice A not connected\r\n" 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) 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
@ -242,11 +221,7 @@ def handle_browser_request(browser_conn, browser_addr):
'timestamp': time.time() 'timestamp': time.time()
} }
if isinstance(data, bytes): modified_data = "X-Proxy-Request-ID: " + request_id + "\r\n" + data
modified_data = ("X-Proxy-Request-ID: " + request_id + "\r\n").encode('utf-8') + data
else:
modified_data = "X-Proxy-Request-ID: " + request_id + "\r\n" + data
modified_data = modified_data.encode('utf-8')
with a_device_lock: with a_device_lock:
try: try:
@ -257,7 +232,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 = b"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 = "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
@ -276,8 +251,6 @@ 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:
@ -285,12 +258,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 = b"HTTP/1.1 504 Gateway Timeout\r\nContent-Type: text/plain\r\n\r\nResponse timeout\r\n" 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) 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 = b"HTTP/1.1 504 Gateway Timeout\r\nContent-Type: text/plain\r\n\r\nRequest timeout\r\n" 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) 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))

View File

@ -1,33 +0,0 @@
# -*- 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()