-
Notifications
You must be signed in to change notification settings - Fork 0
/
task3_server_4968_5758.py
253 lines (219 loc) · 8.01 KB
/
task3_server_4968_5758.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
import socket
import select
import re
#Description: Send global message
#Parameters: dictionary/list/tuple, string, boolean
#Return: nil
def sendGlobal(clients,msg,log=True):
if log:
print msg.strip()
for c in clients:
try:
c.sendall(msg)
except:
pass
#Description: Send message to specific client
#Parameters: socket, string, boolean
#Return: nil
def sendToClient(client,msg,log=True):
if log:
print msg.strip()
try:
client.sendall(msg)
except:
pass
#Description: Format client info into string
#Parameters: dictionary/list/tuple
#Return: string
def formatClientInfo(clients):
if len(clients) > 0:
string = 'Server:\n==================== Clients ====================\n'
string = string + '%-20s\t\t%s\n' % ('IP','Name')
for c in clients:
info = clients[c]
address = '%s:%s' % (info[0][0],info[0][1])
name = info[1]
if not name:
name = '-'
string = string + ('%-20s\t\t%s\n' % (address,name))
string = string + '=================================================\n'
else:
string = 'Server: No clients connected\n'
return string
#Description: Get name from data
#Parameters: string
#Return: string
def getNameFromData(data):
name = None
try:
name = re.search(r'^\[([^\[\]\:]*)\]\:',data).group(1)
except:
pass
return name
#Description: Format address generated by socket accept
#Parameters: list
#Return: string
def addressToIP(address):
return '%s:%d' % (address[0],address[1])
def getIPFromData(data):
ip = None
try:
ip = re.search(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\:\d{1,5}',data).group(0)
except:
pass
return ip
#Description: Find IP from dictionary
#Parameters: dictionary/list/tuple, string
#Return: socket
def findIP(clients,ip):
client = None
for c in clients:
address = clients[c][0]
if addressToIP(address) == ip:
client = c
break
return client
#Server socket for client connection
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('0.0.0.0',8089))
server.listen(5)
#Socket for admin connection
admin = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
admin.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
admin.bind(('0.0.0.0',8090))
admin.listen(5)
#recv size
size = 255
#Variables
clients = {}
admins = {}
print 'Server started'
run = True
while run:
#All users and admins
connected = list(clients) + list(admins)
#IO objects
input = [server,admin] + connected
#Wait for object to be ready
rlist, wlist, xlist = select.select(input,[],[])
for r in rlist: #Loop through ready objects
if r == server:
#Client connect
conn, address = server.accept()
sendGlobal(connected,('Server: %s has connected\n' % (addressToIP(address))))
clients[conn] = [address,'']
elif r == admin:
#Admin connect
conn, address = admin.accept()
sendGlobal(admins,('Server: [ADMIN] %s has connected\n' % (addressToIP(address))))
admins[conn] = [address,'']
else:
disconnected = False
try:
data = r.recv(size)
if data:
if r in admins: #Check if admin
fchar = data[0]
string = ''
if fchar == '!': #Check if data is a command
command = data[1:] #Exclude '!'
print 'Admin command: ', command
if command == 'shutdown':
#Shutdown server
run = False
break
elif command == 'show':
#Show client info
string = formatClientInfo(clients)
elif command[:len('kick')] == 'kick':
#Kick specific client
ip = getIPFromData(command[len('kick'):].strip())
client = findIP(clients,ip) #Find client with given IP
if client:
#IP exists
client.close()
del clients[client]
sendGlobal(connected,('Server: %s has been kicked\n' % (ip)))
else:
#IP not found
string = 'Server: %s is not connected\n' % (ip)
elif command[:len('broadcast')] == 'broadcast':
#Broadcast message to all
msg = command[len('broadcast'):].strip()
sendGlobal(connected,'Server: [BROADCAST] %s\n' % msg)
else:
#Unknown command
string = 'Server: Unknown command \'%s\'\n' % (data)
if string:
#Message to send back to admin
sendToClient(r,string)
elif fchar == '@':
#Private message
ip = getIPFromData(data.strip('@')) #Get given IP
client = findIP(clients,ip) #Find client with given IP
if client:
#Client exists
name = admins[r][1]
if not name: #Check if admin has name
name = 'Admin'
msg = data[len(ip) + 1:].strip()
sendToClient(client, '[%s -> You]:%s\n' % (name,msg), False)
if name == 'Admin': #Check if name is default
name = 'Admin (%s)' % (addressToIP(admins[r][0]))
else:
name = '%s (%s)' % (name,addressToIP(admins[r][0]))
cname = clients[client][1]
if cname: #Check if client has name
cname = '%s (%s)' % (cname,addressToIP(clients[client][0]))
else:
cname = 'Client (%s)' % (addressToIP(clients[client][0]))
print ('[%s -> %s]: %s' % (name,cname,msg)).strip()
msg = '[You -> %s]:%s\n' % (cname, msg)
else:
#Client does not exists
if ip:
msg = 'Server: %s is not connected\n' % (ip)
else:
msg = 'Server: Invalid IP\n'
sendToClient(r,msg,False)
else:
if not admins[r][1]: #Check if admin already has name
#Store admin name
admins[r][1] = getNameFromData(data)
sendGlobal(connected,data)
else:
if not clients[r][1]: #Check if client already has name
#Store client name
clients[r][1] = getNameFromData(data)
sendGlobal(connected,data)
else:
#No connection
disconnected = True
except:
pass
if disconnected:
#Handle disconnect
if r in admins:
info = admins[r][1]
if not info:
info = addressToIP(admins[r][0])
else:
info = info + (' (%s)' % (addressToIP(admins[r][0])))
sendGlobal(admins,('Server: [ADMIN] %s has disconnected\n' % (info)))
del admins[r]
else:
info = clients[r][1]
if not info:
info = addressToIP(clients[r][0])
sendGlobal(connected,('Server: %s has disconnected\n' % (info)))
del clients[r]
r.close()
#Close all connections
for c in clients:
c.close()
for a in admins:
a.close()
server.close()
admin.close()
print 'Server shutting down'