cn-py-serv/server/main.py

234 lines
7.4 KiB
Python
Raw Normal View History

2023-12-29 02:13:10 +03:00
import threading
2023-12-22 02:48:34 +03:00
import socket
import logging
2023-12-29 02:13:10 +03:00
import config
from .file_read import fileiter
from .response import Response
2023-12-22 02:48:34 +03:00
MAX_REQLINE = 64 * 1024
2023-12-29 02:13:10 +03:00
class HTTPHandler:
def __init__(self, conn, addr):
self.conn = conn
self.addr = addr
2023-12-22 02:48:34 +03:00
2023-12-29 02:13:10 +03:00
self.read_fb = conn.makefile("rb")
self.write_fb = conn.makefile("wb")
2023-12-22 02:48:34 +03:00
self.http_type = ""
self.http_address = ""
self.http_get_request = {}
self.http_headers = {}
self.data = b""
2023-12-29 02:13:10 +03:00
self.pre_handle_connection()
2023-12-22 02:48:34 +03:00
2023-12-29 02:13:10 +03:00
def pre_handle_connection(self):
"""
Chain of handle first line in HTTP request
"""
2023-12-29 02:13:10 +03:00
raw = self.read_fb.readline(MAX_REQLINE + 1)
2023-12-22 02:48:34 +03:00
2023-12-29 02:13:10 +03:00
if len(raw) > MAX_REQLINE:
logging.debug("Request line too long")
self.conn.send(b"")
self.conn.close()
return
2023-12-22 02:48:34 +03:00
2023-12-29 02:13:10 +03:00
req_line = raw.decode().rstrip("\r\n")
req_line_splited = req_line.split(" ")
2023-12-22 02:48:34 +03:00
2023-12-29 02:13:10 +03:00
if len(req_line_splited) != 3:
if len(req_line_splited) > 3:
logging.debug("Request head too long")
else:
logging.debug("Request head too small")
2023-12-29 02:13:10 +03:00
self.conn.send(b"")
self.conn.close()
return
2023-12-22 02:48:34 +03:00
2023-12-29 02:13:10 +03:00
if req_line_splited[2] == "HTTP/1.0" or req_line_splited[2] == "HTTP/1.1":
self.http_type = req_line_splited[0]
else:
self.conn.send(b"")
self.conn.close()
return
if req_line_splited[0] == "GET" and req_line_splited[1].find("?") >= 0:
addr, get_req = req_line_splited[1].split("?", 1)
self.http_address = addr
for param in get_req.split("&"):
if len(param) == 0:
continue
elif param.find("=") >= 0:
name, val = param.split("=", 1)
else:
name, val = (param, "")
self.http_get_request.update({name: val})
else:
self.http_address = req_line_splited[1]
self.http_get_request = {}
self.http_header_handle()
2023-12-22 02:48:34 +03:00
2023-12-29 02:13:10 +03:00
def http_header_handle(self):
"""
Chain of handle headers in HTTP request
"""
2023-12-22 02:48:34 +03:00
while True:
2023-12-29 02:13:10 +03:00
raw = self.read_fb.readline(MAX_REQLINE + 1)
if len(raw) > MAX_REQLINE:
logging.debug("Request header line too long")
self.conn.send(b"")
self.conn.close()
return
if raw == b"":
self.conn.send(b"")
self.conn.close()
return
if raw == b"\r\n":
self.http_data_handle()
break
else:
decoded_data = raw.decode("UTF-8").rstrip("\r\n")
decoded_data_split = decoded_data.split(":", 1)
self.http_headers.update({decoded_data_split[0]: decoded_data_split[1].strip(" ")})
2023-12-29 02:13:10 +03:00
def http_data_handle(self):
"""
Chain of receive data partitions HTTP request
2023-12-29 02:13:10 +03:00
"""
# TODO: Get from headers Content-Length and get body of request, else receive 1024 bytes
"""
2023-12-29 02:13:10 +03:00
raw = self.read_fb.readline(1024)
if len(raw) == 1024:
while True:
self.data += raw
if len(raw) < 1024:
break
else:
raw = self.read_fb.readline(1024)
"""
2023-12-30 15:45:47 +03:00
logging.debug(self.http_type)
logging.debug(self.http_address)
logging.debug(self.http_headers)
logging.debug(self.http_get_request)
2023-12-30 15:45:47 +03:00
logging.debug(self.data)
2023-12-29 02:13:10 +03:00
self.send_form_data()
def send_form_data(self):
"""
Chain of handle, pack & send data to client
"""
found = False
2023-12-30 15:45:47 +03:00
for elem in config.urls:
if self.http_address in elem.keys():
url_metadata = elem[self.http_address]
2023-12-30 15:45:47 +03:00
if self.http_type in url_metadata[0]:
found = True
if url_metadata[1] == "static-file":
r = Response(data=fileiter(url_metadata[2]))
for i in r:
self.write_fb.write(i)
self.write_fb.flush()
elif url_metadata[1] == "function":
func = url_metadata[2]
if func.__code__.co_argcount == 0:
func_ret = func()
elif func.__code__.co_argcount == 1:
func_ret = func(self.http_headers)
elif func.__code__.co_argcount == 2:
func_ret = func(self.http_headers, self.http_get_request)
for i in func_ret:
self.write_fb.write(i)
self.write_fb.flush()
else:
logging.warning("Address configured on server, but type not allowed URL type in URLs list")
r = Response(status_code=404, data=b"Address configured on server, but type not allowed URL type in URLs list")
for i in r:
self.write_fb.write(i)
self.write_fb.flush()
if not found:
r = Response(status_code=404, data=b"Not found!")
2023-12-30 15:45:47 +03:00
for i in r:
self.write_fb.write(i)
self.write_fb.flush()
2023-12-29 02:13:10 +03:00
2023-12-30 15:45:47 +03:00
self.write_fb.close()
self.read_fb.close()
self.conn.close()
2023-12-29 02:13:10 +03:00
def start():
2023-12-29 02:13:10 +03:00
logging.basicConfig(filename="main.log", filemode="a", encoding="UTF-8",
level=config.SETUP["setup"]["log_level"], format="[%(asctime)s][%(levelname)s] %(message)s")
project_logotype = """
___________ _____ _____________
/ _______ / _/ /_ /_____ _____/
/ / /_/ _/ __ /_ / /
/ / / _/ /_ / / /
/ / / _/____/_ / / /
/ / __ / _______ / / /
/ /_______/ / / / / / / /
/___________/ /_/ /_/ /_/
___ __ ___________ _____________
/ _ | / / / _________/ /_____ _____/
/ / || / / / / / /
/ / || / / / /___ / /
/ / || / / / ____/ / /
/ / || / / / / / /
/ / ||/ / / /_________ / /
/_/ |__/ /___________/ /_/
====================================================
=== Server start separator ===
===================================================="""
logging.info(project_logotype)
2023-12-29 02:13:10 +03:00
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as main_server_socket:
main_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
main_server_socket.bind(("0.0.0.0", config.SETUP["server"]["port"]))
main_server_socket.listen()
while True:
conn, addr = main_server_socket.accept()
logging.info("Accept connection from %s", addr[0])
2023-12-22 02:48:34 +03:00
2023-12-29 02:13:10 +03:00
thr_serv_conn = threading.Thread(target=HTTPHandler, args=(conn, addr,))
thr_serv_conn.run()
2023-12-22 02:48:34 +03:00
2023-12-29 02:13:10 +03:00
except KeyboardInterrupt:
logging.info("Server get keyboard interrupt. Initialize server to stop")
logging.info("==================== End of log ====================")