-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
374 lines (270 loc) · 13.6 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
"""
Multi-Threaded Server
Python 3.7
Usage: python server.py server_port block_duration timeout
coding: utf-8
Author: Yuanyuan Luo
"""
from socket import *
from threading import *
from datetime import datetime
import sys, select
import re as regular
import time
import datetime as dt
if len(sys.argv) != 4:
print("\n===== Error usage, python server.py server_port block_duration timeout ======\n");
exit(0);
serverPort,blockDuration,timeout=int(sys.argv[1]),int(sys.argv[2]),int(sys.argv[3])
blacklistedUsers = {}
addresses = {}
loginHistory = {}
connections = {}
offlineDeliveries = {}
blockedUsers = []
def main():
# socket family: AF_INET, socket type: SOCK_STREAM (connection-oriented)
serverSocket = socket(AF_INET, SOCK_STREAM)
# bind the port to listen on
serverSocket.bind(('', serverPort))
# start listening, can queue up five links
serverSocket.listen(5)
while True:
client, address = serverSocket.accept()
privatePort = int(client.recv(1024).decode())
Thread(target = verifyUsername, args = (client, address, privatePort)).start()
def verifyUsername(client, address, privatePort):
message = 'Username: '
client.sendall(message.encode())
response = client.recv(1024)
response = response.decode()
file = open('credentials.txt', 'r')
isValid = False
for line in file:
command = regular.search('^(%s) (.*)$'%(response), line)
if command:
isValid = True
username = command.group(1)
password = command.group(2)
file.close()
if isValid==False:
message = 'Invalid Username. Please try again\n'
client.sendall(message.encode())
verifyUsername(client, address, privatePort)
else:
verifyPassword(client, address, username, password, privatePort)
return
def verifyPassword(client, address, username, password, privatePort):
loginStatus = False
maxAttempts = 3
for i in range(1,maxAttempts+1):
message = 'password: {0} msg: Password: '.format(username)
client.sendall(message.encode())
response = client.recv(1024)
response = response.decode()
if (response == password):
if username in blockedUsers:
message = 'Your account is blocked due to multiple login failures. Please try again later\n'
break
elif username in connections:
message = 'This account is already logged in elsewhere. Please logout and try again\n'
break
else:
message = 'Welcome to the greatest messaging application ever!\n'
client.sendall(message.encode())
loginStatus = True
break
else:
if (i < maxAttempts):
message = 'Invalid Password. Please try again\n'
client.sendall(message.encode())
else:
message = 'Invalid Password. Your account has been blocked. Please try again later\n'
blockedUsers.append(username)
Timer(blockDuration, lambda block: blockedUsers.remove(username), args = [username]).start()
break
if loginStatus:
serverOperate(client, address, username, password, privatePort)
else:
client.sendall(message.encode())
client.close()
def serverOperate(client, address, username, password, privatePort):
loginHistory[username] = True
flag=1
presenceBroadcast = '%s logged in\n'%(username)
for user in connections:
if not(user in blacklistedUsers and username in blacklistedUsers[user]):
connections[user].sendall(presenceBroadcast.encode())
connections[username] = client
if username in offlineDeliveries:
for message in offlineDeliveries[username]:
client.sendall(message.encode())
del offlineDeliveries[username]
addresses[username] = (address[0], privatePort)
try:
client.settimeout(timeout)
while True:
response = client.recv(1024)
if response:
response = response.decode()
if response == 'logout':
raise error('Client logout')
if response == 'whoelse':
for user in connections:
if user != username:
client.sendall((user + '\n').encode())
continue
command = regular.search(r'^message (\S+) (.*)$', response)
if command:
user = command.group(1)
message = command.group(2)
formattedMessage = '{}: {}\n'.format(username, message)
if user == username:
message = 'Error. Cannot message self\n'
client.sendall(message.encode())
elif username in blacklistedUsers and user in blacklistedUsers[username]:
message = 'Your message could not be delivered as the recipient has blocked you\n'
client.sendall(message.encode())
elif user in connections:
connections[user].sendall(formattedMessage.encode())
else:
credentials = open('credentials.txt', 'r')
exists = False
for line in credentials:
command = regular.search('^{} .*$'.format(user), line)
if command:
exists = True
credentials.close()
if not exists:
message = 'Error. Invalid user\n'
client.sendall(message.encode())
else:
if user in offlineDeliveries:
offlineDeliveries[user].append(formattedMessage)
else:
offlineDeliveries[user] = [formattedMessage]
continue
command = regular.search('^broadcast (.*)$', response)
if command:
message = command.group(1)
broadcast = '{}: {}\n'.format(username, message)
someBlocked = False
for user in connections:
if username in blacklistedUsers and user in blacklistedUsers[username]:
someBlocked = True
elif user != username:
connections[user].sendall(broadcast.encode())
if someBlocked:
message = 'Your message could not be delivered to some recipients\n'
client.sendall(message.encode())
continue
command = regular.search('^whoelsesince ([0-9]+)$', response)
if command:
seconds = int(command.group(1))
currentTime = datetime.now()
for user in loginHistory:
if user != username and (loginHistory[user] == True or (currentTime - loginHistory[user]).total_seconds() < seconds):
client.sendall((user + '\n').encode())
continue
command = regular.search(r'^block (\S+)$', response)
if command:
user = command.group(1)
if user == username:
message = 'Error. Cannot block self\n'
client.sendall(message.encode())
else:
credentials = open('credentials.txt', 'r')
exists = False
for line in credentials:
command = regular.search('^{} .*$'.format(user), line)
if command:
exists = True
break
credentials.close()
if exists:
if user not in blacklistedUsers:
blacklistedUsers[user] = [username]
else:
blacklistedUsers[user].append(username)
message = '%s is blocked\n'%(user)
client.sendall(message.encode())
else:
message = 'Error. Invalid user\n'
client.sendall(message.encode())
continue
command = regular.search(r'^unblock (\S+)$', response)
if command:
user = command.group(1)
if user == username:
message = 'Error. Cannot unblock self\n'
client.sendall(message.encode())
else:
credentials = open('credentials.txt', 'r')
exists = False
for line in credentials:
command = regular.search('^%s .*$'%(user), line)
if command:
exists = True
break
credentials.close()
if exists:
if user in blacklistedUsers and username in blacklistedUsers[user]:
blacklistedUsers[user].remove(username)
message = '%s is unblocked\n'%(user)
client.sendall(message.encode())
else:
message = 'Error. %s was not blocked\n'%(user)
client.sendall(message.encode())
else:
message = 'Error. Invalid user\n'
client.sendall(message.encode())
continue
command = regular.search(r'^startprivate (\S+)$', response)
if command:
user = command.group(1)
if user == username:
message = 'Error. Cannot private message self\n'
client.sendall(message.encode())
elif username in blacklistedUsers and user in blacklistedUsers[username]:
message = 'Cannot commence private messaging as the recipient has blocked you\n'
client.sendall(message.encode())
elif user in connections:
message = 'startprivate: {0} {1} {2} msg: Start private messaging with {2}\n'.format(addresses[user][0], addresses[user][1], user)
client.sendall(message.encode())
else:
credentials = open('credentials.txt', 'r')
exists = False
for line in credentials:
command = regular.search('^%s .*$'%(user), line)
if command:
exists = True
break
credentials.close()
if exists:
message = 'Cannot start private messaging since %s is offline\n'%(user)
else:
message = 'Error. Invalid user\n'
client.sendall(message.encode())
continue
command = regular.search(r'^stopprivate (\S+)$', response)
if command:
user = command.group(1)
message = 'stopprivate: %s msg: Private messaging with %s has ended\n'%(user, username)
client.sendall(message.encode())
continue
message = 'Error. Invalid command\n'
client.sendall(message.encode())
else:
raise error('Client timeout')
except:
if flag:
client.close()
del connections[username]
presenceBroadcast = '%s logged out\n'%(username)
else:
raise error('Client timeout')
for user in connections:
if(user in blacklistedUsers and username in blacklistedUsers[user]):continue
connections[user].sendall(presenceBroadcast.encode())
loginHistory[username] = datetime.now()
main()