This repository has been archived by the owner on Aug 17, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
server.py
555 lines (431 loc) · 16.8 KB
/
server.py
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
"""Модуль сервера."""
from base64 import b64encode
from hashlib import sha256
from json import dumps
from json import loads
from os import path
from random import choice
from socket import AF_INET
from socket import SOCK_DGRAM
from socket import socket
from sqlite3 import connect
from string import ascii_letters
from string import digits
from threading import Thread
from time import sleep
from time import time
from aes_crypto import acrypt
from bcrypt import kdf
PASSWORD_EXTRA_SALT = "Pu~w9cC+RV)Bfjnd1oSbLQhjwGP)mJ$R^%+DHp(u)LP@AgMq)dl&0T\
(V$Thope)Q"
KEY_EXTRA = "LX@$wmd3l8Yt9zxj9WH8yp@DOzNrDk2^flJzzNU!%oYy3EUoXabyGF~k%5TiJBH*"
IDLE_MAX_TIME = 10
IDLE_SLEEP_TIME = 1
clients = {}
def absolute(path_: str) -> str:
"""Возвращает абсолютный путь из относительного."""
return path.normpath(path.join(
path.dirname(path.realpath(__file__)),
path_
))
def encrypt_password(user_id: int, password: str) -> str:
"""Шифрует пароль.
Аргументы:
user_id: ID пользователя.
password: Пароль пользователя.
Возвращаемое значение: Зашифрованный пароль.
"""
user_id = str((user_id + 1) ** 3)
hashed_password = b64encode(kdf(
password=sha256(
password.encode("utf8")
).digest() + PASSWORD_EXTRA_SALT.encode("utf8"),
salt=user_id.encode("utf8"),
desired_key_bytes=24,
rounds=64
)).decode("utf8").replace("=", "_")
return hashed_password
class Database:
"""Класс базы данных."""
def __init__(self, filepath: str) -> None:
"""Инициализация базы данных.
Аргументы:
filepath: Путь к базе данных.
"""
self.__con = connect(filepath)
self.__cur = self.__con.cursor()
def sql(
self,
sql_text: str,
format_=None,
noresult: bool = False
):
"""Выполняет SQL код.
Аргументы:
sql_text: SQL код.
format_: Заменители '?' в SQL коде.
noresult: Если включено, то результатом будет булевое значение.
Возвращаемое значение:
bool: Если включено noresult, возвращает True, если результат
выполнения SQL кода пустой, иначе False.
list: Массив с результатами.
tuple: Единственный результат.
"""
code = ""
results = []
if format_ is None:
format_ = []
else:
format_ = format_[::-1]
try:
sql_text = sql_text[:sql_text.index("--")]
except ValueError:
pass
for line in sql_text.split("\n"):
stripped_line = line.strip()
if len(stripped_line) == 0:
continue
code += stripped_line
if stripped_line.endswith(";"):
formats = [format_.pop() for _ in range(len(format_))]
cursor = self.__cur.execute(code, tuple(formats))
results.append(cursor.fetchall())
code = ""
self.__con.commit()
if noresult:
return all(len(result) == 0 for result in results)
if len(results) == 1:
return results[0]
return results
def reset_database(self) -> bool:
"""Сбрасывает базу данных к начальному состоянию.
Возвращаемое значение: True, если удалось сбросить, иначе False.
"""
return self.sql("""
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS direct_messages;
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name VARCHAR(16) NOT NULL,
password CHAR(32) NOT NULL
);
CREATE TABLE direct_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
sender INTEGER NOT NULL,
content TEXT NOT NULL,
receiver INTEGER NOT NULL,
read TINYINT NOT NULL DEFAULT 0
);
""", noresult=True)
def create_account(self, name: str, password: str):
"""Создаёт аккаунт.
Аргументы:
name: Логин аккаунта.
password: Пароль от аккаунта.
Возвращаемое значение: Статус выполнения, id в случае успеха.
"""
if len(name) < 1:
return 1 # ERR_SHORT_NAME
if len(name) > 16:
return 2 # ERR_LONG_NAME
if len(password) < 6:
return 3 # ERR_SHORT_PASSWORD
if not self.sql("SELECT * FROM users WHERE name = ?;", [name], True):
return 4 # ERR_ACCOUNT_EXISTS
count = self.sql("SELECT COUNT(*) FROM users;")[0][0] + 1
hashed_password = encrypt_password(count, password)
self.sql(
"INSERT INTO users (name, password) VALUES (?, ?);",
[name, hashed_password]
)
# SUCCESSFULL
return [
0,
self.sql("SELECT id FROM users WHERE name = ?;", [name])[0][0]
]
def login_account(self, name: str, password: str):
"""Входит в аккаунт.
Аргументы:
name: Логин аккаунта.
password: Пароль от аккаунта.
Возвращаемое значение: Статус выполнения, id в случае успеха.
"""
if len(name) < 1:
return 1 # ERR_SHORT_NAME
if len(name) > 16:
return 2 # ERR_LONG_NAME
if len(password) < 6:
return 3 # ERR_SHORT_PASSWORD
result = self.sql("SELECT id FROM users WHERE name = ?;", [name])
if not result:
return 4 # ERR_ACCOUNT_NOT_EXISTS
result = result[0][0]
hashed_password = encrypt_password(result, password)
if self.sql(
"SELECT * FROM users WHERE name = ? AND password = ?;",
[name, hashed_password],
True
):
return 5 # ERR_INCORRECT_PASSWORD
# SUCCESSFULL
return [
0,
self.sql("SELECT id FROM users WHERE name = ?;", [name])[0][0]
]
def get_account_data(self, name: str) -> (tuple, list):
"""Получает данные аккаунта.
Аргументы:
name: Логин аккаунта.
Возвращаемое значение:
[
Отправленные и полученные сообщения,
ID пользователей, чей статус сообщений был изменён.
].
"""
account_id = self.sql("SELECT id FROM users WHERE name = ?;", [name])
if not account_id:
return ()
account_id = account_id[0][0]
sended = self.sql(
"SELECT * FROM direct_messages WHERE sender = ?;",
[account_id]
)
received = self.sql(
"SELECT * FROM direct_messages WHERE receiver = ?;",
[account_id]
)
usernames = []
usernames_logins = {}
for smsg in sended:
if smsg[3] not in usernames:
usernames.append(smsg[3])
for rmsg in received:
if rmsg[1] not in usernames:
usernames.append(rmsg[1])
for uname in usernames:
usernames_logins[uname] = self.sql(
"SELECT name FROM users WHERE id = ?;",
[uname]
)[0][0]
status_changed = self.sql("""
SELECT sender FROM direct_messages WHERE receiver = ? AND read = 0;
""", [account_id])
st_changed = []
for id_ in status_changed:
if id_[0] not in st_changed:
st_changed.append(id_[0])
if len(st_changed) > 0:
self.sql("""
UPDATE direct_messages \
SET read = 1 \
WHERE receiver = ? AND read = 0;
""", [account_id])
return ((sended, received, usernames_logins), st_changed)
def send_message(self, login: str, receiver: int, message: str) -> bool:
"""Создаёт запись в базе данных о сообщении."""
sender_id = self.sql(
"SELECT id FROM users WHERE name = ?;",
[login]
)
exists_receiver = not self.sql(
"SELECT id FROM users WHERE id = ?;",
[receiver],
noresult=True
)
if len(sender_id) == 0:
return False
if not exists_receiver:
return False
sender_id = sender_id[0][0]
result = self.sql("""
INSERT INTO direct_messages (sender, receiver, content)
VALUES (?, ?, ?);
""", [sender_id, receiver, message], noresult=True)
self.sql("""
UPDATE direct_messages \
SET read = 2 \
WHERE receiver = ? AND sender = ? AND (read = 0 OR read = 1);
""", [sender_id, receiver])
return result
def find_user(self, username: str):
"""Ищет пользователя по username.
Аргументы:
username: Имя пользователя.
Возвращаемое значение:
False: Пользователь не найден.
list[int, str]: ID пользователя и его имя.
"""
result = self.sql("SELECT id FROM users WHERE name = ?;", [username])
if len(result) == 0:
return False
return [result[0][0], username]
def close(self) -> None:
"""Закрывает базу данных."""
self.__con.close()
class NetworkedClient:
"""Класс клиента."""
_instances = []
def __init__(self, sock: socket, addr, key: str) -> None:
self.sock: socket = sock
self.addr = addr
self.login = None
self.id_ = None
self.__password = None
self.__key = key
self.__aes = acrypt(KEY_EXTRA + self.__key)
self._instances.append(self)
def __encode_message(self, message) -> bytes:
"""Превращает объекты, преобразоваемые в JSON в байты."""
return self.__aes.encrypt(dumps(
message,
separators=(",", ":"),
ensure_ascii=False
))
def __decode_message(self, message: bytes):
"""Превращает байты в объекты, преобразоваемые в JSON."""
return loads(self.__aes.decrypt(message))
def send(self, message: list) -> None:
"""Отправляет сообщение клиенту.
Аргументы:
message: Сообщение.
"""
print("Отправлено клиенту:", message)
encoded = self.__encode_message(message)
self.sock.sendto(encoded, self.addr)
def send_account_data(self) -> None:
"""Отправляет данные об аккаунте."""
if self.login is None:
return
adata = dtb.get_account_data(self.login)
self.send(["account_data", adata[0]])
for receiver in adata[1]:
for inst in self._instances:
if inst.id_ == receiver:
inst.send_account_data()
def receive(self, jdata: bytes) -> bool:
"""Получает сообщение от клиента.
Аргументы:
jdata: Данные от клиента.
Возвращаемое значаени: Надо ли обновлять таймер сообщений?
"""
data = self.__decode_message(jdata)
if data == ["client_alive"]:
return True
print("Получено от клиента:", data)
com = data[0]
args = data[1:]
if com == "register":
result = dtb.create_account(*args[:2])
if isinstance(result, list):
status = result[0]
self.id_ = result[1]
self.send(["register_status", status])
if status == 0:
self.login, self.__password = args[:2]
elif com == "login":
result = dtb.login_account(*args[:2])
if isinstance(result, list):
status = result[0]
self.id_ = result[1]
self.send(["login_status", status])
if status == 0:
self.login, self.__password = args[:2]
elif com == "disconnect":
self.close()
return False
elif not (self.login is None and self.__password is None):
if com == "get_account_data":
self.send_account_data()
elif com == "send_message":
msg = args[0][:65535]
dtb.send_message(self.login, args[1], msg)
self.send_account_data()
for instance in self._instances:
if args[1] == instance.login:
instance.send_account_data()
break
elif com == "find_user":
if args[0] == self.login:
self.send(["find_user_result", False])
else:
self.send(["find_user_result", dtb.find_user(args[0])])
else:
return False
elif com in ["get_account_data", "send_message", "find_user"]:
self.send(["not_logged"])
return False
else:
return False
return True
def close(self) -> None:
"""Закрывает соединение с клиентом."""
del clients[self.addr]
dtb = Database(absolute("messenger.db"))
def check_idle() -> None:
"""Отключает неактивных клиентов.
Аргументы:
clients: Словарь всех клиентов.
"""
while True:
inactive_clients = []
for client in clients.values():
if client[1] < time() - IDLE_MAX_TIME:
inactive_clients.append(client[0])
for client in inactive_clients:
client.close()
sleep(IDLE_SLEEP_TIME)
def main() -> None:
"""Основная функция."""
sock = socket(AF_INET, SOCK_DGRAM)
sock.bind(("0.0.0.0", 7505))
print("Сервер запущен")
Thread(target=check_idle, daemon=True).start()
with sock:
while True:
try:
adrdata = sock.recvfrom(70000)
except (ConnectionResetError, ConnectionAbortedError):
continue
data = adrdata[0]
addr = adrdata[1]
key = None
print("<", data)
if addr not in clients:
key = "".join(
[choice(ascii_letters + digits) for _ in range(64)]
)
clients[addr] = [
NetworkedClient(sock, addr, key),
time() - IDLE_MAX_TIME + 5
]
if data == b"\x05\x03\xff\x01":
key = key.encode("ascii")
sock.sendto(key, addr)
print(">", key)
key = None
else:
try:
if clients[addr][0].receive(data):
clients[addr][1] = time()
except BaseException as exc:
clients[addr][0].close()
print(exc)
dtb.close()
if __name__ == "__main__":
# dtb.reset_database()
# print(len(dtb.create_account("Werryx", "123456")) > 1)
# print(len(dtb.create_account("Werland", "123456")) > 1)
# print(len(dtb.create_account("zhbesluk", "123456")) > 1)
# print(len(dtb.create_account("WTest", "123456")) > 1)
# print(dtb.sql("""
# INSERT INTO direct_messages (sender, receiver, content) VALUES
# (2, 1, "Привет, я Werland"),
# (2, 1, ?),
# (1, 2, "Я - Werryx"),
# (2, 1, "Как дела?"),
# (3, 1, "Помнишь?"),
# (1, 2, "Нормально"),
# (4, 1, "TEST");
# """, [f"А ты?{' ОЧЕНЬ ДЛИННАЯ СТРОКА!' * 20}"], noresult=True))
# print(dtb.sql("SELECT * FROM direct_messages;"))
main()