From 18be89f6e87312edad7834cc0a0aef7d32739bc8 Mon Sep 17 00:00:00 2001 From: Conrad Hoffmann Date: Mon, 14 Aug 2023 21:31:47 +0200 Subject: [PATCH] Fix checksum calculation and test it Signed-off-by: Conrad Hoffmann --- net/icmp/+test.ha | 5 +++++ net/icmp/message.ha | 14 ++++++-------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/net/icmp/+test.ha b/net/icmp/+test.ha index fe79d92..0d4a5b6 100644 --- a/net/icmp/+test.ha +++ b/net/icmp/+test.ha @@ -18,6 +18,7 @@ use bytes; let outbuf = memio::dynamic(); let encsz = encode(&outbuf, &inmsg)!; assert(encsz == 13); + assert(inmsg.checksum == 8672); let msg = memio::buffer(&outbuf); @@ -60,6 +61,7 @@ use bytes; let outbuf = memio::dynamic(); let encsz = encode(&outbuf, &inmsg)!; assert(encsz == 13); + assert(inmsg.checksum == 10720); let msg = memio::buffer(&outbuf); @@ -98,6 +100,7 @@ use bytes; let outbuf = memio::dynamic(); let encsz = encode(&outbuf, &inmsg)!; assert(encsz == 4); + assert(inmsg.checksum == 64757); let msg = memio::buffer(&outbuf); @@ -129,6 +132,7 @@ use bytes; let outbuf = memio::dynamic(); let encsz = encode(&outbuf, &inmsg)!; assert(encsz == 4); + assert(inmsg.checksum == 62709); let msg = memio::buffer(&outbuf); @@ -161,6 +165,7 @@ use bytes; let outbuf = memio::dynamic(); let encsz = encode(&outbuf, &inmsg)!; assert(encsz == 6); + assert(inmsg.checksum == 62440); let msg = memio::buffer(&outbuf); diff --git a/net/icmp/message.ha b/net/icmp/message.ha index cbeefeb..9e2c91f 100644 --- a/net/icmp/message.ha +++ b/net/icmp/message.ha @@ -56,21 +56,19 @@ fn checksum(msg: []u8) u16 = { let cov: size = len(msg) - 1z; let s: u32 = 0; - for (let i = 0z; i < cov; i += 1) { - s += ((msg[i + 1]: u32) << 8) | msg[i]: u32; + for (let i = 0z; i < cov; i += 2) { + s += ((msg[i]: u32) << 8) + msg[i + 1]: u32; }; if (cov & 1 == 0) { s += msg[cov]: u32; }; - s = (s >> 16) + (s & 0xffff); - - s = s + (s >> 16); - - s ^= s: u16; + for ((s >> 16) != 0) { + s = (s >> 16) + (s & 0xffff); + }; - return s: u16; + return ~s: u16; }; // Encodes a [[message]] into the [[io::handle]] provided -- 2.45.2