From e1f0d54ac803ee7fc0f81147c32f83e6f11d7467 Mon Sep 17 00:00:00 2001 From: Yohann D'ANELLO Date: Mon, 21 Dec 2020 16:04:16 +0100 Subject: [PATCH] Use a random squirrel id and an incremental nonce Signed-off-by: Yohann D'ANELLO --- squinnondation/hazel.py | 11 +++++++++-- squinnondation/messages.py | 10 +++++++--- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/squinnondation/hazel.py b/squinnondation/hazel.py index b01428d..28bdb16 100644 --- a/squinnondation/hazel.py +++ b/squinnondation/hazel.py @@ -1,6 +1,7 @@ # Copyright (C) 2020 by eichhornchen, ÿnérant # SPDX-License-Identifier: GPL-3.0-or-later from datetime import datetime +from random import randint from typing import Any, Tuple from ipaddress import IPv6Address from threading import Thread @@ -17,6 +18,7 @@ class Hazelnut: """ def __init__(self, nickname: str = None, address: str = "localhost", port: int = 2500): self.nickname = nickname + self.id = -1 try: # Resolve DNS as an IPv6 @@ -37,6 +39,11 @@ class Squirrel(Hazelnut): """ def __init__(self, instance: Any, nickname: str): super().__init__(nickname, instance.bind_address, instance.bind_port) + + # Random identifier on 64 bits + self.id = randint(0, 1 << 64 - 1) + self.incr_nonce = 0 + # Create UDP socket self.socket = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) # Bind the socket @@ -175,7 +182,7 @@ class Squirrel(Hazelnut): elif key != "\n": # Insert the pressed key in the current message new_buffer = self.input_buffer[:self.input_index] + key + self.input_buffer[self.input_index:] - if len(DataTLV.construct(f"{self.nickname}: {new_buffer}")) > 255 - 8 - 4: + if len(DataTLV.construct(f"{self.nickname}: {new_buffer}", None)) > 255 - 8 - 4: # The message is too long to be sent once. We don't allow the user to type any other character. curses.beep() return @@ -194,7 +201,7 @@ class Squirrel(Hazelnut): msg = f"{self.nickname}: {msg}" self.add_message(msg) - pkt = Packet.construct(DataTLV.construct(msg)) + pkt = Packet.construct(DataTLV.construct(msg, self)) for hazelnut in list(self.hazelnuts.values()): self.send_packet(hazelnut, pkt) diff --git a/squinnondation/messages.py b/squinnondation/messages.py index 7080e74..f36577e 100644 --- a/squinnondation/messages.py +++ b/squinnondation/messages.py @@ -227,13 +227,17 @@ class DataTLV(TLV): sender.nickname = nickname @staticmethod - def construct(message: str) -> "DataTLV": + def construct(message: str, squirrel: Any) -> "DataTLV": tlv = DataTLV() tlv.type = 4 - tlv.sender_id = 42 # FIXME Use the good sender id - tlv.nonce = 42 # FIXME Use an incremental nonce + tlv.sender_id = squirrel.id if squirrel else 0 + tlv.nonce = squirrel.incr_nonce if squirrel else 0 tlv.data = message.encode("UTF-8") tlv.length = 12 + len(tlv.data) + + if squirrel: + squirrel.incr_nonce += 1 + return tlv