Better nickname parsing, warn other clients when they does not provide a parsable nickname

Signed-off-by: Yohann D'ANELLO <ynerant@crans.org>
This commit is contained in:
2020-12-21 16:04:15 +01:00
parent e37c43b78d
commit 9f070f594b
2 changed files with 32 additions and 8 deletions

View File

@ -1,6 +1,6 @@
# Copyright (C) 2020 by eichhornchen, ÿnérant
# SPDX-License-Identifier: GPL-3.0-or-later
import re
from typing import Any, List, Optional
from ipaddress import IPv6Address
from enum import Enum
@ -207,7 +207,21 @@ class DataTLV(TLV):
A message has been sent. We log it.
TODO: Check that the tuple (sender_id, nonce) is unique to avoid duplicates.
"""
squirrel.add_message(self.data.decode('UTF-8'))
msg = self.data.decode('UTF-8')
squirrel.add_message(msg)
nickname_match = re.match("(.*): (.*)", msg)
if nickname_match is None:
squirrel.send_packet(sender, Packet.construct(WarningTLV.construct(
"Unable to retrieve your username. Please use the syntax 'nickname: message'")))
else:
nickname = nickname_match.group(1)
if sender.nickname is None:
sender.nickname = nickname
elif sender.nickname != nickname:
squirrel.send_packet(sender, Packet.construct(WarningTLV.construct(
"It seems that you used two different nicknames. "
f"Known nickname: {sender.nickname}, found: {nickname}")))
sender.nickname = nickname
@staticmethod
def construct(message: str) -> "DataTLV":
@ -281,7 +295,7 @@ class WarningTLV(TLV):
def unmarshal(self, raw_data: bytes) -> None:
self.type = raw_data[0]
self.length = raw_data[1]
self.message = raw_data[2:self.length].decode("UTF-8")
self.message = raw_data[2:self.length + 2].decode("UTF-8")
def marshal(self) -> bytes:
return self.type.to_bytes(1, sys.byteorder) + \
@ -289,7 +303,15 @@ class WarningTLV(TLV):
self.message.encode("UTF-8")[:self.length]
def handle(self, squirrel: Any, sender: Any) -> None:
squirrel.add_message(f"<warning> *A client warned you: {self.message}*")
squirrel.add_message(f"warning: *A client warned you: {self.message}*")
@staticmethod
def construct(message: str) -> "WarningTLV":
tlv = WarningTLV()
tlv.type = 7
tlv.message = message
tlv.length = len(tlv.message.encode("UTF-8"))
return tlv
class Packet: