From ab73580c2321c36bf486cb876dff2734b87768f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juhani=20Krekel=C3=A4?= Date: Wed, 10 Jul 2019 14:00:44 +0300 Subject: [PATCH] Check msgid on receive and update caches --- ethermess.c | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/ethermess.c b/ethermess.c index 7f17916..d144b25 100644 --- a/ethermess.c +++ b/ethermess.c @@ -446,7 +446,42 @@ void handle_message(const unsigned char source_mac[6], const unsigned char *data // TODO: Check that the message is valid utf-8 with newline as the only control char - // TODO: Check whether we've received this message already and update msgid cache + // See whether we've already received this message and update the next msgid if so + ssize_t cache_index = msgid_cache_lookup(source_mac); + if (cache_index == -1) { + // No cache entry -> add an empty one + cache_index = msgid_cache_add(source_mac); + } + + if (!msgid_cache[cache_index].know_receive) { + // We have a cache entry, but no idea what next message to receive + // Assume this is not a repeat transmission, and accept the message + // The easiest way to do this is to set this message's msgid as the + // one we're looking to receive + msgid_cache[cache_index].next_receive = msgid; + msgid_cache[cache_index].know_receive = true; + } + + if (msgid_cache[cache_index].next_receive - msgid < 0x8000) { + // The msgid counter can wrap around, so a simple larger than + // comparison will not work. Instead, we look at the distance + // between the message's msgid and the one we're expecting to + // receive. If it is from 0 to 0x8000, we consider it to be + // in the forwards direction, and if it is more, we consider it + // to be in the backwards one. This leaves equally sized (2^15) + // ranges for values in both cases. + + // In this case the msgid is considered to be of a message we + // haven't yet seen. Therefore we'll continue processing, and + // update the next msgid we're expecting to receive to this one + // plus 1 + msgid_cache[cache_index].next_receive = msgid + 1; + } else { + // In this case we consider the message already received + // We will send an ack, but not process it any further + send_ack(source_mac, msgid); + return; + } char mac[18]; format_mac(source_mac, mac);