kalparse.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #!/usr/bin/python3
  2. import argparse
  3. parser = argparse.ArgumentParser(description='KALYPSO 2.5/2.6 Data Parser ver. 0.1')
  4. parser.add_argument('-inv', action="store_true", help='Check for Tail filling in reverse byte order')
  5. parser.add_argument('-o', metavar="outfile", type=argparse.FileType('wb'), nargs='?', help='File to write decoded data to. If not set, will print human readable Hex Values to stdout instead.')
  6. parser.add_argument('infile', type=argparse.FileType('rb'), nargs=1, help='File to read from')
  7. args = parser.parse_args()
  8. writeToFile = True if args.o else False
  9. def print32Hex(b, offset, blocks=4, withLineNumber=True):
  10. if withLineNumber:
  11. print('0x{0:08x}'.format(offset), end=": ")
  12. for i in range(blocks):
  13. print('0x{0:02x}'.format(b[(i*4)+0]), end ="")
  14. print('{0:02x}'.format(b[(i*4)+1]), end ="")
  15. print('{0:02x}'.format(b[(i*4)+2]), end ="")
  16. print('{0:02x}'.format(b[(i*4)+3]), end ="")
  17. print(" ", end ="")
  18. print("") #newline after block
  19. def checkTail(b, inverse=False, words=4):
  20. a = [0xfe, 0xdc, 0xba, 0x98] #Filling pattern
  21. for w in range(words):
  22. u = (w+1) * 4 #upper window
  23. l = u - 4 #lower window
  24. for i,e in enumerate(b[l:u]):
  25. comp = a[3-i] if inverse else a[i]
  26. if e is not comp:
  27. return False
  28. return True
  29. def flipBytes(bytes):
  30. ret = []
  31. #Take every second element from bytes, starting with 0 (bytes[0::2])
  32. #Take every second element from bytes, starting with 1 (bytes[1::2])
  33. #Create a list of pairs from the previous two (zip)
  34. #Append first (f) and second (s) element to 'ret' (append)
  35. for f,s in zip(bytes[0::2], bytes[1::2]):
  36. ret.append(s)
  37. ret.append(f)
  38. return ret
  39. #---------- MAIN LOOP -------------#
  40. with args.infile[0] as ifile:
  41. offset = 0
  42. #read header
  43. byte_s = ifile.read(32)
  44. if not byte_s:
  45. print("Failed to read header from file. Not enough data to read!")
  46. quit()
  47. #print header
  48. if writeToFile:
  49. args.o.write(bytes(byte_s))
  50. else:
  51. print32Hex(byte_s[0:16], 0)
  52. print32Hex(byte_s[16:32], 16)
  53. #read rest of the file
  54. offset = 32
  55. keep_flipping = True
  56. while 1:
  57. byte_s = ifile.read(16) #read 4 words
  58. if not byte_s:
  59. #quit once no more data is available
  60. break
  61. #Have we found the Tail filling?
  62. if checkTail(byte_s, args.inv):
  63. keep_flipping = False
  64. #dO ThE fLiP!
  65. byte_s = flipBytes(byte_s) if keep_flipping else byte_s
  66. if writeToFile:
  67. args.o.write(bytes(byte_s))
  68. else:
  69. print32Hex(byte_s, offset)
  70. offset = offset + 16 #continue