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', ''))
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.')
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.')
return False
ackDataPayloadLength, = unpack('>L', ackData[16:20])
if len(ackData) - 24 != ackDataPayloadLength:
payload = ackData[shared.Header.size:]
if len(payload) != payload_length:
logger.info('ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.')
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.')
return False
if ackDataPayloadLength > 180000000: # If the size of the message is greater than 180MB, ignore it.
return False
if (ackData[4:16] != 'getpubkey\x00\x00\x00' and
ackData[4:16] != 'pubkey\x00\x00\x00\x00\x00\x00' and
ackData[4:16] != 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' and
ackData[4:16] != 'broadcast\x00\x00\x00'):
command = command.rstrip('\x00')
if (command != 'getpubkey' and
command != 'pubkey' and
command != 'msg' and
command != 'broadcast'):
return False
return True
@ -1210,4 +1213,4 @@ class objectProcessor(threading.Thread):
# Throw away any extra lines (headers) after the subject.
if subject:
subject = subject.splitlines()[0]
return subject, body
return subject, body