From d54b74e65f13c35f72be4b72c712dfc1032fc13e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=B2=D0=B0=D0=BD=20=D0=A1=D0=BE=D0=BB=D0=BD=D1=86?= =?UTF-8?q?=D0=B5=D0=B2?= Date: Fri, 22 Dec 2023 02:48:34 +0300 Subject: [PATCH] Create primitive fork HTTP server --- .gitignore | 2 ++ __main__.py | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 .gitignore create mode 100755 __main__.py 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)