utils.py.bak 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. """DWC Network Server Emulator
  2. Copyright (C) 2014 polaris-
  3. Copyright (C) 2014 msoucy
  4. Copyright (C) 2016 Sepalani
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU Affero General Public License as
  7. published by the Free Software Foundation, either version 3 of the
  8. License, or (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU Affero General Public License for more details.
  13. You should have received a copy of the GNU Affero General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. """
  16. import base64
  17. import logging
  18. import logging.handlers
  19. import random
  20. import string
  21. import struct
  22. import urlparse
  23. import ctypes
  24. import os
  25. def generate_random_str_from_set(ln, chs):
  26. """Generate a random string of size <ln> based on charset <chs>."""
  27. return ''.join(random.choice(chs) for _ in range(ln))
  28. def generate_random_str(ln, chs=""):
  29. """Generate a random string of size <ln>."""
  30. return generate_random_str_from_set(
  31. ln,
  32. chs or (string.ascii_letters + string.digits)
  33. )
  34. def generate_random_number_str(ln):
  35. """Generate a random number string of size <ln>."""
  36. return generate_random_str_from_set(ln, string.digits)
  37. def generate_random_hex_str(ln):
  38. """Generate a random hexadecimal number string of size <ln>."""
  39. return generate_random_str_from_set(ln, string.hexdigits.lower())
  40. def calculate_crc8(inp):
  41. """
  42. Code: Tetris DS @ 020573F4
  43. """
  44. crc_table = [
  45. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15, 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  46. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  47. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5, 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  48. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85, 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  49. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2, 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  50. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2, 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  51. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32, 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  52. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42, 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  53. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C, 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  54. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC, 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  55. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C, 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  56. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C, 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  57. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B, 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  58. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B, 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  59. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB, 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  60. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB, 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  61. ]
  62. crc = 0
  63. for b in inp:
  64. crc = crc_table[(b ^ crc) & 0xff]
  65. return crc
  66. def base32_encode(num, reverse=True):
  67. """Encode a number in base 32.
  68. Result string is reversed by default.
  69. """
  70. alpha = "0123456789abcdefghijklmnopqrstuv"
  71. encoded = ""
  72. while num > 0:
  73. encoded += alpha[num & 0x1f]
  74. num >>= 5
  75. encoded.ljust(9, '0')
  76. if reverse:
  77. encoded = encoded[::-1]
  78. return encoded
  79. def base32_decode(s, reverse=False):
  80. """Decode a number in base 32.
  81. Input string is not reversed by default.
  82. """
  83. alpha = "0123456789abcdefghijklmnopqrstuv"
  84. if reverse:
  85. s = s[::-1]
  86. return reduce(lambda orig, b: ((orig << 5) | alpha.index(b)), s, 0)
  87. # Number routines
  88. def get_num_from_bytes(data, idx, fmt, bigEndian=False):
  89. """Get number from bytes.
  90. Endianness by default is little.
  91. """
  92. return struct.unpack_from("<>"[bigEndian] + fmt, buffer(bytearray(data)), idx)[0]
  93. # Instead of passing slices, pass the buffer and index so we can calculate
  94. # the length automatically.
  95. def get_short_signed(data, idx, be=False):
  96. """Get short from bytes.
  97. Endianness by default is little.
  98. """
  99. return get_num_from_bytes(data, idx, 'h', be)
  100. def get_short(data, idx, be=False):
  101. """Get unsigned short from bytes.
  102. Endianness by default is little.
  103. """
  104. return get_num_from_bytes(data, idx, 'H', be)
  105. def get_int_signed(data, idx, be=False):
  106. """Get int from bytes.
  107. Endianness by default is little.
  108. """
  109. return get_num_from_bytes(data, idx, 'i', be)
  110. def get_int(data, idx, be=False):
  111. """Get unsigned int from bytes.
  112. Endianness by default is little.
  113. """
  114. return get_num_from_bytes(data, idx, 'I', be)
  115. def get_ip(data, idx, be=False):
  116. """Get IP from bytes.
  117. Endianness by default is little.
  118. """
  119. return ctypes.c_int32(get_int(data, idx, be)).value
  120. def get_ip_str(data, idx):
  121. """Get IP string from bytes."""
  122. return '.'.join("%d" % x for x in bytearray(data[idx:idx+4]))
  123. def get_ip_from_str(ip_str, be=False):
  124. """Get IP from string.
  125. Endianness by default is little.
  126. """
  127. return get_ip(bytearray([int(x) for x in ip_str.split('.')]), 0, be)
  128. def get_local_addr(data, idx):
  129. """Get local address."""
  130. localip = get_ip_str(data, idx)
  131. localip_int_le = get_ip(data, idx)
  132. localip_int_be = get_ip(data, idx, True)
  133. localport = get_short(data, idx + 4, True)
  134. return (localip, localport, localip_int_le, localip_int_be)
  135. def get_string(data, idx):
  136. """Get string from bytes."""
  137. data = data[idx:]
  138. end = data.index('\x00')
  139. return str(''.join(data[:end]))
  140. def get_bytes_from_num(num, fmt, bigEndian=False):
  141. """Get bytes from number.
  142. Endianness by default is little.
  143. """
  144. return struct.pack("<>"[bigEndian] + fmt, num)
  145. def get_bytes_from_short_signed(num, be=False):
  146. """Get bytes from short.
  147. Endianness by default is little.
  148. """
  149. return get_bytes_from_num(num, 'h', be)
  150. def get_bytes_from_short(num, be=False):
  151. """Get bytes from unsigned short.
  152. Endianness by default is little.
  153. """
  154. return get_bytes_from_num(num, 'H', be)
  155. def get_bytes_from_int_signed(num, be=False):
  156. """Get bytes from int.
  157. Endianness by default is little.
  158. """
  159. return get_bytes_from_num(num, 'i', be)
  160. def get_bytes_from_int(num, be=False):
  161. """Get bytes from unsigned int.
  162. Endianness by default is little.
  163. """
  164. return get_bytes_from_num(num, 'I', be)
  165. def get_bytes_from_ip_str(ip_str):
  166. """Get bytes from IP string."""
  167. return bytearray([int(x) for x in ip_str.split('.')])
  168. def create_logger(loggername, filename, level, log_to_console, log_to_file):
  169. """Server logging."""
  170. log_folder = "logs"
  171. # Create log folder if it doesn't exist
  172. if not os.path.exists(log_folder):
  173. os.makedirs(log_folder)
  174. # Build full path to log file
  175. filename = os.path.join(log_folder, filename)
  176. logging.addLevelName(-1, "TRACE")
  177. fmt = "[%(asctime)s | " + loggername + "] %(message)s"
  178. date_format = "%Y-%m-%d %H:%M:%S"
  179. # logging.basicConfig(format=format, datefmt=date_format)
  180. logger = logging.getLogger(loggername)
  181. logger.setLevel(level)
  182. # Only needed when logging.basicConfig isn't set.
  183. if log_to_console:
  184. console_logger = logging.StreamHandler()
  185. console_logger.setFormatter(
  186. logging.Formatter(fmt, datefmt=date_format)
  187. )
  188. logger.addHandler(console_logger)
  189. if log_to_file and filename:
  190. # Use a rotating log set to rotate every night at midnight with a
  191. # max of 10 backups
  192. file_logger = logging.handlers.TimedRotatingFileHandler(
  193. filename,
  194. when='midnight',
  195. backupCount=10) # logging.FileHandler(filename)
  196. file_logger.setFormatter(
  197. logging.Formatter(fmt, datefmt=date_format)
  198. )
  199. logger.addHandler(file_logger)
  200. return logger
  201. def print_hex(data, cols=16, sep=' ', pretty=True):
  202. """Print data in hexadecimal.
  203. Customizable separator and columns number.
  204. Can be pretty printed but takes more time.
  205. """
  206. if pretty:
  207. print(pretty_print_hex(data, cols, sep))
  208. else:
  209. print(sep.join("%02x" % b for b in bytearray(data)))
  210. def pretty_print_hex(orig_data, cols=16, sep=' '):
  211. """Hexadecimal pretty print.
  212. Takes ~1s per characters.
  213. Customizable separator and columns number.
  214. """
  215. data = bytearray(orig_data)
  216. end = len(data)
  217. line = "\n%08x | %-*s | %s"
  218. size = cols * 3 - 1
  219. i = 0
  220. output = ""
  221. while i < end:
  222. if i + cols < end:
  223. j = i + cols
  224. else:
  225. j = end
  226. output += line % (
  227. i,
  228. size,
  229. sep.join("%02x" % c for c in data[i:j]),
  230. "".join(chr(c) if 0x20 <= c < 0x7F else
  231. '.'
  232. for c in data[i:j])
  233. )
  234. i += cols
  235. return output
  236. # def pretty_print_hex(orig_data, cols=16):
  237. # """Takes ~1.5s per characters"""
  238. #
  239. # data = bytearray(orig_data)
  240. # output = "\n"
  241. #
  242. # for i in range(len(data) / cols + 1):
  243. # output += "%08x | " % (i * 16)
  244. #
  245. # c = 0
  246. # for x in range(cols):
  247. # if (i * cols + x + 1) > len(data):
  248. # break
  249. #
  250. # output += "%02x " % data[i * cols + x]
  251. # c += 1
  252. #
  253. # c = cols - c
  254. # output += " " * (c * 3 + 1)
  255. # for x in range(cols):
  256. # if (i * cols + x + 1) > len(data):
  257. # break
  258. #
  259. # if not chr(data[i * cols + x]) in string.printable:
  260. # output += "."
  261. # else:
  262. # output += "%c" % data[i * cols + x]
  263. # output += "\n"
  264. #
  265. # return output
  266. def qs_to_dict(s):
  267. """Convert query string to dict."""
  268. ret = urlparse.parse_qs(s, True)
  269. for k, v in ret.items():
  270. try:
  271. # I'm not sure about the replacement for '-', but it'll at
  272. # least let it be decoded.
  273. # For the most part it's not important since it's mostly
  274. # used for the devname/ingamesn fields.
  275. ret[k] = base64.b64decode(urlparse.unquote(v[0])
  276. .replace("*", "=")
  277. .replace("?", "/")
  278. .replace(">", "+")
  279. .replace("-", "/"))
  280. except TypeError:
  281. """
  282. print("Could not decode following string: ret[%s] = %s"
  283. % (k, v[0]))
  284. print("url: %s" % s)
  285. """
  286. # If you don't assign it like this it'll be a list, which
  287. # breaks other code.
  288. ret[k] = v[0]
  289. return ret
  290. def dict_to_qs(d):
  291. """Convert dict to query string.
  292. nas(wii).nintendowifi.net has a URL query-like format but does not
  293. use encoding for special characters.
  294. """
  295. # Dictionary comprehension is used to not modify the original
  296. ret = {k: base64.b64encode(v).replace("=", "*") for k, v in d.items()}
  297. return "&".join("{!s}={!s}".format(k, v) for k, v in ret.items()) + "\r\n"