lib/packet/packet_utils: Add a function to calculate fletcher checksum

I'm resending the patches which appease pep8

fletcher checksum function for OSPF LSA checksum.
refer to RFC1008.

Signed-off-by: Wataru ISHIDA <ishida.wataru@lab.ntt.co.jp>
Signed-off-by: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
This commit is contained in:
ishida wataru 2013-12-13 15:18:41 +09:00 committed by FUJITA Tomonori
parent 31c0941fb8
commit 23b1226cd2

View File

@ -97,3 +97,40 @@ def checksum_ip(ipvx, length, payload):
buf = header + payload
return checksum(buf)
_MODX = 4102
def fletcher_checksum(data, offset):
"""
Fletcher Checksum -- Refer to RFC1008
calling with offset == _FLETCHER_CHECKSUM_VALIDATE will validate the
checksum without modifying the buffer; a valid checksum returns 0.
"""
c0 = 0
c1 = 0
pos = 0
length = len(data)
data = bytearray(data)
data[offset:offset+2] = [0]*2
while pos < length:
tlen = min(length - pos, _MODX)
for d in data[pos:pos+tlen]:
c0 += d
c1 += c0
c0 %= 255
c1 %= 255
pos += tlen
x = ((length - offset - 1) * c0 - c1) % 255
if x <= 0:
x += 255
y = 510 - c0 - x
if y > 255:
y -= 255
data[offset] = x
data[offset+1] = y
return (x << 8) | (y & 0xff)