-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
70 lines (60 loc) · 1.72 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
import OpenSSL
import socket
import signal
import sys
from messenger import *
import logging
logging.basicConfig(level=logging.DEBUG)
conn = None
sock = None
def signal_handler(signal, frame):
print('Ctrl+C pressed! Closing the socket.')
try:
if conn:
conn.shutdown()
if sock:
sock.close()
except:
pass
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('0.0.0.0', 8009))
sock.listen(5)
context = OpenSSL.SSL.Context(OpenSSL.SSL.SSLv23_METHOD)
context.use_certificate_file('cert.pem')
context.use_privatekey_file('key.pem')
while True:
client_sock, fromaddr = sock.accept()
conn = OpenSSL.SSL.Connection(context, client_sock)
conn.set_accept_state()
accepted = False
try:
conn.do_handshake()
accepted = True
print('Connection accepted from', fromaddr)
except OpenSSL.SSL.Error as e:
print(f"Handshake failed: {e}")
continue
if accepted:
try:
while True:
try:
data = conn.recv(1024)
except OpenSSL.SSL.Error as e:
print(f"SSL error occurred: {e}")
break
except Exception as e:
print(f"Unexpected error occurred: {e}")
break
if data:
print('Received:', data)
should_close = handle_received_data(data, conn)
if should_close:
conn.shutdown()
break
else:
break
finally:
#conn.shutdown()
pass