Advertisement
MeIiodas

Untitled

May 12th, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.35 KB | None | 0 0
  1. import datetime
  2. import gzip
  3. import sys
  4. import traceback
  5.  
  6. import tornado.gen
  7. import tornado.web
  8. from raven.contrib.tornado import SentryMixin
  9.  
  10. from common.log import logUtils as log
  11. from common.web import requestsManager
  12. from constants import exceptions
  13. from constants import packetIDs
  14. from constants import serverPackets
  15. from events import cantSpectateEvent
  16. from events import changeActionEvent
  17. from events import changeMatchModsEvent
  18. from events import changeMatchPasswordEvent
  19. from events import changeMatchSettingsEvent
  20. from events import changeSlotEvent
  21. from events import channelJoinEvent
  22. from events import channelPartEvent
  23. from events import createMatchEvent
  24. from events import friendAddEvent
  25. from events import friendRemoveEvent
  26. from events import joinLobbyEvent
  27. from events import joinMatchEvent
  28. from events import loginEvent
  29. from events import logoutEvent
  30. from events import matchChangeTeamEvent
  31. from events import matchCompleteEvent
  32. from events import matchFailedEvent
  33. from events import matchFramesEvent
  34. from events import matchHasBeatmapEvent
  35. from events import matchInviteEvent
  36. from events import matchLockEvent
  37. from events import matchNoBeatmapEvent
  38. from events import matchPlayerLoadEvent
  39. from events import matchReadyEvent
  40. from events import matchSkipEvent
  41. from events import matchStartEvent
  42. from events import matchTransferHostEvent
  43. from events import partLobbyEvent
  44. from events import partMatchEvent
  45. from events import requestStatusUpdateEvent
  46. from events import sendPrivateMessageEvent
  47. from events import sendPublicMessageEvent
  48. from events import setAwayMessageEvent
  49. from events import spectateFramesEvent
  50. from events import startSpectatingEvent
  51. from events import stopSpectatingEvent
  52. from events import userPanelRequestEvent
  53. from events import userStatsRequestEvent
  54. from events import tournamentMatchInfoRequestEvent
  55. from events import tournamentJoinMatchChannelEvent
  56. from events import tournamentLeaveMatchChannelEvent
  57. from helpers import packetHelper
  58. from objects import glob
  59. from common.sentry import sentry
  60.  
  61.  
  62. class handler(requestsManager.asyncRequestHandler):
  63. @tornado.web.asynchronous
  64. @tornado.gen.engine
  65. @sentry.captureTornado
  66. def asyncPost(self):
  67. # Track time if needed
  68. if glob.outputRequestTime:
  69. # Start time
  70. st = datetime.datetime.now()
  71.  
  72. # Client's token string and request data
  73. requestTokenString = self.request.headers.get("osu-token")
  74. requestData = self.request.body
  75.  
  76. # Server's token string and request data
  77. responseTokenString = "ayy"
  78. responseData = bytes()
  79.  
  80. if requestTokenString is None:
  81. # No token, first request. Handle login.
  82. responseTokenString, responseData = loginEvent.handle(self)
  83. else:
  84. userToken = None # default value
  85. try:
  86. # This is not the first packet, send response based on client's request
  87. # Packet start position, used to read stacked packets
  88. pos = 0
  89.  
  90. # Make sure the token exists
  91. if requestTokenString not in glob.tokens.tokens:
  92. raise exceptions.tokenNotFoundException()
  93.  
  94. # Token exists, get its object and lock it
  95. userToken = glob.tokens.tokens[requestTokenString]
  96. userToken.processingLock.acquire()
  97.  
  98. # Keep reading packets until everything has been read
  99. while pos < len(requestData):
  100. # Get packet from stack starting from new packet
  101. leftData = requestData[pos:]
  102.  
  103. # Get packet ID, data length and data
  104. packetID = packetHelper.readPacketID(leftData)
  105. dataLength = packetHelper.readPacketLength(leftData)
  106. packetData = requestData[pos:(pos+dataLength+7)]
  107.  
  108. # Console output if needed
  109. if glob.outputPackets and packetID != 4:
  110. log.debug("Incoming packet ({})({}):\n\nPacket code: {}\nPacket length: {}\nSingle packet data: {}\n".format(requestTokenString, userToken.username, str(packetID), str(dataLength), str(packetData)))
  111.  
  112. # Event handler
  113. def handleEvent(ev):
  114. def wrapper():
  115. ev.handle(userToken, packetData)
  116. return wrapper
  117.  
  118. eventHandler = {
  119. packetIDs.client_changeAction: handleEvent(changeActionEvent),
  120. packetIDs.client_logout: handleEvent(logoutEvent),
  121. packetIDs.client_friendAdd: handleEvent(friendAddEvent),
  122. packetIDs.client_friendRemove: handleEvent(friendRemoveEvent),
  123. packetIDs.client_userStatsRequest: handleEvent(userStatsRequestEvent),
  124. packetIDs.client_requestStatusUpdate: handleEvent(requestStatusUpdateEvent),
  125. packetIDs.client_userPanelRequest: handleEvent(userPanelRequestEvent),
  126.  
  127. packetIDs.client_channelJoin: handleEvent(channelJoinEvent),
  128. packetIDs.client_channelPart: handleEvent(channelPartEvent),
  129. packetIDs.client_sendPublicMessage: handleEvent(sendPublicMessageEvent),
  130. packetIDs.client_sendPrivateMessage: handleEvent(sendPrivateMessageEvent),
  131. packetIDs.client_setAwayMessage: handleEvent(setAwayMessageEvent),
  132.  
  133. packetIDs.client_startSpectating: handleEvent(startSpectatingEvent),
  134. packetIDs.client_stopSpectating: handleEvent(stopSpectatingEvent),
  135. packetIDs.client_cantSpectate: handleEvent(cantSpectateEvent),
  136. packetIDs.client_spectateFrames: handleEvent(spectateFramesEvent),
  137.  
  138. packetIDs.client_joinLobby: handleEvent(joinLobbyEvent),
  139. packetIDs.client_partLobby: handleEvent(partLobbyEvent),
  140. packetIDs.client_createMatch: handleEvent(createMatchEvent),
  141. packetIDs.client_joinMatch: handleEvent(joinMatchEvent),
  142. packetIDs.client_partMatch: handleEvent(partMatchEvent),
  143. packetIDs.client_matchChangeSlot: handleEvent(changeSlotEvent),
  144. packetIDs.client_matchChangeSettings: handleEvent(changeMatchSettingsEvent),
  145. packetIDs.client_matchChangePassword: handleEvent(changeMatchPasswordEvent),
  146. packetIDs.client_matchChangeMods: handleEvent(changeMatchModsEvent),
  147. packetIDs.client_matchReady: handleEvent(matchReadyEvent),
  148. packetIDs.client_matchNotReady: handleEvent(matchReadyEvent),
  149. packetIDs.client_matchLock: handleEvent(matchLockEvent),
  150. packetIDs.client_matchStart: handleEvent(matchStartEvent),
  151. packetIDs.client_matchLoadComplete: handleEvent(matchPlayerLoadEvent),
  152. packetIDs.client_matchSkipRequest: handleEvent(matchSkipEvent),
  153. packetIDs.client_matchScoreUpdate: handleEvent(matchFramesEvent),
  154. packetIDs.client_matchComplete: handleEvent(matchCompleteEvent),
  155. packetIDs.client_matchNoBeatmap: handleEvent(matchNoBeatmapEvent),
  156. packetIDs.client_matchHasBeatmap: handleEvent(matchHasBeatmapEvent),
  157. packetIDs.client_matchTransferHost: handleEvent(matchTransferHostEvent),
  158. packetIDs.client_matchFailed: handleEvent(matchFailedEvent),
  159. packetIDs.client_matchChangeTeam: handleEvent(matchChangeTeamEvent),
  160. packetIDs.client_invite: handleEvent(matchInviteEvent),
  161.  
  162. packetIDs.client_tournamentMatchInfoRequest: handleEvent(tournamentMatchInfoRequestEvent),
  163. packetIDs.client_tournamentJoinMatchChannel: handleEvent(tournamentJoinMatchChannelEvent),
  164. packetIDs.client_tournamentLeaveMatchChannel: handleEvent(tournamentLeaveMatchChannelEvent),
  165. }
  166.  
  167. # Packets processed if in restricted mode.
  168. # All other packets will be ignored if the user is in restricted mode
  169. packetsRestricted = [
  170. packetIDs.client_logout,
  171. packetIDs.client_userStatsRequest,
  172. packetIDs.client_requestStatusUpdate,
  173. packetIDs.client_userPanelRequest,
  174. packetIDs.client_changeAction,
  175. packetIDs.client_channelJoin,
  176. packetIDs.client_channelPart,
  177. ]
  178.  
  179. # Process/ignore packet
  180. if packetID != 4:
  181. if packetID in eventHandler:
  182. if not userToken.restricted or (userToken.restricted and packetID in packetsRestricted):
  183. eventHandler[packetID]()
  184. else:
  185. log.warning("Ignored packet id from {} ({}) (user is restricted)".format(requestTokenString, packetID))
  186. else:
  187. log.warning("Unknown packet id from {} ({})".format(requestTokenString, packetID))
  188.  
  189. # Update pos so we can read the next stacked packet
  190. # +7 because we add packet ID bytes, unused byte and data length bytes
  191. pos += dataLength+7
  192.  
  193. # Token queue built, send it
  194. responseTokenString = userToken.token
  195. responseData = userToken.queue
  196. userToken.resetQueue()
  197. except exceptions.tokenNotFoundException:
  198. # Token not found. Disconnect that user
  199. responseData = serverPackets.loginError()
  200. responseData += serverPackets.notification("Whoops! Something went wrong, please login again.")
  201. log.warning("Received packet from unknown token ({}).".format(requestTokenString))
  202. log.info("{} has been disconnected (invalid token)".format(requestTokenString))
  203. finally:
  204. # Unlock token
  205. if userToken is not None:
  206. # Update ping time for timeout
  207. userToken.updatePingTime()
  208. # Release processing lock
  209. userToken.processingLock.release()
  210. # Delete token if kicked
  211. if userToken.kicked:
  212. glob.tokens.deleteToken(userToken)
  213.  
  214. if glob.outputRequestTime:
  215. # End time
  216. et = datetime.datetime.now()
  217.  
  218. # Total time:
  219. tt = float((et.microsecond-st.microsecond)/1000)
  220. log.debug("Request time: {}ms".format(tt))
  221.  
  222. # Send server's response to client
  223. # We don't use token object because we might not have a token (failed login)
  224. if glob.gzip:
  225. # First, write the gzipped response
  226. self.write(gzip.compress(responseData, int(glob.conf.config["server"]["gziplevel"])))
  227.  
  228. # Then, add gzip headers
  229. self.add_header("Vary", "Accept-Encoding")
  230. self.add_header("Content-Encoding", "gzip")
  231. else:
  232. # First, write the response
  233. self.write(responseData)
  234.  
  235. # Add all the headers AFTER the response has been written
  236. self.set_status(200)
  237. self.add_header("cho-token", responseTokenString)
  238. self.add_header("cho-protocol", "19")
  239. self.add_header("Connection", "keep-alive")
  240. self.add_header("Keep-Alive", "timeout=5, max=100")
  241. self.add_header("Content-Type", "text/html; charset=UTF-8")
  242.  
  243. @tornado.web.asynchronous
  244. @tornado.gen.engine
  245. def asyncGet(self):
  246. html = "<html><head><title>Anna's really cute tho</title></head><body><pre>"
  247. html += " _ __<br>"
  248. html += " (_) / /<br>"
  249. html += " ______ __ ____ ____ / /____<br>"
  250. html += " / ___/ / _ \\/ _ \\/ / _ \\<br>"
  251. html += " / / / / /_) / /_) / / ____/<br>"
  252. html += "/__/ /__/ .___/ .___/__/ \\_____/<br>"
  253. html += " / / / /<br>"
  254. html += " /__/ /__/<br>"
  255. html += "<b>PYTHON > ALL VERSION</b><br><br>"
  256. html += "<marquee style='white-space:pre;'><br>"
  257. html += " .. o .<br>"
  258. html += " o.o o . o<br>"
  259. html += " oo...<br>"
  260. html += " __[]____<br>"
  261. html += " ______\___/o_o_\ <span style=\"font-family: 'Comic Sans MS'; font-size: 8pt;\">Sate Sate Sate :crab:</span><br>"
  262. html += " \\\"\"\"\"\"\"\"\"\"\"\"\"\"\"/<br>"
  263. html += " \\ . .. .. . /<br>"
  264. html += "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>"
  265. html += "</marquee><br><strike>reverse engineering a protocol impossible to reverse engineer since always</strike><br>we are actually reverse engineering bancho successfully. for the third time.<br><br><i>&copy; Ripple team, Ainu and Homura 2016-2019</i></pre></body></html>"
  266. html += "<pre>Meliodas's Auto Installer v1<br>"
  267. self.write(html)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement