-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
170 lines (157 loc) · 7.02 KB
/
server.py
File metadata and controls
170 lines (157 loc) · 7.02 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# Simple HTTP server with threads (one per connection)
import socket, threading, os, json, random, string
from datetime import datetime
HOST = '127.0.0.1'
PORT = 8080
ROOT_DIR = os.path.join(os.path.dirname(__file__), 'resources')
UPLOADS_DIR = os.path.join(ROOT_DIR, 'uploads')
LOG_DIR = os.path.join(os.path.dirname(__file__), 'logs')
LOG_FILE = os.path.join(LOG_DIR, 'server.log')
# Create necessary directories if they don't exist
os.makedirs(UPLOADS_DIR, exist_ok=True)
os.makedirs(LOG_DIR, exist_ok=True)
# --------------------------
# Logging utility
# --------------------------
def log(msg):
stamp = datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")
line = f"{stamp} {msg}"
print(line)
with open(LOG_FILE, "a", encoding="utf-8") as f:
f.write(line + "\n")
def random_id(n=5):
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=n))
def http_date():
from email.utils import formatdate
return formatdate(timeval=None, usegmt=True)
def get_content_type(path):
ext = os.path.splitext(path)[1].lower()
if ext == '.html': return 'text/html; charset=utf-8'
if ext == '.css': return 'text/css; charset=utf-8'
if ext == '.js': return 'application/javascript; charset=utf-8'
if ext in ('.png', '.jpg', '.jpeg', '.txt'): return 'application/octet-stream'
return None
def safe_path(request_path):
# Prevent path traversal
if '..' in request_path or request_path.startswith('/') or request_path.startswith('\\'):
return None
if request_path == '' or request_path == '/':
request_path = 'index.html'
abs_path = os.path.realpath(os.path.join(ROOT_DIR, request_path))
if not abs_path.startswith(os.path.realpath(ROOT_DIR)):
return None
return abs_path
def handle_client(conn, addr):
try:
data = b''
while b'\r\n\r\n' not in data and len(data) < 8192:
chunk = conn.recv(4096)
if not chunk: break
data += chunk
if not data: return
lines = data.decode('iso-8859-1').split('\r\n')
request_line = lines[0].split()
if len(request_line) != 3:
conn.sendall(b'HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\nBad Request')
log(f"[{addr}] Bad request line format")
return
method, path, version = request_line
headers = {}
for line in lines[1:]:
if ':' in line:
k,v = line.split(':',1)
headers[k.strip().lower()] = v.strip()
# Only accept Host header matching server
if 'host' not in headers or not headers['host'].startswith('127.0.0.1'):
conn.sendall(b'HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\nBad Host header')
log(f"[{addr}] Bad Host header: {headers.get('host', 'None')}")
return
# GET: serve static files
if method == 'GET':
file_path = safe_path(path.lstrip('/'))
if not file_path or not os.path.isfile(file_path):
conn.sendall(b'HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\nNot Found')
log(f"[{addr}] GET {path} -> 404 Not Found")
return
content_type = get_content_type(file_path)
if not content_type:
conn.sendall(b'HTTP/1.1 415 Unsupported Media Type\r\nConnection: close\r\n\r\nUnsupported Media Type')
log(f"[{addr}] GET {path} -> 415 Unsupported Media Type")
return
headers_out = [
'HTTP/1.1 200 OK',
f'Date: {http_date()}',
f'Server: SimplePythonServer',
f'Content-Type: {content_type}',
f'Content-Length: {os.path.getsize(file_path)}',
'Connection: close'
]
if content_type == 'application/octet-stream':
headers_out.append(f'Content-Disposition: attachment; filename="{os.path.basename(file_path)}"')
headers_out.append('\r\n')
conn.sendall(('\r\n'.join(headers_out)).encode('utf-8'))
with open(file_path, 'rb') as f:
content = f.read()
conn.sendall(content)
log(f"[{addr}] GET {path} -> 200 OK ({os.path.getsize(file_path)} bytes)")
return
# POST: accept JSON and save
elif method == 'POST' and path == '/upload':
if headers.get('content-type','') != 'application/json':
conn.sendall(b'HTTP/1.1 415 Unsupported Media Type\r\nConnection: close\r\n\r\nUnsupported Media Type')
log(f"[{addr}] POST {path} -> 415 Unsupported Media Type")
return
content_length = int(headers.get('content-length','0'))
body = data.split(b'\r\n\r\n',1)[1]
while len(body) < content_length:
more = conn.recv(content_length - len(body))
if not more: break
body += more
try:
obj = json.loads(body.decode('utf-8'))
except Exception:
conn.sendall(b'HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\nBad JSON')
log(f"[{addr}] POST {path} -> 400 Bad Request - Invalid JSON")
return
ts = datetime.now().strftime('%Y%m%d_%H%M%S')
fname = f'upload_{ts}_{random_id()}.json'
with open(os.path.join(UPLOADS_DIR, fname),'w',encoding='utf-8') as f:
json.dump(obj, f, indent=2)
resp = json.dumps({'status':'success','message':'File created successfully','filepath':f'/uploads/{fname}'}).encode('utf-8')
headers_out = [
'HTTP/1.1 201 Created',
f'Date: {http_date()}',
f'Server: SimplePythonServer',
'Content-Type: application/json',
f'Content-Length: {len(resp)}',
'Connection: close',
'\r\n'
]
conn.sendall(('\r\n'.join(headers_out)).encode('utf-8') + resp)
log(f"[{addr}] POST upload -> created {fname}")
return
else:
conn.sendall(b'HTTP/1.1 405 Method Not Allowed\r\nConnection: close\r\n\r\nMethod Not Allowed')
log(f"[{addr}] {method} {path} -> 405 Method Not Allowed")
finally:
conn.close()
def main():
log(f'HTTP Server started on http://{HOST}:{PORT}')
# Configuration Summary
log("Configuration Summary:")
log(f" Host: {HOST}")
log(f" Port: {PORT}")
log(f" Resource Dir: {ROOT_DIR}")
log(f" Uploads Dir: {UPLOADS_DIR}")
log(f" Logs Dir: {LOG_DIR}")
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(50)
log("Server initialized and listening for connections...")
while True:
conn, addr = s.accept()
log(f"New connection from {addr}")
threading.Thread(target=handle_client, args=(conn, addr), daemon=True).start()
if __name__ == '__main__':
main()