/
client_manager.py
286 lines (266 loc) · 9.32 KB
/
client_manager.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
import hmac
import json
import socket
import threading
import time
from model.category import Category
from model.ibai_exceptions import *
from model.auction import Auction
from utils import error_print, debug_print
def synchronized(l):
"""Synchronizer decorator
:param l: lock variable
:return: function decorated with lock
"""
def wrap(funct):
def LockedFunction(*args, **kw):
l.acquire()
try:
return funct(*args, **kw)
finally:
l.release()
return LockedFunction
return wrap
myLock = threading.Lock()
class ClientManager(threading.Thread):
"""
This class manage the communication with the single client
"""
def __init__(self, cs, address, auct):
"""Initalize the Client Manager
:param cs: client socket
:param address: remote address
:param auct: reference to the auction object
"""
threading.Thread.__init__(self)
self._address = address
self._cs = cs
self._auct = auct
self.logged = False
self.user = None
self.go = True
def run(self):
"""Main loop of the Thread, here listens for the client msgs
:return: return when the connnection closes
"""
while(self.go):
try:
msg = self._cs.recv(1024)
except socket.error:
return
if msg == "":
self.go = False
else:
msgs = msg.split('\r\n')
msgs.pop() # remove last msg
for l in msgs:
self.read_command(l)
self._cs.close()
def read_command(self, line):
"""Read a message received by socket and perform the right command
:param line: line read on the socket
:return: return when it has been executed
"""
json_d = json.loads(line)
if json_d['msg_id'] == 11: # Login
self.login(json_d['user'], json_d['pass'])
return
if json_d['msg_id'] == 12: # Logout
self.go = False
return
if not self.check_session(json_d):
# invalid session
return
if json_d['msg_id'] == 31: # Register category
self.register(json_d['category'])
return
if json_d['msg_id'] == 41: # Register auction
self.sell(json_d['category'], json_d['product'], json_d['price'])
return
if json_d['msg_id'] == 51: # Make a bid
self.buy(json_d['category'], json_d['product'], json_d['price'])
return
if json_d['msg_id'] == 52: # Remove last bid
self.unbuy(json_d['category'], json_d['product'])
return
if json_d['msg_id'] == 53: # Remove last bid
self.close_bid(json_d['category'], json_d['product'])
return
if json_d['msg_id'] == 21: # Register the endpoint for push notif
self.user.update_notif_socket(json_d['host'], json_d['port'])
try:
self.user.notify(1, "Notifiche attivate")
self.response(1, "Notifiche ok")
except Exception, e:
self.response(0, "Erorre connessione notifiche")
return
self.response(-1, "Comando non valido")
return
def check_session(self, session):
if 'token' not in session.keys() or not session['token']:
self.response(3, "Errore, sessione invalida")
return False
session = session['token']
# check if the session is expired
if(int(session['expire']) - time.time() < 0):
self.response(2, "Errore, sessione scaduta")
return False
server_mac = hmac.new(self._auct._key)
server_mac.update(session['username'])
server_mac.update(session['expire'])
# check if the session token is valid
if(hmac.compare_digest(server_mac.hexdigest(), str(session['token']))):
return True
else:
self.response(3, "Errore, sessione non valida")
print "UNAUTHORIZED"
return False
def gen_session(self):
"""Generate the session tocken for the logged user
:return: json session token
"""
now = time.time()
# add 24h to the current time 60*60*24
expire = str(int(now + 86400))
mac = hmac.new(self._auct._key)
mac.update(self.user.name)
mac.update(expire)
session = {"username": self.user.name, "expire": expire, "token": mac.hexdigest()}
return session
def login(self, user, pwd):
"""
Log a user on the server
:param user: username
:param pwd: MD5 hash of the password
"""
username = user
try:
self.user = self._auct._users[username]
token = ""
if self.user.password == pwd:
# Login effettuato
self.logged = True
self.response(1, token=self.gen_session())
return
debug_print("Password non valida")
self.response(0, "Password non valida", token="")
except KeyError, e:
error_print("Utente non trovato")
self.response(0, "Utente non trovato", token="")
@synchronized(myLock)
def register(self, cat_name):
"""Register a new category
:param cat_name: category name
"""
if not cat_name:
self.response(0, res_msg="Invalid category name")
return
if cat_name in self._auct._categories:
self.response(0, res_msg="Categoria gia' esistente")
return
try:
self._auct._categories[cat_name] = Category(cat_name)
except Exception, e:
self.response(0, "Categoria non valida")
finally:
self.response(1)
@synchronized(myLock)
def sell(self, cat_name, prod_name, price):
""" Add a new product on the server
:param cat_name: category name
:param prod_name: product name
:param price: base price for the auction
"""
print "Selling: "
print price
try:
cat = Category.search_category(self._auct._categories, cat_name)
a = Auction(prod_name, price, self.user)
cat.add_auction(a)
self.response(1)
except CategoryException, e:
debug_print(e)
self.response(0, res_msg=str(e))
except AuctionException, e:
self.response(3, res_msg=str(e))
@synchronized(myLock)
def buy(self, cat_name, prod_name, price):
""" Place a bid on a product
:param cat_name: category name
:param prod_name: product name
:param price: value of the bid
"""
try:
cat = Category.search_category(self._auct._categories, cat_name)
auct = cat.search_auction(prod_name)
auct.bid(price=price, user=self.user)
self.response(1)
except UserException, e:
self.response(5, res_msg=str(e))
except CategoryException, e:
debug_print(e)
self.response(4, res_msg="Category not found")
except ExistingAuctionException, e:
self.response(5, res_msg="Auction not found")
@synchronized(myLock)
def unbuy(self, cat_name, prod_name):
""" Remove our last offer only if it's the highest
:param cat_name: category name
:param prod_name: product name
"""
try:
cat = Category.search_category(self._auct._categories, cat_name)
auct = cat.search_auction(prod_name)
auct.unbid(self.user)
self.response(1)
except CategoryException, e:
debug_print(e)
self.response(0)
except AuctionException, e:
debug_print(e)
self.response(3)
@synchronized(myLock)
def close_bid(self, cat_name, prod_name):
""" Close a bid
:param cat_name: category name
:param prod_name: product name
"""
print "Closing bid " + prod_name
try:
cat = Category.search_category(self._auct._categories, cat_name)
auct = cat.search_auction(prod_name)
auct.close(self.user)
cat.del_auction(auct)
self.response(1)
except CategoryException, e:
# Not matching category
error_print(e)
self.response(0)
except AuctionException, e:
# No Winner
error_print(e)
self.response(8)
except ExistingAuctionException, e:
#No auction
error_print(e)
self.response(5)
except UserException, e:
#User not allowed to close
error_print(e)
self.response(7)
def response(self, response, res_msg="", token={}):
"""Compose a generic response
:param response: response code
:param res_msg: response message
:param token: optional, token of the session
"""
payload = {
'msg_id': -1,
'response': response,
}
if(res_msg):
payload['res_msg'] = res_msg
if(token):
payload['token'] = token
json_d = json.dumps(payload) + "\r\n"
self._cs.send(json_d)