-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
143 lines (109 loc) · 3.97 KB
/
client.py
File metadata and controls
143 lines (109 loc) · 3.97 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
import socket
import threading
import ssl
import os
import time
from protocol import send_json, recv_json
from encryption_utils import encrypt_message, decrypt_message, set_key
HOST = "10.207.26.156"
PORT = 5000
def receive_messages(sock):
buffer = ""
while True:
try:
messages, buffer = recv_json(sock, buffer)
for data in messages:
msg_type = data.get("type")
if msg_type == "message":
print(f"[{data['sender']}]: {data['content']}")
elif msg_type == "private":
print(f"[PRIVATE from {data['from']}]: {data['content']}")
elif msg_type == "secret":
decrypted = decrypt_message(data["content"])
print(f"[SECRET from {data['from']}]: {decrypted}")
elif msg_type == "info":
print(f"[INFO]: {data['message']}")
elif msg_type == "file":
os.makedirs("received_files", exist_ok=True)
filename = "received_files/" + data["filename"]
filesize = data["filesize"]
remaining = filesize
with open(filename, "wb") as f:
while remaining > 0:
chunk = sock.recv(min(4096, remaining))
f.write(chunk)
remaining -= len(chunk)
print(f"[FILE RECEIVED]: {filename}")
except Exception as e:
print("Receive error:", e)
break
def start_client():
key = b'oGk8-xGWT0PhL0ek9rhQ1xgGjkVaawX8EhAHfy5bHmQ='
set_key(key)
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
raw_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
secure_sock = context.wrap_socket(raw_sock)
secure_sock.connect((HOST, PORT))
print("Connected with cipher:", secure_sock.cipher())
threading.Thread(target=receive_messages, args=(secure_sock,), daemon=True).start()
username = input("Enter username: ")
room = input("Enter room: ")
send_json(secure_sock, {
"type": "join",
"username": username,
"room": room
})
while True:
msg = input()
if msg == "/exit":
secure_sock.close()
break
elif msg.startswith("/private"):
parts = msg.split(" ", 2)
if len(parts) < 3:
print("Usage: /private user message")
continue
send_json(secure_sock, {
"type": "private",
"to": parts[1],
"content": parts[2]
})
elif msg.startswith("/secret"):
parts = msg.split(" ", 2)
if len(parts) < 3:
print("Usage: /secret user message")
continue
encrypted = encrypt_message(parts[2])
send_json(secure_sock, {
"type": "secret",
"to": parts[1],
"content": encrypted
})
elif msg.startswith("/file"):
parts = msg.split(" ", 1)
if len(parts) < 2 or not os.path.exists(parts[1]):
print("Invalid file")
continue
filepath = parts[1]
filesize = os.path.getsize(filepath)
filename = os.path.basename(filepath)
send_json(secure_sock, {
"type": "file",
"filename": filename,
"filesize": filesize,
"room": room
})
time.sleep(0.1)
with open(filepath, "rb") as f:
while chunk := f.read(4096):
secure_sock.sendall(chunk)
else:
send_json(secure_sock, {
"type": "message",
"room": room,
"content": msg
})
if __name__ == "__main__":
start_client()