-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_server.py
More file actions
672 lines (488 loc) · 14.4 KB
/
Copy pathweb_server.py
File metadata and controls
672 lines (488 loc) · 14.4 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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
import socket
import urllib.parse
from html import escape
import os
import json
import secrets
import hmac
DATA_FILE = "message_board.json"
COOKIE_NAME = "token"
# token -> for user session dictionary
SESSIONS = {}
LOGINS = {
"paul":"123cool",
"admin":"password"
}
DEFAULT_TOPICS = {
"cooking" :[
{
"text":"pavel made soup",
"author":"paul",
},
],
"cars" :[
{
"text":"Toyota is reliable",
"author":"admin",
},
],
}
def default_topics_copy():
return {
topic: [
message.copy()
for message in messages
]
for topic,messages in DEFAULT_TOPICS.items()
}
def load_topics():
if not os.path.exists(DATA_FILE):
return default_topics_copy()
try:
with open(DATA_FILE,"r",encoding="utf8") as f:
data = json.load(f)
except Exception as e:
print("Failed to load data file:",e)
return default_topics_copy()
if not isinstance(data,dict):
return default_topics_copy()
topics ={}
for topic,messages in data.items():
if not isinstance(topic,str):
continue
if not isinstance(messages,list):
continue
clean_messages = []
for message in messages:
# old format
# "Hello"
if isinstance(message,str):
clean_messages.append({
"text":message,
"author":"anonymous"
})
continue
# new format
# {"text":"hello","author":"paul"}
if isinstance(message,dict):
text = message.get("text")
author = message.get("author")
if not isinstance(text,str):
continue
if not isinstance(author,str):
continue
clean_messages.append({
"text":text,
"author":author
})
topics[topic] = clean_messages
return topics
TOPICS = load_topics()
def save_topics():
temp_file = DATA_FILE + ".tmp"
with open(temp_file,"w",encoding="utf8") as f:
json.dump(TOPICS,f,ensure_ascii=False,indent=2)
os.replace(temp_file,DATA_FILE)
def parse_cookies(cookie_header):
cookies = {}
if not cookie_header:
return cookies
# Cookie: token=abc; theme=dark
for part in cookie_header.split(";"):
part = part.strip()
if "=" not in part:
continue
name, value = part.split("=",1)
name = name.strip()
value = value.strip()
if name:
cookies[name] = value
return cookies
def valid_token(token):
if not isinstance(token,str):
return False
# secrets.token_hex(32) -> 64 hex chars
if len(token) != 64:
return False
try:
int(token,16)
except ValueError:
return False
return True
def create_nonce(session):
nonce = secrets.token_hex(32) #create nonce value
session["nonce"] = nonce
return nonce
def valid_nonce(sesson,params):
if "nonce" not in sesson:
return False
if "nonce" not in params:
return False
return hmac.compare_digest( # compare nonce value
sesson["nonce"],
params["nonce"]
)
def handle_connection(conx):
req = conx.makefile("b")
reqline = req.readline().decode('utf8')
if not reqline:
conx.close()
return
method, url, version = reqline.split(" ", 2)
assert method in ["GET", "POST"]
headers = {}
while True:
line = req.readline().decode('utf8')
if line == '\r\n':
break
header, value = line.split(":", 1)
headers[header.casefold()] = value.strip()
if 'content-length' in headers:
length = int(headers['content-length'])
body = req.read(length).decode('utf8')
else:
body = None
# read cookie
cookie_header = headers.get("cookie","")
cookies = parse_cookies(cookie_header)
token = cookies.get(COOKIE_NAME)
new_cookie = False
# first visit,or get invalid token
if not valid_token(token):
token = secrets.token_hex(32)
new_cookie = True
# get user server-side session
session = SESSIONS.setdefault(token,{})
# let session pass into request
status, body = do_request(session,
method,
url,
headers,
body
)
body_bytes = body.encode("utf8")
response = "HTTP/1.0 {}\r\n".format(status)
response += "Content-Type: text/html; charset=utf-8\r\n"
response += "Content-Length: {}\r\n".format(len(body_bytes))
# when first visit,request broswer must save token
if new_cookie:
response += "Set-Cookie: {}={}\r\n".format(
COOKIE_NAME,
token
)
response += "\r\n"
conx.sendall(response.encode('utf8')+body_bytes)
conx.close()
def form_decode(body):
params ={}
if not body:
return params
for field in body.split("&"):
if "=" in field:
name, value = field.split("=",1)
else:
name , value = field,""
name = urllib.parse.unquote_plus(name)
value = urllib.parse.unquote_plus(value)
params[name] = value
return params
def path_only(url):
if "?" in url:
path,query = url.split("?",1)
return path
return url
def topic_to_url(topic):
return "/"+urllib.parse.quote(topic,safe="")
def add_topic_url(topic):
return "/add/" +urllib.parse.quote(topic,safe="")
def normalize_topic_name(topic):
topic = topic.strip().lower()
out = []
last_dash = False
for ch in topic:
if ch.isalnum():
out.append(ch)
last_dash = False
elif ch in [" ","-","_"]:
if not last_dash:
out.append("-")
last_dash = True
topic = "".join(out).strip("-")
return topic
def login_form(session):
out = "<!doctype html>"
out += "<html>"
out += "<body>"
out += "<h1>Log in</h1>"
out += "<form action=/ method=post>"
out += "<p>"
out += "Username: "
out += "<input name=username>"
out += "</p>"
out += "<p>"
out += "Password: "
out += "<input name=password type=password>"
out += "</p>"
out += "<p>"
out += "<button>Log in</button>"
out += "</p>"
out += "</form>"
out += "<p><a href=/>Back to topics</a></p>"
out += "</body>"
out += "</html>"
return out
def do_login(session,params):
username = params.get("username","")
password = params.get("password","")
expected_password = LOGINS.get(username)
valid_login =(
expected_password is not None
and hmac.compare_digest(
expected_password,
password
)
)
if valid_login:
session["user"] = username
return "200 OK",show_home(session)
out = "<!doctype html>"
out += "<html>"
out += "<body>"
out += "<h1>Invalid username or password</h1>"
if username:
out+="<p>Username:"
out+=escape(username)
out+="</p>"
out += "<p><a href=/login>Try again</a></p>"
out += "</body>"
out += "</html>"
return "401 Unauthorized",out
def show_home(session):
out = "<!doctype html>"
out += "<html>"
out += "<body>"
out += "<h1>Message Board</h1>"
if "user" in session:
out += "<p>Hello, "
out += escape(session["user"])
out += "</p>"
else:
out += "<p>"
out += "<a href=/login>"
out += "sign in to post messages"
out += "</a>"
out += "</p>"
out += "<h2>Topics</h2>"
if not TOPICS:
out += "<p>No topics yet.</p>"
else:
out+="<ul>"
for topic in sorted(TOPICS.keys()):
topic_url = topic_to_url(topic)
out += "<li>"
out += "<a href={}>".format(escape(topic_url, quote=True))
out += escape(topic)
out += "</a>"
out += "</li>"
out+="</ul>"
# only login user can add new topic
if "user" in session:
nonce = create_nonce(session)
out += "<h2>Add new topic</h2>"
out += "<form action=/add-topic method=post>"
# add nonce to form
out += "<input "
out += "name=nonce " # nonce field
out += "type=hidden " # hidden field
out += "value={}>".format(nonce) # nonce value
out += "<p><input name=topic></p>"
out += "<p><button>Add topic</button></p>"
out += "</form>"
out += "</body>"
out += "</html>"
return out
def show_topic(session,topic):
messages = TOPICS[topic]
out = "<!doctype html>"
out += "<html>"
out += "<body>"
out += "<p><a href=/>Back to topics</a></p>"
out += "<h1>Topic: "
out += escape(topic)
out += "</h1>"
if "user" in session:
nonce = create_nonce(session)
out += "<p>Hello,"
out += escape(session["user"])
out += "</p>"
out += "<form action={} method=post>".format(
escape(add_topic_url(topic), quote=True)
)
out += "<input "
out += "name=nonce "
out += "type=hidden "
out += "value={}>".format(nonce)
out += "<p><input name=message></p>"
out += "<p><button>Post message</button></p>"
out += "</form>"
else:
out += "<p>"
out += "<a href=/login>"
out += "Sign in to post a message"
out += "</a>"
out += "</p>"
out += "<h2>Messages</h2>"
if not messages:
out += "<p>No messages yet.</p>"
else:
for message in messages:
text = message["text"]
author = message["author"]
out += "<p>"
out += escape(text)
out += "<br>"
out += "<i>by "
out += escape(author)
out += "</i>"
out += "</p>"
out += "</body>"
out += "</html>"
return out
def add_topic(session,params):
if "user" not in session:
return show_home(session)
if "topic" not in params:
return show_home(session)
topic = normalize_topic_name(params["topic"])
if topic=="":
return show_home(session)
if topic not in TOPICS:
TOPICS[topic] = []
save_topics()
return show_home(session)
def add_message(session,topic,params):
if "user" not in session:
return show_topic(session,topic)
if topic not in TOPICS:
return not_found("/add/"+topic,"POST")
if "message" in params:
message = params["message"].strip()
if message and len(message) <= 100:
TOPICS[topic].append({
"text":message,
"author":session["user"],
})
save_topics()
return show_topic(session,topic)
def query_decode(url):
if "?" not in url:
return {}
path,query=url.split("?",1)
return form_decode(query)
def show_submit_result(url):
params = query_decode(url)
out = "<!doctype html>"
out += "<html>"
out += "<body>"
out += "<h1>Submitted GET Form</h1>"
out += "<p>Raw URL:</p>"
out += "<p>" + escape(url) + "</p>"
out += "<h2>Decoded fields</h2>"
if not params:
out += "<p>No fields submitted.</p>"
else:
for name,value in params.items():
out += "<p>"
out += escape(name)
out += " = "
out += escape(value)
out += "</p>"
out += "<p><a href=/>Back</a></p>"
out += "</body>"
out += "</html>"
return out
def csrf_rejected():# when nonce is incorrect return error page
out = "<!doctype html>"
out += "<html>"
out += "<body>"
out += "<h1>Invalid form submission</h1>"
out += "<p>The CSRF nonce is missing or invalid.</p>"
out += "<p><a href=/>Back to topics</a></p>"
out += "</body>"
out += "</html>"
return out
def login_required():
out = "<!doctype html>"
out += "<html>"
out += "<body>"
out += "<h1>Login required</h1>"
out += "<p>You must log in before posting.</p>"
out += "<p><a href=/login>Log in</a></p>"
out += "</body>"
out += "</html>"
return out
def not_found(url,method):
out = "<!doctype html>"
out += "<html>"
out += "<body>"
out += "<h1>{} {} not found!</h1>".format(
escape(method),
escape(url)
)
out += "<p><a href=/>Back to topics</a></p>"
out += "</body>"
out += "</html>"
return out
def do_request(session,method, url, headers, body):
path = path_only(url)
# home page
if method == "GET" and path =="/":
return "200 OK", show_home(session)
# login page
elif method == "GET" and path =="/login":
return "200 OK" ,login_form(session)
# deal with login
elif method == "POST" and path == "/":
params = form_decode(body)
return do_login(
session,
params
)
# add topic
elif method=="POST" and path=="/add-topic":
if "user" not in session:
return "403 Forbidden",login_required()
params = form_decode(body)
if not valid_nonce(session,params):
return "403 Forbidden",csrf_rejected()
return "200 OK" ,add_topic(session,params)
# show topic
elif method=="GET" and path.startswith("/") and len(path) > 1:
topic = urllib.parse.unquote(path[1:])
if topic in TOPICS:
return "200 OK", show_topic(session,topic)
else:
return "404 Not Found",not_found(url,method)
# add message
elif method == "POST" and path.startswith("/add/"):
if "user" not in session:
return "403 Forbidden",login_required()
params = form_decode(body)
if not valid_nonce(session,params):
return "403 Forbidden", csrf_rejected()
topic = urllib.parse.unquote(path[len("/add/"):])
return "200 OK", add_message(session,topic,params)
# other
else:
return "404 Not Found", not_found(url,method)
if __name__ == "__main__":
s = socket.socket(
family=socket.AF_INET,
type=socket.SOCK_STREAM,
proto=socket.IPPROTO_TCP)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', 8000))
s.listen()
while True:
conx, addr = s.accept()
handle_connection(conx)