Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from struct import pack
- class TribeDecodeError(Exception):
- def __init__(self, value):
- self.value = value
- def __str__(self):
- return repr(self.value)
- # Seeks a 'tribe fw bit array for the next packet start.
- # Takes an iterator
- def packetseek(it):
- numbits = 0;
- while(it.next()):
- numbits += 1; # Loop through all the junk bits
- # print "%d bits skipped." % (numbits)
- # Fetch next byte from bitarray.
- # Returns an int.
- def fetchbyte(it):
- tempstr="";
- for x in range(0,8):
- #print it.next()
- tempstr = str(it.next())+tempstr;
- return int(tempstr, 2)
- # fetch a number of bytes to extract a full packet
- # The second optional argument is to ignore the post-signature check, needed for the initial greeting packet
- def fetchpacket(it, ignorepostsig=False, packetindex=0):
- tempbyte=0;tempstr = "";temparray=[];
- tempbyte=fetchbyte(it);
- # Confirm pre-signature
- if(tempbyte != 0xA9):
- raise TribeDecodeError("Invalid packet pre-signature! Should be 0xA9. Found: " + hex(tempbyte));
- # Confirm post-signature
- for x in range(0,256):
- tempbyte = fetchbyte(it);
- tempstr+=pack("B", tempbyte);
- temparray.append(tempbyte);
- if not ignorepostsig:
- # Confirm post-signature
- for x in range(0,3):
- tempbyte = fetchbyte(it);
- if(tempbyte != 0x55 and packetindex != 0x80):
- raise TribeDecodeError("Invalid packet post-signature! Should be 3*0x55. Found: " + hex(tempbyte));
- # Print the mysterious checksum byte
- tempbyte = fetchbyte(it);
- print "Packet %s has checksum (?) %s" % (hex(packetindex), hex(tempbyte));
- # Sanity check
- tempbyte = fetchbyte(it);
- if(tempbyte != 0xff):
- raise TribeDecodeError("Sanity check. Packet should be followed by 0xff but isn't. Found: " + hex(tempbyte));
- return tempstr;
- # main function
- def tribefwdecode(infile, outfile, invert):
- f = open(infile, "r");
- bitarray = f.readlines(); # Fetch the array of bits
- # Validate the bit array and convert it to bool
- for i,b in enumerate(bitarray):
- b = b.strip();
- if (b != "0" and b != "1"):
- raise TribeDecodeError("Only 0 and 1 in the bit file, please! Found: " + b);
- else:
- if invert:
- bitarray[i] = 1-int(b);
- else:
- bitarray[i] = int(b);
- bititer = iter(bitarray);
- # Seek for the greeting packet.
- packetseek(bititer);
- fetchpacket(bititer, True)
- f = open(outfile, "w")
- packetidx = 0;
- while True:
- try:
- packetseek(bititer); # Try to get a packet
- except StopIteration:
- break; # Detect end of file.
- # Parse packet and write it fo the file.
- packet = fetchpacket(bititer,False,packetidx)
- f.write(packet)
- packetidx += 1;
- # If we're done, close the file.
- f.close();
- print "File %s successfully parsed and written to %s" % (infile, outfile)
- tribefwdecode("bits", "firmware2.bin", True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement