#!/usr/bin/env python3
"""
simple_web_server.py -- Activity 7, Chapter 7 (Software Security)
"Computer Security: The Foundations", Krerk Piromsopa, Ph.D.
https://www.cp.eng.chula.ac.th/~krerk/books/ComputerSecurity/

This server is DELIBERATELY INSECURE.  It is the starting point for the
activity, not a finished program: a single connection blocks all others
(denial of service), there is no access control (path traversal, information
disclosure, tampering), and nothing is logged (no non-repudiation).  Hardening
it is the exercise.

Do not deploy this on a network you do not control, and never in production.

Run it with:  python3 simple_web_server.py
then place an index.html beside it and open http://localhost:8080/index.html
"""

import socket

PORT = 8080

def serve_file(conn, pathname):
    if pathname.startswith('/'):
        pathname = pathname[1:]
    if pathname == '':
        pathname = 'index.html'

    try:
        with open(pathname, 'r') as f:
            content = f.read()
    except Exception:
        conn.sendall(b"HTTP/1.0 404 Not Found\r\n\r\n")
        return

    conn.sendall(b"HTTP/1.0 200 OK\r\n\r\n")
    conn.sendall(content.encode())

def process_request(conn):
    data = conn.makefile('r').readline()
    parts = data.split()
    command  = parts[0]
    pathname = parts[1]

    if command == 'GET':
        serve_file(conn, pathname)
    else:
        conn.sendall(b"HTTP/1.0 501 Not Implemented\r\n\r\n")

    conn.close()

def run():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server.bind(('', PORT))
        server.listen(5)
        while True:
            conn, addr = server.accept()
            process_request(conn)

if __name__ == '__main__':
    run()
