-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnetchallonged.py
executable file
·474 lines (363 loc) · 11.8 KB
/
netchallonged.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import socket
import random
import time
import threading
import math
import copy
import os
import pdb
import cPickle
#Custom timer :P
import timer
import scores
import challenge
from user import * #Holding scores and lvl and nick
from prompt import *
try:
import SocketServer
except:
import socketserver as SocketServer
#Appending the challenge dir to the module loading path :)
challengeDir = "challenges"
sys.path.append(challengeDir)
DEBUG = 1
#CONFIGZ
#http://docs.python.org/library/socketserver.html
HOST, PORT = '', 1337
#
#
# Code::Phun Network challonge.
#
#
scores = scores.Scores()
def load(chl):
""" Dynamically loading modules. Returns the module loaded"""
if os.path.isdir(chl): return load("%s.%s" % ((chl, chl)))
byteCodeFile = challenge.Challenge.challengeDir + "/" + chl + ".pyc"
if (os.path.exists(byteCodeFile)):
print ( "python bytecode exists. Deleting it " )
try:
os.remove(byteCodeFile)
except:
print ("Could not delete file. please delete manually for a refreshed challenge")
print ("file: %s" % (byteCodeFile,))
return __import__(chl, fromlist=[])
class NerdHandler(SocketServer.StreamRequestHandler):
"""
The class invoked when dealing with a nerd.
Each client connecting will get a separate thread running handling them. (this class)
It is here the communication happens between the server and client. It will ask the server main thread for
the current challenge active for the user. (@see ThreadedNetChallonged.getChallenge() )Then serve it.
"""
def handle(self):
cur_thread = threading.currentThread()
ip = self.client_address[0]
print ("%s Joined. Will he or she manage? The clock is ticking." %(ip))
try:
command = self.ReadSomething().split(' ')
if len(command) > 1:
# Got nick and trailing command...
self.runCommand(command[0], command[1:])
return
# Normal procedure
# Getting the nickname the nerd is using
nickname = command[0]
print ("******************************** Nerd: %s " % (nickname,))
lvl = server.addUser(str(nickname))
# Making a challenge for him /her
challengeHandler = server.getChallenge(str(lvl))
print (challengeHandler.desc())
challenge = challengeHandler.challenge()
self.SaySomething(challenge)
#Ticking down
t = timer.Timer(challengeHandler.timeLimit())
nerdAttempt = str(self.ReadSomething())
#Did he make the challenge?
passed = challengeHandler.passed(nerdAttempt)
if passed and t.timeLeft():
server.levelUpUser(str(nickname))
#Telling him/her:
reply = "Correct!\n" if passed and t.timeLeft() else "Wrong or not solved in time :)!\n"
self.SaySomething(reply)
answer = str(challengeHandler.validAnswer())
#Logging the query
server.log(ip, nickname, challengeHandler.name(), lvl, "Passed" if passed else "Failed")
# http://effbot.org/zone/thread-synchronization.htm
#Grading him
scores.addResult("%s [%s]" %(nickname, self.client_address[0]), passed)
except Exception as e:
print ( "Man quit! %s" %(e,))
finally:
print ( "%s Nerd Gones " % self.client_address[0] )
def SaySomething(self, something):
"""
Method for writing to the socket. Python 3 compability issue handling :)
Str is no longar string or something
"""
self.wfile.write((something).encode('UTF-8')+'\n')
def ReadSomething(self):
"""
Method to read from the socket. The comp... well, it decodes utf-8.
"""
return self.rfile.readline(65536).decode('UTF-8').strip()
def runCommand(self, nick, params):
# Allows users to run commands
if params[0] == 'stats':
self.stats(nick)
elif params[0] == 'list':
self.listChallenges()
elif params[0] == 'desc' and len(params) > 1:
# Not sure about the name of this command
self.challengeDescription(params[1])
def listChallenges(self):
challengeDict = server.listChallenges()
output = ""
for lvl, challenge in challengeDict.iteritems():
output += "%s: %s\n" % (lvl, challenge.name())
output += "\nTry to send\n"
output += "\t<nick> desc <lvl>\n"
output += "to get a description of a challenge\n"
self.SaySomething(output)
def stats(self, nick):
user = server.getUser(nick)
self.SaySomething("Current level: %s\n" % (user.lvl,))
def challengeDescription(self, lvl):
challengeDict = server.listChallenges()
if lvl in challengeDict:
challenge = challengeDict[lvl]
self.SaySomething(
"Name: %(name)s\nDescription: %(desc)s\nExample: %(example)s\n" %
(challenge.name(), challenge.desc(), challenge.example())
)
else:
self.SaySomething("Challenge does not exist :(")
class ThreadedNetChallonged(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
allow_reuse_address = True #SO_REUSEADDR so we can reboot the server immidiently
def log(self, ip, nick, chlName,lvl, status):
""" Logging to the server"""
print (
"%s (%s) : attempting %s (lvl %s) status: %s"
%( ip, nick, chlName, lvl, status)
)
# print ( "The nerd gave an attempt to answer the challonge. \n \
# \t Challenge: \t %s \n \
# . He thought it to be: %s \n \
# It should be: %s\n \
# , and he is %s !!!!" %
# (challenge, nerdAttempt, answer, reply) )
def addChallenge(self, challenge, lvl):
"""
For globally adding a new challenge to the server. lvl overwriting is
done by adding a new challenge with an old lvl
"""
try:
with self.lock:
self.challenges[lvl] = challenge
except Exception as e: print (e, "failed")
def getChallenge(self, lvl):
"""
Returns a Challenge object linked with a current lvl
"""
#todo implement a mechanism for when there are no challenges left.
try:
with self.lock:
return self.challenges[lvl]
except Exception as e: print (e, "failed")
def addUser(self, nickname):
"""
Checks if the user is new, then creates it. If we have the user from
before, this method does nothing. Returns lvl of the user.
"""
try:
with self.userlock:
#a.setdefault(k[, x]) does this... wher a is the self.users dictionary.
if not nickname in self.users:
self.users[nickname] = User(nickname)
return self.users[nickname].lvl
except Exception as e: print (e, "failed")
def levelUpUser(self, nickname):
"""
Leveling up a user. If the last level is reached, it will still update
level, but there will be no challenges to let it further exceed.
getChallonge should take account for handling lvls which does not yet
change
"""
try:
with self.userlock:
#a.setdefault(k[, x]) does this... wher a is the self.users dictionary.
if not nickname in self.users:
self.users[nickname] = User(nickname)
self.users[nickname].lvl+=1
except Exception as e: print (e, "failed")
def getUser(self, nickname):
"""Returns a User object wit nick: nickname"""
try:
with self.userlock:
return self.users[nickname]
except Exception as e: print (e, "failed")
def listUsers(self):
""" Returns a copy of the current userlists """
try:
with self.userlock:
return copy.copy(self.users)
except Exception as e: print (e, "failed")
def listChallenges(self):
""" Returns a copy of the current userlists """
try:
with self.lock:
return copy.copy(self.challenges)
except Exception as e:
print ("List challenges erroer %s " %(e,))
def saveServerState(self):
"""
Function to save the state of the server.
- Users and their levels
- Challenges and their levels
- Scores [not implemented]
"""
if DEBUG: pdb.set_trace()
try:
with self.stateLock:
with self.userlock:
with self.lock:
#Saving user state
userFile = open("user.state", "w")
cPickle.dump(self.users, userFile)
#Saving Challenge state
challengeFile = open("challenge.state", "w")
cPickle.dump(self.challenges, challengeFile)
#Saving score state
scoreFile = open("score.state", "w")
#todo: implement. Move scores under the threaded server object.
#cPickle.dump(self.scores, scoreFile)
except Exception as e:
print ("Failed to save states.. %s " %(e,))
finally:
userFile.close()
scoreFile.close()
challengeFile.close()
def loadServerState(self):
"""
Function to load a earlier state of the server.
- Users and their levels
- Challenges and their levels
- Scores [not implemented]
"""
if DEBUG: pdb.set_trace()
try:
with self.stateLock:
with self.userlock:
with self.lock:
#loading user state
userFile = open("user.state", "r")
self.users = cPickle.load(userFile)
#loading challenge state
challengeFile = open("challenge.state", "r")
self.challenges = cPickle.load(challengeFile)
#loading score state
#todo: implement
scoreFile = open("score.state", "r")
except Exception as e:
print ("Failed to save states.. %s " %(e,))
finally:
userFile.close()
scoreFile.close()
challengeFile.close()
#State objects :)
challenges = {}
users = {}
#To make the operations on add / get users / challenges atomic.
lock = threading.RLock() #challengelock
userlock = threading.RLock()
stateLock = threading.RLock()
# Below are the control and running of the server.
# It is an interactive prompt that controls it.
if __name__ == "__main__":
server = ThreadedNetChallonged((HOST, PORT), NerdHandler)
def shutUp():
print ("Shuting down.. eh, up")
server.shutdown()
exit()
print ( "The Challonge is alive" )
serveraddr, serverport = server.server_address
try:
serverThread = threading.Thread(target=server.serve_forever)
serverThread.setDaemon(True)
serverThread.start()
while 1:
cmd = prompt("Code::Phun->NetChallongeD>> ")
if "quit" in cmd:
shutUp()
if "help" in cmd:
args = cmd.split(" ")
#Lists all cmds
if len(args) == 1:
for k in ["load", "scores", "quit", "help", "users", "load state", "save state", "challenges"]:
print (k)
print ("Usage help [<command>] \n if no command given, it lists all commands")
continue
if "load" in args[1]:
print("Usage: load <challenge-name> <lvl>")
elif "load" in cmd:
#
# LOAD SERVER STATE
#
if "state" in cmd:
"""
Overwriting the load challenge command to act for load state
from state files
"""
print ("Loading server states")
try:
server.loadServerState()
except Exception as e:
print (" Failed to load states: %s " %(e,))
continue #skipping over the next steps
#
# LOAD Challenge
#
""" Loads a new challenge module """
try:
(name, lvl) = cmd.split(" ")[1:3]
print ("Loading %s at lvl %s" %(name, lvl))
mod = load(name)
exec ("challengeObj = mod.%s()" %(name, )) #dirty hack?
#Testing the loaded module
if not challenge.Challenge.test(challengeObj):
print ("Not loaded")
continue
#loading it into the server
server.addChallenge(challengeObj, lvl)
print ("loaded")
except Exception as e:
print ("Exception %s" %(e))
print("Usage: load <challenge-name> <lvl>")
elif "scores" in cmd:
print ( scores.getScores() )
#
# Save Server States
#
elif "save" in cmd:
if "state" in cmd:
print ("Saving states")
try:
server.saveServerState()
except Exception as e:
print( "Failed to save server state %s " % (e,))
#Skipping the next sub comands
continue
elif "users" in cmd:
print("%s")
for k,v in server.listUsers().items():
print ("User: %s has gone to lvl: %s" % (k, v.lvl))
elif "challenges" in cmd:
print (" Listing challenges ")
for k,v in server.listChallenges().items():
print ("Lvl: %s \t Challenge: %s \n\tExample: %s \n\n" % (k, v.name(), v.example()))
except KeyboardInterrupt:
print ( "Shuting down, erh up... ")
finally:
server.shutdown()