-
Notifications
You must be signed in to change notification settings - Fork 3
/
auth-server.py
72 lines (63 loc) · 2.3 KB
/
auth-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
SERVER_HOST = '127.0.0.1'
SERVER_PORT = 1335
MAX_GET_REQUESTS = 10
import re, socket
import random
import string
MSG_AUTH_RE = re.compile('''^AUTH +(.+) +(.+)''')
MSG_GET_RE = re.compile('''^GET +(.+) +(.+)''')
MSG_RVK_RE = re.compile('''^RVK +(.+)''')
def serve(srv):
while 1:
print('[S] Waiting for new connections')
(s, address) = srv.accept()
print('[S] New connection from', address)
handle_connection(s)
print('[S] Closing connection')
s.close()
def handle_connection(s):
print('[S] Waiting for request')
auth = False
while (not auth):
req = s.recv(1024).decode().strip()
print('[S] Received: ' + req)
m = MSG_AUTH_RE.match(req)
if (m is not None):
letters = string.ascii_letters
token = ''.join(random.choice(letters) for i in range(20))
reply = 'SUCC ' + token
print('[S] Replying: ', reply)
s.sendall(str.encode(reply + '\n'))
auth = True
getRequests = 0
while(auth):
req = s.recv(1024).decode().strip()
print('[S] Received: ' + req)
m_get = MSG_GET_RE.match(req)
m_rvk = MSG_RVK_RE.match(req)
if (m_get is not None):
if (getRequests < MAX_GET_REQUESTS):
reply = 'RES content'
print('[S] Replying: ', reply)
s.sendall(str.encode(reply + '\n'))
getRequests += 1
else:
reply = 'TIMEOUT'
print('[S] Replying: ', reply)
s.sendall(str.encode(reply + '\n'))
auth = False
elif (m_rvk is not None):
auth = True
break
else:
print('[S] Invalid message')
if (__name__ == '__main__'):
# SERVER_PORT = int(argv[1])
print('[S] Auth server starting. Press Ctrl+C to quit')
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Avoid TIME_WAIT
srv.bind((SERVER_HOST, SERVER_PORT))
print('[S] Listening on ', SERVER_HOST, SERVER_PORT)
srv.listen(8)
serve(srv)
srv.close()