Refactor handling of packet headers

Refactored ackDataHasAVaildHeader:
 -shared.Header is used as necessary
 -avoided slicing wherever possible
 -remove trailing null characters when comparing command strings
 -don't calculate the checksum of a large payload
This commit is contained in:
bmng-dev 2014-05-22 13:08:30 +00:00
parent 947f7655ab
commit ccfbe8da47

View File

@ -1149,25 +1149,28 @@ class objectProcessor(threading.Thread):
shared.workerQueue.put(('sendmessage', '')) shared.workerQueue.put(('sendmessage', ''))
def ackDataHasAVaildHeader(self, ackData): def ackDataHasAVaildHeader(self, ackData):
if len(ackData) < 24: if len(ackData) < shared.Header.size:
logger.info('The length of ackData is unreasonably short. Not sending ackData.') logger.info('The length of ackData is unreasonably short. Not sending ackData.')
return False return False
if ackData[0:4] != '\xe9\xbe\xb4\xd9':
magic,command,payload_length,checksum = shared.Header.unpack(ackData[:shared.Header.size])
if magic != 0xE9BEB4D9:
logger.info('Ackdata magic bytes were wrong. Not sending ackData.') logger.info('Ackdata magic bytes were wrong. Not sending ackData.')
return False return False
ackDataPayloadLength, = unpack('>L', ackData[16:20]) payload = ackData[shared.Header.size:]
if len(ackData) - 24 != ackDataPayloadLength: if len(payload) != payload_length:
logger.info('ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.') logger.info('ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.')
return False return False
if ackData[20:24] != hashlib.sha512(ackData[24:]).digest()[0:4]: # test the checksum in the message. if payload_length > 180000000: # If the size of the message is greater than 180MB, ignore it.
return False
if checksum != hashlib.sha512(payload).digest()[0:4]: # test the checksum in the message.
logger.info('ackdata checksum wrong. Not sending ackdata.') logger.info('ackdata checksum wrong. Not sending ackdata.')
return False return False
if ackDataPayloadLength > 180000000: # If the size of the message is greater than 180MB, ignore it. command = command.rstrip('\x00')
return False if (command != 'getpubkey' and
if (ackData[4:16] != 'getpubkey\x00\x00\x00' and command != 'pubkey' and
ackData[4:16] != 'pubkey\x00\x00\x00\x00\x00\x00' and command != 'msg' and
ackData[4:16] != 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' and command != 'broadcast'):
ackData[4:16] != 'broadcast\x00\x00\x00'):
return False return False
return True return True