-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat.py
More file actions
208 lines (169 loc) · 7.46 KB
/
Copy pathchat.py
File metadata and controls
208 lines (169 loc) · 7.46 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
# File: chat.py
# Function: Cross-domain chat tool GUI based on L2-VPN
# Author: Cyans from Chang'an University
import tkinter as tk
from tkinter import scrolledtext, messagebox, font
import socket
import threading
import os
import sys
import subprocess
import time
import datetime
# ==================== User Configuration ====================
ROLE = 'A' # 'A' or 'B'
SERVER_IP = "" # <--- Please fill in your Server IP here
SERVER_PORT = "9999"
INTERFACE_NAME = "qwq"
CHAT_PORT = 12345
if ROLE == 'A':
MY_NAME = "Alice"
MY_VIRTUAL_IP = "10.0.0.1"
TARGET_IP = "10.0.0.2"
else:
MY_NAME = "Bob"
MY_VIRTUAL_IP = "10.0.0.2"
TARGET_IP = "10.0.0.1"
# ============================================================
class QwQChatApp:
def __init__(self, root):
self.root = root
self.root.title(f"QwQ L2-Link - {MY_NAME}")
self.root.geometry("700x550")
if os.geteuid() == 0:
messagebox.showwarning("Launch Error", "Do NOT run with sudo!\nRun directly: python3 chat.py\n(We will ask for sudo password later)")
sys.exit(1)
self.bg_color = "#F5F5F5"
self.chat_bg_color = "#EBEDF0"
self.my_msg_color = "#0099FF"
self.peer_msg_color = "#333333"
self.root.configure(bg=self.bg_color)
if not self.pre_auth_sudo():
sys.exit(1)
self.vpn_process = None
self.init_system()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
self.sock.bind((MY_VIRTUAL_IP, CHAT_PORT))
except Exception as e:
messagebox.showerror("Error", f"Port bind failed: {e}")
self.cleanup()
sys.exit(1)
self.setup_ui()
self.stop_event = threading.Event()
self.recv_thread = threading.Thread(target=self.receive_loop, daemon=True)
self.recv_thread.start()
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
def pre_auth_sudo(self):
print("\n" + "="*50)
print("[Sudo Request] Please enter sudo password to start VPN core:")
print("Note: Password will not be visible. Press Enter after typing.")
print("="*50 + "\n")
ret = os.system("sudo -v")
if ret != 0:
print("\n[X] Password incorrect or cancelled. Exiting.")
return False
print("\n[V] Authorization successful! Starting GUI...")
return True
def run_sudo(self, cmd):
return os.system(f"sudo {cmd}")
def init_system(self):
self.run_sudo("killall -9 client 2>/dev/null")
self.run_sudo(f"ip link delete {INTERFACE_NAME} 2>/dev/null")
time.sleep(0.5)
if not os.path.exists("./client"):
print("[*] Compiling C client...")
ret = os.system("gcc client.c tap.c -o client -lpthread")
if ret != 0:
messagebox.showerror("Error", "Compilation failed")
sys.exit(1)
print(f"[*] Starting background VPN connection to {SERVER_IP}...")
self.vpn_process = subprocess.Popen(
["sudo", "./client", SERVER_IP, SERVER_PORT],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
time.sleep(1)
if self.vpn_process.poll() is not None:
messagebox.showerror("Connection Failed", "VPN Core failed to start!\nPlease check Server IP.")
sys.exit(1)
self.run_sudo(f"ip addr add {MY_VIRTUAL_IP}/24 dev {INTERFACE_NAME}")
self.run_sudo(f"ip link set {INTERFACE_NAME} up")
print(f"[*] Network Ready! Local IP: {MY_VIRTUAL_IP}")
def setup_ui(self):
try:
self.custom_font = font.Font(family="Microsoft YaHei", size=11)
except:
self.custom_font = font.Font(family="Arial", size=11)
top_frame = tk.Frame(self.root, bg=self.my_msg_color, height=40)
top_frame.pack(fill=tk.X, side=tk.TOP)
tk.Label(top_frame, text=f"Encrypted Chat with {TARGET_IP}", bg=self.my_msg_color, fg="white", font=("Arial", 10, "bold")).pack(pady=8)
bottom_frame = tk.Frame(self.root, bg="white", height=50)
bottom_frame.pack(fill=tk.X, side=tk.BOTTOM)
self.msg_entry = tk.Entry(bottom_frame, font=("Arial", 12), bd=0, bg="#F0F0F0", relief=tk.FLAT)
self.msg_entry.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=15, pady=15)
self.msg_entry.bind("<Return>", lambda event: self.send_msg())
self.msg_entry.focus_set()
send_btn = tk.Button(bottom_frame, text="Send", command=self.send_msg, bg=self.my_msg_color, fg="white", font=("Arial", 10, "bold"), relief=tk.FLAT, padx=20)
send_btn.pack(side=tk.RIGHT, padx=10, pady=10)
self.chat_display = scrolledtext.ScrolledText(
self.root, state='disabled', font=self.custom_font, bg=self.chat_bg_color, bd=0, padx=10, pady=10
)
self.chat_display.pack(padx=0, pady=0, fill=tk.BOTH, expand=True)
self.chat_display.tag_config('me', foreground=self.my_msg_color, justify='right', rmargin=10)
self.chat_display.tag_config('peer', foreground=self.peer_msg_color, justify='left', lmargin1=10, lmargin2=10)
self.chat_display.tag_config('system', foreground='#999999', justify='center', font=("Arial", 9))
def append_msg(self, name, msg, tag):
self.chat_display.config(state='normal')
now = datetime.datetime.now().strftime("%H:%M")
if tag == 'me':
self.chat_display.insert(tk.END, f"{now} {name}\n", tag)
self.chat_display.insert(tk.END, f"{msg}\n\n", tag)
else:
self.chat_display.insert(tk.END, f"{name} {now}\n", tag)
self.chat_display.insert(tk.END, f"{msg}\n\n", tag)
self.chat_display.see(tk.END)
self.chat_display.config(state='disabled')
def append_system_msg(self, msg):
self.chat_display.config(state='normal')
self.chat_display.insert(tk.END, f"\n=== {msg} ===\n\n", 'system')
self.chat_display.config(state='disabled')
def send_msg(self):
msg = self.msg_entry.get().strip()
if not msg:
return
try:
self.sock.sendto(msg.encode('utf-8'), (TARGET_IP, CHAT_PORT))
self.append_msg("Me", msg, 'me')
self.msg_entry.delete(0, tk.END)
except Exception as e:
self.append_system_msg(f"Send Failed: {e}")
def receive_loop(self):
while not self.stop_event.is_set():
try:
self.sock.settimeout(1.0)
try:
data, addr = self.sock.recvfrom(4096)
msg_text = data.decode('utf-8')
self.chat_display.after(0, self.append_msg, "Peer", msg_text, 'peer')
except socket.timeout:
continue
except UnicodeDecodeError:
self.chat_display.after(0, self.append_msg, "Peer", "[Non-text data]", 'peer')
except Exception as e:
print(f"Receive error: {e}")
break
def cleanup(self):
if self.vpn_process:
self.run_sudo("kill -TERM " + str(self.vpn_process.pid))
self.run_sudo("killall -9 client 2>/dev/null")
self.run_sudo(f"ip link delete {INTERFACE_NAME} 2>/dev/null")
def on_closing(self):
self.stop_event.set()
self.cleanup()
self.root.destroy()
sys.exit(0)
if __name__ == "__main__":
root = tk.Tk()
app = QwQChatApp(root)
root.mainloop()