-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
92 lines (76 loc) · 2.98 KB
/
server.py
File metadata and controls
92 lines (76 loc) · 2.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import socket
import argparse
from pathlib import Path
import os
CRLF = b"\r\n"
PATH = "files/"
def handle_client(conn, addr, root: Path, timeout: float):
conn.settimeout(timeout)
try:
# Get Request from client
request = conn.recv(1024).decode().split()
good_request = True
# Verify Request
if request[0] != "GET" or request[2] != "HTTP/1.1":
good_request = False
try:
conn.sendall(b"ERR 400 bad-request")
except Exception:
pass
# Retrieve file to send back
if good_request:
try:
file = open(f"{PATH}{request[1]}")
file_contents = file.read()
except:
good_request = False #terminate
conn.send(b"ERR 404 not-found")
# send file to client, file is in "root" folder
# file can be sent as "text", no need to use bytes
# See TCPClient/TCPServer on sending text
# add error handling in case file is not found
if good_request:
encoded_file = file_contents.encode()
file_size = len(encoded_file)
conn.sendall(f"HTTP/1.1 200 OK\nContent-Length:{file_size}\r\n\r\n".encode())
for i in range(file_size):
conn.send(encoded_file[i:i+1])
# Send CRLF at the end if the file
conn.send(CRLF)
# handle timeout message
except socket.timeout:
try:
conn.sendall(b"ERR 400 timeout\r\n")
except Exception:
pass
# handle general exceptions
except Exception:
try:
conn.sendall(b"ERR 500 server-error\r\n")
except Exception:
pass
finally:
conn.close()
def serve(host: str, port: int, root: Path, workers: int, timeout: float):
root = root.resolve()
# Create a socket in a python context manager
# The socket is opened using IPV4 and TCP
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Bind socket to ip address and port
s.bind((host, port))
# Start listening
s.listen()
print(f"[HTTP server] Serving {root} on {host}:{port}")
while True:
conn, addr = s.accept()
handle_client(conn, addr, root, timeout)
if __name__ == "__main__":
p = argparse.ArgumentParser(description="TinyFile server")
p.add_argument("--host", default="0.0.0.0")
p.add_argument("--port", type=int, default=9009)
p.add_argument("--root", type=Path, default=Path("files"))
p.add_argument("--timeout", type=float, default=10.0)
args = p.parse_args()
args.root.mkdir(parents=True, exist_ok=True)
serve(args.host, args.port, args.root, workers=100, timeout=args.timeout)