Fix singleton implementation in Logger class and add function to check for valid HTTP status codes
This commit is contained in:
parent
83606d3a97
commit
213f23977f
|
@ -15,6 +15,9 @@ BACKLOG = 50
|
|||
class Logger:
|
||||
_instance = None
|
||||
def __init__(self):
|
||||
if self._instance is not None:
|
||||
raise Exception("Logger is a singleton!")
|
||||
|
||||
self.logger = logging.getLogger('PythonProxy')
|
||||
self.logger.setLevel(logging.DEBUG)
|
||||
|
||||
|
@ -25,16 +28,13 @@ class Logger:
|
|||
self.logger.debug('Initiating Proxy logger!')
|
||||
|
||||
def log(self, message:str):
|
||||
self.logger.debug(message)
|
||||
print('INFO:', message)
|
||||
self.logger.debug(message)
|
||||
|
||||
def critical(self, message:str):
|
||||
self.logger.critical(message)
|
||||
print('CRITICAL:', message)
|
||||
|
||||
def __del__(self):
|
||||
self.logger.close()
|
||||
|
||||
@classmethod
|
||||
def instance(self):
|
||||
if self._instance is None:
|
||||
|
@ -71,9 +71,13 @@ class Server:
|
|||
def __del__(self):
|
||||
self.sock.close()
|
||||
|
||||
def connectionHandle(client_socket, client_address):
|
||||
# print(f"Connection received from {client_address[0]}:{client_address[1]}")
|
||||
def is_valid_status_code(status_code:str):
|
||||
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)
|
||||
logger = Logger.instance()
|
||||
|
||||
|
@ -84,7 +88,6 @@ def connectionHandle(client_socket, client_address):
|
|||
try:
|
||||
raw_request = request.decode()
|
||||
except UnicodeDecodeError:
|
||||
print("UnicodeDecodeError")
|
||||
client_socket.close()
|
||||
return
|
||||
|
||||
|
@ -108,8 +111,6 @@ def connectionHandle(client_socket, client_address):
|
|||
request_port = int(request_host.split(':')[1])
|
||||
request_host = request_host.split(':')[0]
|
||||
|
||||
# print(f"REQUEST [{client_address[0]}:{client_address[1]}] {raw_request}")
|
||||
|
||||
if "monitorando" in request_url:
|
||||
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")
|
||||
|
@ -117,16 +118,12 @@ def connectionHandle(client_socket, client_address):
|
|||
client_socket.close()
|
||||
return
|
||||
|
||||
# forward the request to the destination server
|
||||
# print(f"Forwarding request to {request_host}:{request_port}")
|
||||
destination_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
destination_socket.connect((request_host, request_port))
|
||||
destination_socket.sendall(request)
|
||||
|
||||
# print(f"Waiting for response from {request_host}:{request_port}")
|
||||
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
server_socket.connect((request_host, request_port))
|
||||
server_socket.send(request)
|
||||
|
||||
while True:
|
||||
triple = select.select([client_socket, destination_socket], [], [], 20)[0]
|
||||
triple = select.select([client_socket, server_socket], [], [], 20)[0]
|
||||
if not len(triple):
|
||||
break
|
||||
try:
|
||||
|
@ -134,16 +131,17 @@ def connectionHandle(client_socket, client_address):
|
|||
data = client_socket.recv(16 * 1024)
|
||||
if not data:
|
||||
break
|
||||
destination_socket.send(data)
|
||||
if destination_socket in triple:
|
||||
data = destination_socket.recv(16 * 1024)
|
||||
server_socket.send(data)
|
||||
if server_socket in triple:
|
||||
data = server_socket.recv(16 * 1024)
|
||||
if not data:
|
||||
break
|
||||
|
||||
try:
|
||||
status_code = data.decode().split(' ')[1:]
|
||||
status_code = data.decode().split('\r\n')[0].split(' ')[1:]
|
||||
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:
|
||||
pass
|
||||
|
||||
|
@ -151,15 +149,9 @@ def connectionHandle(client_socket, client_address):
|
|||
except ConnectionAbortedError:
|
||||
break
|
||||
|
||||
# print(f"Closing connection with {request_host}:{request_port} and {client_address[0]}:{client_address[1]}")
|
||||
|
||||
# close the sockets
|
||||
destination_socket.close()
|
||||
server_socket.close()
|
||||
client_socket.close()
|
||||
|
||||
# print("Connection closed")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
ser = Server(host="0.0.0.0", port=8080)
|
||||
ser.start()
|
||||
|
|
Loading…
Reference in New Issue