Fix singleton implementation in Logger class and add function to check for valid HTTP status codes

This commit is contained in:
José Henrique 2023-11-16 21:51:08 -03:00
parent 83606d3a97
commit 213f23977f
1 changed files with 21 additions and 29 deletions

View File

@ -15,6 +15,9 @@ BACKLOG = 50
class Logger: class Logger:
_instance = None _instance = None
def __init__(self): def __init__(self):
if self._instance is not None:
raise Exception("Logger is a singleton!")
self.logger = logging.getLogger('PythonProxy') self.logger = logging.getLogger('PythonProxy')
self.logger.setLevel(logging.DEBUG) self.logger.setLevel(logging.DEBUG)
@ -25,16 +28,13 @@ class Logger:
self.logger.debug('Initiating Proxy logger!') self.logger.debug('Initiating Proxy logger!')
def log(self, message:str): def log(self, message:str):
self.logger.debug(message)
print('INFO:', message) print('INFO:', message)
self.logger.debug(message)
def critical(self, message:str): def critical(self, message:str):
self.logger.critical(message) self.logger.critical(message)
print('CRITICAL:', message) print('CRITICAL:', message)
def __del__(self):
self.logger.close()
@classmethod @classmethod
def instance(self): def instance(self):
if self._instance is None: if self._instance is None:
@ -71,9 +71,13 @@ class Server:
def __del__(self): def __del__(self):
self.sock.close() self.sock.close()
def connectionHandle(client_socket, client_address): def is_valid_status_code(status_code:str):
# print(f"Connection received from {client_address[0]}:{client_address[1]}") valid_starts = [str(i) for i in range(5)]
if status_code.startswith(tuple(valid_starts)):
return True
return False
def connectionHandle(client_socket, client_address):
request = client_socket.recv(16 * 1024) request = client_socket.recv(16 * 1024)
logger = Logger.instance() logger = Logger.instance()
@ -84,7 +88,6 @@ def connectionHandle(client_socket, client_address):
try: try:
raw_request = request.decode() raw_request = request.decode()
except UnicodeDecodeError: except UnicodeDecodeError:
print("UnicodeDecodeError")
client_socket.close() client_socket.close()
return return
@ -108,8 +111,6 @@ def connectionHandle(client_socket, client_address):
request_port = int(request_host.split(':')[1]) request_port = int(request_host.split(':')[1])
request_host = request_host.split(':')[0] request_host = request_host.split(':')[0]
# print(f"REQUEST [{client_address[0]}:{client_address[1]}] {raw_request}")
if "monitorando" in request_url: if "monitorando" in request_url:
body = "<HTML><HEAD><TITLE>403</TITLE><meta charset=\"UTF-8\"></HEAD> <BODY>Acesso não autorizado!</BODY> </HTML>" body = "<HTML><HEAD><TITLE>403</TITLE><meta charset=\"UTF-8\"></HEAD> <BODY>Acesso não autorizado!</BODY> </HTML>"
client_socket.sendall(b"HTTP/1.1 403 Forbidden\r\n\r\n") client_socket.sendall(b"HTTP/1.1 403 Forbidden\r\n\r\n")
@ -117,16 +118,12 @@ def connectionHandle(client_socket, client_address):
client_socket.close() client_socket.close()
return return
# forward the request to the destination server server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# print(f"Forwarding request to {request_host}:{request_port}") server_socket.connect((request_host, request_port))
destination_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.send(request)
destination_socket.connect((request_host, request_port))
destination_socket.sendall(request)
# print(f"Waiting for response from {request_host}:{request_port}")
while True: while True:
triple = select.select([client_socket, destination_socket], [], [], 20)[0] triple = select.select([client_socket, server_socket], [], [], 20)[0]
if not len(triple): if not len(triple):
break break
try: try:
@ -134,16 +131,17 @@ def connectionHandle(client_socket, client_address):
data = client_socket.recv(16 * 1024) data = client_socket.recv(16 * 1024)
if not data: if not data:
break break
destination_socket.send(data) server_socket.send(data)
if destination_socket in triple: if server_socket in triple:
data = destination_socket.recv(16 * 1024) data = server_socket.recv(16 * 1024)
if not data: if not data:
break break
try: try:
status_code = data.decode().split(' ')[1:] status_code = data.decode().split('\r\n')[0].split(' ')[1:]
status_code = ' '.join(status_code) status_code = ' '.join(status_code)
logger.log(f"REQUEST [{client_address[0]}:{client_address[1]}] to [{request_host}:{request_port}] - {status_code} ({len(data)} bytes)") if is_valid_status_code(status_code):
logger.log(f"REQUEST [{client_address[0]}:{client_address[1]}] to [{request_host}:{request_port}] - {status_code}")
except UnicodeDecodeError: except UnicodeDecodeError:
pass pass
@ -151,15 +149,9 @@ def connectionHandle(client_socket, client_address):
except ConnectionAbortedError: except ConnectionAbortedError:
break break
# print(f"Closing connection with {request_host}:{request_port} and {client_address[0]}:{client_address[1]}") server_socket.close()
# close the sockets
destination_socket.close()
client_socket.close() client_socket.close()
# print("Connection closed")
if __name__ == '__main__': if __name__ == '__main__':
ser = Server(host="0.0.0.0", port=8080) ser = Server(host="0.0.0.0", port=8080)
ser.start() ser.start()