-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.py
277 lines (205 loc) · 8.7 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
# -*- coding: utf-8 -*-
# @Author: amaneureka
# @Date: 2017-04-01 16:07:30
# @Last Modified by: amaneureka
# @Last Modified time: 2017-04-13 18:20:51
import sys
import uuid
import socket
import select
import logging
import hashlib
import configparser
import sqlite3 as sql
from time import sleep
from enum import Enum
class REQUEST(Enum):
# S2C --> Server to Client
# C2S --> Client to Server
IDENTIFY = 'IDY' # S2C : Prove your identity
REGISTER = 'REG' # C2S : Register me as a new device
INVALID = 'INV' # C2S : Invalid Request
LOGIN = 'LOG' # C2S : Login me with my UID
UID = 'UID' # S2C : Here is your new UID
HELLO = 'HLO' # S2C : Hello! login successful
COMMAND = 'CMD' # S2C : Execute Command
RESPONSE = 'RSP' # C2S : Response of Command
SAVE = 'SAV' # C2S : Save Response
ACKNOWLEDGE = 'ACK' # S2C : Response Recieved
PING = 'PNG' # C2S : Ping
PONG = 'POG' # S2C : Pong
def get_request_header(data):
try:
res = REQUEST(data)
except:
res = REQUEST.INVALID
return res
def send_request(sock, request, data=''):
logging.debug('[%s] \'%s\' sent', str(sock.getpeername()), request.name)
sock.send(request.value + str(data))
def register_new_device(connection, key):
cursor = connection.cursor()
t = (key, )
cursor.execute('INSERT INTO clients (key) VALUES (?)', t)
connection.commit()
def get_device_id_from_key(connection, key):
cursor = connection.cursor()
t = (key, )
row = cursor.execute('SELECT id FROM clients WHERE key=?', t).fetchone()
if row is None:
return None
return row[0]
def setup_database(connection):
cursor = connection.cursor()
t = (str(uuid.uuid4()), )
cursor.execute('''
CREATE TABLE IF NOT EXISTS clients
(
id INTEGER primary key NOT NULL,
key VARCHAR
);''');
cursor.execute('''
CREATE TABLE IF NOT EXISTS logs
(
id INTEGER primary key NOT NULL,
client_id INTEGER,
response VARCHAR
);''');
try:
cursor.execute('INSERT INTO clients (id, key) VALUES (0, ?);', t)
except:
pass
connection.commit()
def start_server():
server_config = config['Server']
# configurations
HOST = server_config['HOST']
PORT = server_config.getint('PORT')
BUFFER_SIZE = server_config.getint('BUFFER_SIZE')
# server socket setup
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(server_config.getint('LIMIT'))
# server database setup
sql_connection = sql.connect(server_config['DATABASE'])
setup_database(sql_connection)
LABEL_2_ID = { }
ID_2_SOCKET = { }
SOCKET_LIST = []
SOCKET_PENDING_DATA = { }
SOCKET_LIST.append(server_socket)
logging.info('server started %s:%d', HOST, PORT)
while True:
# list of sockets which are ready to read
ready_to_read, _, _ = select.select(SOCKET_LIST, [], [], 0)
for sock in ready_to_read:
# new connection
if sock == server_socket:
sockfd, addr = server_socket.accept()
logging.info('[%s:%s] connected' % addr)
# send 'IDENTIFY' request
try:
send_request(sockfd, REQUEST.IDENTIFY)
SOCKET_LIST.append(sockfd)
try:
send_request(ID_2_SOCKET[0], REQUEST.PONG, '\'%s:%s\' Joined!\n' % addr)
except:
pass
except:
logging.info('[%s:%s] disconnected')
# message from client
else:
# process data
try:
data = sock.recv(BUFFER_SIZE)
header = get_request_header(data[:3])
label = str(sock.getpeername())
logging.debug('[%s] requested \'%s\'', label, header.name)
if sock in SOCKET_PENDING_DATA and SOCKET_PENDING_DATA[sock] > 0:
length = SOCKET_PENDING_DATA[sock] - len(data)
if length < 0:
raise ValueError('invalid response size')
SOCKET_PENDING_DATA[sock] = length
try:
ID_2_SOCKET[0].send(data)
send_request(sock, REQUEST.ACKNOWLEDGE)
except:
if 0 in ID_2_SOCKET[0]:
ID_2_SOCKET[0].close()
ID_2_SOCKET.pop(0, None)
elif header == REQUEST.REGISTER:
key = str(uuid.uuid4())
register_new_device(sql_connection, key)
send_request(sock, REQUEST.UID, key)
elif header == REQUEST.LOGIN:
key = data[3:].strip()
logging.debug('\tkey \'%s\'', key)
device_id = get_device_id_from_key(sql_connection, key)
if device_id is None:
send_request(sock, REQUEST.INVALID)
logging.debug('\tlogin failed')
continue
logging.debug('\tdevice id \'%s\'', device_id)
LABEL_2_ID[label] = device_id
ID_2_SOCKET[device_id] = sock
send_request(sock, REQUEST.HELLO)
elif header == REQUEST.PING:
if label not in LABEL_2_ID or LABEL_2_ID[label] != 0:
continue
for key in ID_2_SOCKET:
if ID_2_SOCKET[key] in SOCKET_LIST:
send_request(sock, REQUEST.PONG, str(key) + '\n')
elif header == REQUEST.RESPONSE:
if label not in LABEL_2_ID:
continue
try:
length = int(data[3:10]) - len(data)
logging.debug('\tlength \'%d\'', length)
if length < 0:
raise ValueError('invalid response size')
SOCKET_PENDING_DATA[sock] = length
ID_2_SOCKET[0].send(data)
send_request(sock, REQUEST.ACKNOWLEDGE)
except:
if 0 in ID_2_SOCKET[0]:
ID_2_SOCKET[0].close()
ID_2_SOCKET.pop(0, None)
elif header == REQUEST.SAVE:
if label not in LABEL_2_ID:
continue
device_id = LABEL_2_ID[label]
response = data[3:]
logging.debug('\tsave \'%s\'', response)
try:
t = (device_id, response, )
cursor = sql_connection.cursor()
cursor.execute('INSERT INTO logs (client_id, response) VALUES (?, ?);', t)
sql_connection.commit()
except Exception as e:
logging.error('error while logging data' + str(e))
elif header == REQUEST.COMMAND:
if label not in LABEL_2_ID or LABEL_2_ID[label] != 0:
continue
request_id = int(data[3:7])
cmd = data[7:]
logging.debug('\t%s', cmd)
if request_id not in ID_2_SOCKET:
send_request(sock, REQUEST.INVALID)
logging.debug('\tdevice not found')
continue
send_request(ID_2_SOCKET[request_id], REQUEST.COMMAND, cmd)
else:
raise ValueError('Invalid Header \'' + str(data + '\''))
except Exception as error:
if sock in SOCKET_LIST:
SOCKET_LIST.remove(sock)
SOCKET_PENDING_DATA.pop(sock, None)
logging.error(str(error))
sleep(0.01)
server_socket.close()
if __name__ == '__main__':
config = configparser.ConfigParser()
config.read('config.ini')
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
sys.exit(start_server())