-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathremote_peer.py
More file actions
1024 lines (794 loc) · 30.4 KB
/
Copy pathremote_peer.py
File metadata and controls
1024 lines (794 loc) · 30.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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (C) 2025 pdnguyen of HCMC University of Technology VNU-HCM.
# All rights reserved.
# This file is part of the CO3093/CO3094 course,
# and is released under the "MIT License Agreement". Please see the LICENSE
# file that should have been included as part of this package.
#
# WeApRous release
#
# The authors hereby grant to Licensee personal permission to use
# and modify the Licensed Source Code for the sole purpose of studying
# while attending the course
#
"""
session_base_http_server
~~~~~~~~~~~~~~~~~~~~~~~~~
This is a cookie session-based HTTP server implementation, with self-defined routes and corresponding handlers, using the start_backend module to create a server process and use daemon like httpadapter, request, and response for processing HTTP requests.
"""
import argparse
import json
import os
import socket
import threading
from daemon import WeApRous
from daemon.response import Response
from remote_util import get_host_default_interface_ip
# Using Framework
app = WeApRous()
# Default port number used if none is specified via command-line arguments.
PORT = 8000
# Global dictionary to store active sessions
# Key: session_id, Value: user information
TRACKER_IP = '0.0.0.0'
TRACKER_PORT = 9000
SESSION = ''
REACHABLE_PEERS = []
REACHABLE_CHANNELS = {}
UNREAD_CHANNELS = set()
UNREAD_PEERS = set()
HISTORY_LOCK = threading.Lock()
UNREAD_PEERS_LOCK = threading.Lock()
UNREAD_CHANNELS_LOCK = threading.Lock()
def cal_content_len(raw_data):
return len(raw_data)
def check_authentication(request):
global SESSION
session_id = request.cookies.get('session_id', '')
print("[Auth] peer session: {}".format(SESSION))
return session_id and session_id == SESSION
def protect_routes(func):
def wrapper(request):
if not check_authentication(request):
print("[Auth] Access Denied. Unauthorized 401.")
resp = Response()
return resp.build_unauthorized_basic('/login.html')
return func(request)
return wrapper
def extract_session_value_from_response(raw_data):
"""
Parses a raw HTTP response to find the 'Set-Cookie' header
and extract only the session value.
:param raw_data (str): The full HTTP response as a string.
:return (str or None): The session value (e.g., "9cbf90..."),
or None if not found.
"""
try:
lines = raw_data.splitlines()
except AttributeError:
return None
for line in lines:
if line.lower().startswith('set-cookie:'):
full_cookie_value = line.split(':', 1)[1].strip()
parts = full_cookie_value.split(';')
if parts and '=' in parts[0]:
session_pair = parts[0].strip()
if session_pair.lower().startswith('session_id='):
value_parts = session_pair.split('=', 1)
if len(value_parts) == 2:
return value_parts[1] # Return the second part
return None
def tracker_communicate(raw_data):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.connect((TRACKER_IP, TRACKER_PORT))
server_socket.sendall(raw_data)
resp_chunk = []
while True:
chunk = server_socket.recv(4096)
if not chunk:
break
resp_chunk.append(chunk)
resp_chunk = b''.join(resp_chunk)
return resp_chunk
def manual_decode(text):
decoded = []
i = 0
length = len(text)
while i < length:
char = text[i]
if char == '%':
hex_value = text[i + 1: i + 3]
try:
ascii_char = chr(int(hex_value, 16))
decoded.append(ascii_char)
i += 3
except ValueError:
decoded.append('%')
i += 1
elif char == '+':
decoded.append(' ')
i += 1
else:
decoded.append(char)
i += 1
return "".join(decoded)
###############################
#########PEER ROUTES###########
###############################
def parse_custom_body(raw_body: str) -> dict:
data = {}
# Split by '&' to get individual key=value pairs
for entry in raw_body.split('&'):
if '=' in entry:
# Split only on the first '=' to handle values that might contain '='
key, value = entry.split('=', 1)
data[key.strip()] = value.strip()
return data
def filter_self(peers_list, self_ip, self_port):
return [peer for peer in peers_list if peer != (self_ip, self_port)]
def update_reachable_peers(raw_data):
try:
full_text = raw_data.decode()
if '\r\n\r\n' in full_text:
# split(..., 1) ensures we only split at the first occurrence (the header boundary)
body = full_text.split('\r\n\r\n', 1)[1]
else:
print("[WARNING] No HTTP headers found in response.")
body = full_text
if not body.strip():
return
# The format is a stream: key=value&key=value...
pairs = body.split('&')
new_peers = []
current_ip = None
for pair in pairs:
# Skip empty or malformed pairs
if '=' not in pair:
continue
key, value = pair.split('=', 1)
if key == 'peer-ip':
current_ip = value
elif key == 'peer-port':
if current_ip is not None:
# We have a complete pair
new_peers.append((current_ip, int(value)))
current_ip = None
new_peers = filter_self(new_peers, app.ip, app.port)
global REACHABLE_PEERS
REACHABLE_PEERS = new_peers
print(f"[PEER UPDATE] Reachable list updated: {REACHABLE_PEERS}")
except Exception as e:
print(f"[ERROR] Failed to parse peer list: {e}")
def process_peer_data(body_string):
parsed_data = {}
pairs = body_string.split('&')
for pair in pairs:
if '=' in pair:
key, value = pair.split('=', 1)
parsed_data[key] = value
target_ip = parsed_data.get('peer-ip')
target_port = parsed_data.get('peer-port')
message = parsed_data.get('message')
parsed_data['peer-ip'] = app.ip
parsed_data['peer-port'] = app.port
modified_pairs = []
for key, value in parsed_data.items():
modified_pairs.append(f"{key}={value}")
modified_string = '&'.join(modified_pairs)
return {
"ip": target_ip,
"port": target_port,
"only_message": message,
"modified_body_string": modified_string
}
def raw_reachable_peers():
global REACHABLE_PEERS
parts = [f"peer-ip={pip}&peer-port={pport}" for pip, pport in REACHABLE_PEERS]
result = "&".join(parts)
return result
def peer_communicate(peer_ip, peer_port, raw_data):
peer_port = int(peer_port)
peer_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
peer_socket.connect((peer_ip, peer_port))
peer_socket.sendall(raw_data)
resp_chunk = []
while True:
chunk = peer_socket.recv(4096)
if not chunk:
break
resp_chunk.append(chunk)
resp_chunk = b''.join(resp_chunk)
return resp_chunk
@app.route('/submit-info', methods=['POST'])
@protect_routes
def route_submit(request):
request.path = '/add_list'
request.body = ("peer-ip=" + str(app.ip)
+ "&peer-port=" + str(app.port))
raw_data = request.build_raw()
tracker_communicate(raw_data)
resp = Response()
# Copy session cookie from request to response to maintain session across redirect
if 'session_id' in request.cookies:
resp.cookies['session_id'] = request.cookies['session_id']
print("[SUBMIT-INFO] Copying session cookie: {}".format(request.cookies['session_id']))
else:
print("[SUBMIT-INFO] WARNING: No session_id in request cookies!")
print("[SUBMIT-INFO] Response cookies: {}".format(resp.cookies))
return resp.build_redirect_response('/chat.html', 301, 'Moved Permanently')
@app.route('/broadcast-peer', methods=['POST'])
@protect_routes
def route_broadcast_peer(request):
msg = parse_custom_body(request.body)
msg = msg['message']
modified_msg = ('peer-ip=' + str(app.ip) +
'&peer-port=' + str(app.port) +
'&message=' + msg)
print(f"[BROADCAST] User sending: {modified_msg}")
for peer in REACHABLE_PEERS:
pip = peer[0]
pport = peer[1]
helper_broadcast(request, pip, pport, msg, modified_msg)
resp = Response()
resp.status_code = 200
resp.reason = 'OK'
return resp.build_response_header(request)
# exact same with send_peer logic trick the protected routes
def helper_broadcast(request, peer_ip='', peer_port=-1, msg='', peer_msg=''):
target_ip = peer_ip
target_port = peer_port
to_store_msg = msg
body_string = peer_msg
# Store in peer
target_address = f"{target_ip}:{target_port}"
new_message = {
"type": "sent",
"message": to_store_msg
}
with HISTORY_LOCK:
save_message_to_json(target_address, new_message)
request.path = '/receive-peer'
request.body = body_string
raw_data = request.build_raw()
print('[MESSAGE] {}'.format(raw_data.decode()))
resp_chunk = peer_communicate(target_ip, target_port, raw_data)
return resp_chunk
@app.route('/send-peer', methods=['POST'])
@protect_routes
def route_send_peer(request):
result = process_peer_data(request.body)
target_ip = result['ip']
target_port = result['port']
to_store_msg = result['only_message']
to_store_msg = manual_decode(to_store_msg)
body_string = result['modified_body_string']
# Store in peer
target_address = f"{target_ip}:{target_port}"
new_message = {
"type": "sent",
"message": to_store_msg
}
with HISTORY_LOCK:
save_message_to_json(target_address, new_message)
request.path = '/receive-peer'
request.body = body_string
raw_data = request.build_raw()
print('[MESSAGE] {}'.format(raw_data.decode()))
resp_chunk = peer_communicate(target_ip, target_port, raw_data)
return resp_chunk
def mark_peer_as_unread(peer_address: str):
print(f"NOTIFICATION: Marking {peer_address} as unread.")
global UNREAD_PEERS
# Debug check (Optional: Add this temporarily to see what's happening)
with UNREAD_PEERS_LOCK:
UNREAD_PEERS.add(peer_address)
print('[ADD TO UNREAD] {}'.format(UNREAD_PEERS))
def mark_peer_as_read(peer_address: str):
global UNREAD_PEERS
if peer_address in UNREAD_PEERS:
with UNREAD_PEERS_LOCK:
print(f"NOTIFICATION: Marking {peer_address} as read.")
UNREAD_PEERS.remove(peer_address)
print('[RM TO UNREAD] {}'.format(UNREAD_PEERS))
# Peer to Peer
@app.route('/receive-peer', methods=['POST'])
def route_receive_peer(request):
request.body = manual_decode(request.body)
print('[MESSAGE] {}'.format(request.body))
data = process_peer_data(request.body)
sender_ip = data['ip']
sender_port = data['port']
to_store_msg = data['only_message']
# Store received address in peer
sender_address = f"{sender_ip}:{sender_port}"
new_message = {
"type": "received",
"message": to_store_msg
}
with HISTORY_LOCK:
save_message_to_json(sender_address, new_message)
mark_peer_as_unread(sender_address) # ipvalue:portvalue
resp = Response()
resp.status_code = 200
resp.reason = 'OK'
return resp.build_response_header(request)
@app.route('/unread-peer', methods=['GET'])
@protect_routes
def route_unread_peer(request):
global UNREAD_PEERS
print(f"[DEBUG] route_unread_peer hit. Current set: {UNREAD_PEERS}", flush=True)
resp = Response()
resp.status_code = 200
resp.reason = 'OK'
if not UNREAD_PEERS:
return resp.build_response_header(request, 0)
parts = []
with UNREAD_PEERS_LOCK:
for peer_address in UNREAD_PEERS:
if ':' in peer_address:
ip, port = peer_address.split(':', 1)
# Add the pair to our list
parts.append(f"peer-ip={ip}")
parts.append(f"peer-port={port}")
body = "&".join(parts)
print('[UNREAD_PEERS] {}'.format(UNREAD_PEERS))
return resp.build_response_header(request, len(body)) + body.encode()
@app.route('/get-history', methods=['POST'])
@protect_routes
def route_get_history(request):
data = parse_custom_body(request.body)
target_ip = data.get('peer-ip')
target_port = data.get('peer-port')
target_peer = f"{target_ip}:{target_port}"
# If no history exists, default to an empty list
with HISTORY_LOCK:
messages = load_history_from_json(target_peer)
parts = []
for msg in messages:
msg_type = msg['type'] # "sent" or "received"
raw_content = msg['message']
parts.append(f"type={msg_type}")
parts.append(f"message={raw_content}")
response_body = "&".join(parts)
# 5. Return Response
# We must calculate the byte length for the Content-Length header
body_bytes = response_body.encode('utf-8')
resp = Response()
resp.status_code = 200
resp.reason = 'OK'
mark_peer_as_read(target_peer)
return resp.build_response_header(request, len(body_bytes)) + body_bytes
@app.route('/get-list', methods=['GET'])
@protect_routes
def route_get_peers(request):
request.path = '/connect-peer'
request.body = ("peer-ip=" + str(app.ip)
+ "&peer-port=" + str(app.port))
update_reachable_peers(tracker_communicate(request.build_raw() ) )
raw_str = raw_reachable_peers()
raw_str = raw_str.encode()
resp = Response()
resp.status_code = 200
resp.reason = 'OK'
resp.headers['Content-Type'] = 'text/html'
return resp.build_response_header(request, cal_content_len(raw_str)) + raw_str
###############################
#########CHANNEL ROUTES########
###############################
def raw_reachable_channels():
global REACHABLE_CHANNELS
channels = [f"channel_name={channel}" for channel in REACHABLE_CHANNELS]
result = "&".join(channels)
return result
@app.route('/create-channel', methods=['POST'])
@protect_routes
def route_create_channel(request):
"""
Expects body: channel_name=General&peer-ip=...&peer-port=...
"""
# Parse the incoming body to get channel name
data = parse_custom_body(request.body)
channel_name = data.get('channel-name', '')
# Rebuild the body with peer info
request.body = f"channel-name={channel_name}&peer-ip={app.ip}&peer-port={app.port}"
request.path = '/create-channel'
raw_data = request.build_raw()
tracker_communicate(raw_data)
resp = Response()
resp.status_code = 200
resp.reason = 'OK'
return resp.build_response_header(request)
@app.route('/get-channel', methods=['GET'])
@protect_routes
def route_get_channel(request):
request.path = '/get-channel'
data = request.build_raw()
result = tracker_communicate(data)
update_reachable_channels(result)
raw_str = raw_reachable_channels()
raw_str = raw_str.encode('utf-8')
resp = Response()
resp.status_code = 200
resp.reason = 'OK'
return resp.build_response_header(request, cal_content_len(raw_str)) + raw_str
@app.route('/join-channel', methods=['POST'])
@protect_routes
def route_join_channel(request):
# Parse the incoming body to get channel name
data = parse_custom_body(request.body)
channel_name = data.get('channel-name', '')
# Rebuild the body with peer info
request.body = f"channel-name={channel_name}&peer-ip={app.ip}&peer-port={app.port}"
request.path = '/join-channel'
raw_data = request.build_raw()
tracker_communicate(raw_data)
resp = Response()
resp.status_code = 200
resp.reason = 'OK'
return resp.build_response_header(request)
@app.route('/leave-channel', methods=['POST'])
@protect_routes
def route_leave_channel(request):
# Parse the incoming body to get channel name
data = parse_custom_body(request.body)
channel_name = data.get('channel-name', '')
# Rebuild the body with peer info
request.body = f"channel-name={channel_name}&peer-ip={app.ip}&peer-port={app.port}"
request.path = '/leave-channel'
raw_data = request.build_raw()
tracker_communicate(raw_data)
resp = Response()
resp.status_code = 200
resp.reason = 'OK'
return resp.build_response_header(request)
def get_members_in_channel(channel_name):
global REACHABLE_CHANNELS
return REACHABLE_CHANNELS.get(channel_name, [])
@app.route('/send-channel', methods=['POST'])
@protect_routes
def send_channel_message(request):
#channel_name=value&message=something
data = parse_custom_body(request.body)
channel_name = data['channel_name']
sender_ip = app.ip
sender_port = app.port
sender = f'{sender_ip}:{sender_port}'
message = data['message']
decoded_message = manual_decode(message)
msg_type = "sent"
new_message = {
"channel_name": channel_name,
"sender": sender,
"message": decoded_message,
"type": msg_type
}
with HISTORY_LOCK:
save_channel_message_to_json(channel_name, new_message)
network_packet = f"channel_name={channel_name}&sender={sender}&message={message}&type=sent"
members_list = get_members_in_channel(channel_name)
print(f"[Channel] Sending to members: {members_list}")
# 5. Fan-Out: Send to everyone
for peer_full_address in members_list:
# Don't send to yourself
if peer_full_address == sender:
continue
try:
# Parse "IP:Port" string
target_ip, target_port = peer_full_address.split(":")
helper_send_channel_msg(target_ip, target_port, network_packet, request)
except Exception as e:
print(f"[Error] Could not send to {peer_full_address}: {e}")
print(f"[Channel] Message sent to {channel_name}")
response = Response()
response.status_code = 200
response.reason = 'OK'
return response.build_response_header(request)
def helper_send_channel_msg(target_ip, target_port, msg, request):
request.path = '/receive-channel'
request.body = msg
raw_data = request.build_raw()
resp_chunk = peer_communicate(target_ip, target_port, raw_data)
return resp_chunk
@app.route('/receive-channel', methods=['POST'])
def receive_channel_message(request):
# Format: channel_name=value&sender=ip:port&message=something&type=sent
data = parse_custom_body(request.body)
print(f"[RECEIVE CHANNEL] {request.body}")
channel_name = data.get('channel_name')
sender = data.get('sender')
message = data.get('message')
decoded_message = manual_decode(message)
received_message = {
"sender": sender,
"message": decoded_message,
"type": "received"
}
with HISTORY_LOCK:
save_channel_message_to_json(channel_name, received_message)
mark_channel_as_unread(channel_name)
print(f"[Channel] Received message in '{channel_name}' from {sender}")
# 4. Acknowledge receipt
resp = Response()
resp.status_code = 200
resp.reason = 'OK'
return resp.build_response_header(request)
def mark_channel_as_unread(channel_name: str):
print(f"NOTIFICATION: Marking channel '{channel_name}' as unread.")
global UNREAD_CHANNELS
with UNREAD_CHANNELS_LOCK:
UNREAD_CHANNELS.add(channel_name)
print('[ADD TO UNREAD CHANNELS] {}'.format(UNREAD_CHANNELS))
def mark_channel_as_read(channel_name: str):
global UNREAD_CHANNELS
# Check first to avoid acquiring lock unnecessarily
if channel_name in UNREAD_CHANNELS:
print(f"NOTIFICATION: Marking channel '{channel_name}' as read.")
with UNREAD_CHANNELS_LOCK:
UNREAD_CHANNELS.remove(channel_name)
print('[RM FROM UNREAD CHANNELS] {}'.format(UNREAD_CHANNELS))
@app.route('/get-channel-history', methods=['POST'])
@protect_routes
def route_get_channel_history(request):
data = parse_custom_body(request.body)
channel_name = data.get('channel_name')
with HISTORY_LOCK:
messages = load_channel_history_from_json(channel_name)
parts = []
# Structure: sender=IP:Port&type=sent/received&message=content
for msg in messages:
sender = msg.get('sender')
raw_content = msg.get('message')
msg_type = msg.get('type')
parts.append(f"sender={sender}")
parts.append(f"message={raw_content}")
parts.append(f"type={msg_type}")
response_body = "&".join(parts)
mark_channel_as_read(channel_name)
# 5. Return Response
body_bytes = response_body.encode('utf-8')
resp = Response()
resp.status_code = 200
resp.reason = 'OK'
return resp.build_response_header(request, len(body_bytes)) + body_bytes
@app.route('/unread-channel', methods=['GET'])
@protect_routes
def route_unread_channel(request):
global UNREAD_CHANNELS
print(f"[DEBUG] route_unread_channel hit. Current set: {UNREAD_CHANNELS}", flush=True)
resp = Response()
resp.status_code = 200
resp.reason = 'OK'
if not UNREAD_CHANNELS:
return resp.build_response_header(request, 0)
parts = []
with UNREAD_CHANNELS_LOCK:
for channel_name in UNREAD_CHANNELS:
# Channels are just names, so we append them directly
parts.append(f"channel_name={channel_name}")
body = "&".join(parts)
print('[UNREAD_CHANNELS] {}'.format(UNREAD_CHANNELS))
return resp.build_response_header(request, len(body)) + body.encode()
def update_reachable_channels(raw_data):
try:
full_text = raw_data.decode()
# Extract Body from HTTP Response
if '\r\n\r\n' in full_text:
body = full_text.split('\r\n\r\n', 1)[1]
else:
body = full_text
# Initialize an empty dictionary immediately
new_channels = {}
# Only parse if there is actually data
if body.strip():
# Format: channel_name=A&member_address=IP:Port&...
pairs = body.split('&')
current_channel_name = None
for pair in pairs:
if '=' not in pair:
continue
key, value = pair.split('=', 1)
if key == 'channel_name':
current_channel_name = value
if current_channel_name not in new_channels:
new_channels[current_channel_name] = []
elif key == 'member_address':
if current_channel_name is not None:
new_channels[current_channel_name].append(value)
# Update the global dictionary regardless of whether it's empty or full
global REACHABLE_CHANNELS
REACHABLE_CHANNELS = new_channels
print(f"[CHANNEL UPDATE] Updated Reachable Channels: {REACHABLE_CHANNELS}")
except Exception as e:
print(f"[ERROR] Failed to parse channel list: {e}")
###############################
#######LOGIN & LOGOUT##########
###############################
@app.route('/logout', methods=['POST'])
def route_logout(request):
# 1. NOTIFY TRACKER (The Graceful Exit)
try:
request.body = f"peer-ip={app.ip}&peer-port={app.port}"
request.path = '/remove-peer'
raw_data = request.build_raw()
# tell tracker we are gone
tracker_communicate(raw_data)
except Exception as e:
print(f"Logout notification failed: {e}")
resp = Response()
global SESSION
SESSION = ''
return resp.build_redirect_response('/login.html', 302, 'Found')
@app.route('/login', methods=['POST', 'GET'])
@app.route('/login.html', methods=['GET'])
def route_login(request):
# request here is the req obj
resp = Response()
if request.method == 'GET':
if not check_authentication(request):
return resp.build_response(request)
else:
return resp.build_redirect_response('/index.html', 301, 'Moved Permanently')
request.path = '/login'
raw_data = request.build_raw()
print("[FROM PEER] {}".format(raw_data.decode() ) )
resp_chunk = tracker_communicate(raw_data)
global SESSION
SESSION = extract_session_value_from_response(resp_chunk.decode())
resp.cookies['session_id'] = SESSION # get session from tracker
return resp.build_redirect_response('/index.html', 301, 'Moved Permanently')
@app.route('/index.html', methods=['GET'])
def route_index(request):
"""
Handle GET / and /index.html - Protected main page.
Requires valid session authentication.
:param request: The incoming HTTP request object
:return: HTTP response bytes
"""
resp = Response()
# Check authentication
if check_authentication(request):
# Valid session - serve index.html
print("[Route] Authenticated user accessing index")
return resp.serve_static_resource(request, '/index.html')
else:
# Invalid or missing session - redirect to login
print("[Route] Unauthenticated user attempting to access index - redirecting to login")
return resp.build_redirect_response("/login.html", 301, "Moved Permanently")
@app.route('/chat.html', methods=['GET'])
def route_chat(request):
"""
Handle GET /chat.html - Protected chat page.
Requires valid session authentication.
:param request: The incoming HTTP request object
:return: HTTP response bytes
"""
resp = Response()
print("[CHAT.HTML] Request cookies: {}".format(request.cookies))
print("[CHAT.HTML] Session check: {}".format(check_authentication(request)))
# Check authentication
if check_authentication(request):
# Valid session - serve chat.html
print("[Route] Authenticated user accessing chat")
return resp.serve_static_resource(request, '/chat.html')
else:
# Invalid or missing session - redirect to login
print("[Route] Unauthenticated user attempting to access chat - redirecting to login")
return resp.build_redirect_response("/login.html", 301, "Moved Permanently")
###############################
#########JSON HISTORY##########
###############################
def get_history_filename():
# This creates a unique file for this specific running instance
# e.g., "peer_8000_history.json"
return f"peer_{app.port}_history.json"
def save_message_to_json(peer_address, msg_data):
"""
Reads the JSON file, appends the new message, and saves it back.
"""
filename = get_history_filename()
data = {"dms": {}, "channels": {}}
if os.path.exists(filename):
try:
with open(filename, 'r') as f:
loaded_data = json.load(f)
# Preserve existing data if valid
if "dms" in loaded_data: data["dms"] = loaded_data["dms"]
if "channels" in loaded_data: data["channels"] = loaded_data["channels"]
except json.JSONDecodeError:
pass
if peer_address not in data["dms"]:
data["dms"][peer_address] = []
data["dms"][peer_address].append(msg_data)
# 4. Write back to disk
with open(filename, 'w') as f:
json.dump(data, f, indent=4)
def load_history_from_json(peer_address):
"""
Reads the history for a specific peer from the JSON file.
"""
filename = get_history_filename()
if not os.path.exists(filename):
return []
try:
with open(filename, 'r') as f:
data = json.load(f)
return data.get("dms", {}).get(peer_address, [])
except (json.JSONDecodeError, KeyError):
return []
def save_channel_message_to_json(channel_name, msg_data):
"""
Reads the JSON file, saves the message specifically into the 'channels' dictionary.
"""
filename = get_history_filename()
data = {"dms": {}, "channels": {}} # Default structure
if os.path.exists(filename):
try:
with open(filename, 'r') as f:
loaded_data = json.load(f)
# Preserve existing data if valid
if "dms" in loaded_data: data["dms"] = loaded_data["dms"]
if "channels" in loaded_data: data["channels"] = loaded_data["channels"]
except json.JSONDecodeError:
pass
# --- LOGIC: Target the 'channels' key ---
if channel_name not in data["channels"]:
data["channels"][channel_name] = []
data["channels"][channel_name].append(msg_data)
# ----------------------------------------
with open(filename, 'w') as f:
json.dump(data, f, indent=4)
def load_channel_history_from_json(channel_name):
"""
Reads the history for a specific channel from the 'channels' dictionary.
"""
filename = get_history_filename()
if not os.path.exists(filename):
return []
try:
with open(filename, 'r') as f:
data = json.load(f)
# --- LOGIC: Get from 'channels' key ---
return data.get("channels", {}).get(channel_name, [])
# --------------------------------------
except (json.JSONDecodeError, KeyError):
return []
if __name__ == "__main__":
"""
Entry point for launching the backend server.
This sets up all route handlers and starts the server using create_backend.
:arg --server-ip (str): IP address to bind the server (default: 127.0.0.1).
:arg --server-port (int): Port number to bind the server (default: 9000).
"""
parser = argparse.ArgumentParser(
prog='Backend',
description='Start the backend process',
epilog='Backend daemon for http_daemon application'
)
parser.add_argument('--server-ip',
type=str,
default='0.0.0.0',
help='IP address to bind the server. Default is 0.0.0.0'
)
parser.add_argument('--peer-ip',
type=str,
default='0.0.0.0',
help='IP address to bind the server. Default is 0.0.0.0'
)
parser.add_argument(