commit d54b74e65f13c35f72be4b72c712dfc1032fc13e Author: Иван Солнцев Date: Fri Dec 22 02:48:34 2023 +0300 Create primitive fork HTTP server diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fc6fa6e --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*.log +*.swp diff --git a/__main__.py b/__main__.py new file mode 100755 index 0000000..ba4acb2 --- /dev/null +++ b/__main__.py @@ -0,0 +1,54 @@ +#!/usr/bin/python3.12 + +import os +import socket +import logging + + +MAX_REQLINE = 64 * 1024 + +def service_connections(conn, addr): + recv_file = conn.makefile("rb") + + logging.debug("START RECV") + raw = recv_file.readline(MAX_REQLINE + 1) + logging.debug("END RDLINE") + if len(raw) > MAX_REQLINE: + logging.debug("Request line is too long") + return + + req_line = raw.decode().rstrip("\r\n") + + words = req_line.split(" ") + + if len(words) != 3: + logging.debug("Request head too long") + return + + if words[0] == "GET": + logging.debug("SEND") + conn.send(b"HTTP/1.1 200 OK\r\nServer: cnserv\r\n\r\nNone") + logging.debug("SENDEND") + conn.close() + logging.debug("CONNEND") + + + +if __name__ == "__main__": + logging.basicConfig(filename="main.log", filemode="w", encoding="UTF-8", + level=logging.DEBUG) + + 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", 8080)) + main_server_socket.listen() + + while True: + conn, addr = main_server_socket.accept() + conn.settimeout(1) + logging.info("Accept connection from %s", addr[0]) + + pid = os.fork() + + if pid == 0: + service_connections(conn, addr)