Files
meshcore-wch/User/meshcore/packets/group.c
2025-12-22 23:02:29 +01:00

108 lines
3.0 KiB
C

#include "ch32v30x_rtc.h"
#include "meshcore/meshframing.h"
#include "meshcore/packetstructs.h"
#include "group.h"
#include "lib/config.h"
#include "util/hexdump.h"
#include "util/log.h"
#include "string.h"
#define TAG "GroupMessage"
void sendGroupMessage (GroupTextMessage msg) {
msg.channelHash = persistent.aesKeys[msg.keyIndex][0];
msg.flags = 0;
msg.timestamp = RTC_GetCounter();
FrameStruct frame;
frame.header = ROUTE_TYPE_FLOOD | PAYLOAD_TYPE_GRP_TXT | PAYLOAD_VERSION_0;
frame.path.pathLen = 0;
size_t offset = 0;
memset (frame.payload, 0, sizeof (frame.payload));
frame.payload[offset++] = msg.channelHash;
uint8_t cipherBuf[176];
size_t offset2 = 0;
memcpy (cipherBuf, (const void *)&(msg.timestamp), 4);
offset2 += 4;
cipherBuf[offset2++] = msg.flags;
size_t textSize = offset2 + strlen ((const char *)msg.text);
if (textSize > 175) {
textSize = 175;
}
memcpy (cipherBuf + offset2, msg.text, textSize);
offset2 += textSize;
size_t olen = 0;
hexdump ("TxDumpDec", cipherBuf, offset2);
encrypt_then_mac (&(persistent.aesKeys[msg.keyIndex][1]), 16, cipherBuf, offset2, &(frame.payload[offset]), &olen);
frame.payloadLen = olen + 1;
sendFrame (frame);
return;
}
void makeSendGroupMessage (char *txt, uint8_t keyIndex) {
GroupTextMessage msg;
strcpy((char *) msg.text, persistent.nodeName);
strcat ((char *)msg.text, ": ");
strcat ((char *)msg.text, txt);
msg.keyIndex = keyIndex;
sendGroupMessage (msg);
return;
}
GroupTextMessage decodeGroupMessage (FrameStruct frame) {
GroupTextMessage msg;
memset (&msg, 0, sizeof (msg));
if ((frame.header & PAYLOAD_TYPE_MASK) != PAYLOAD_TYPE_GRP_TXT) {
ESP_LOGW (TAG, "Not a group text");
return msg;
}
unsigned char index = 0;
msg.channelHash = frame.payload[index++];
unsigned char tmp[184];
unsigned char decrypted = 0;
for (unsigned char i = 0; i < AESKeyCount; i++) {
if (msg.channelHash != persistent.aesKeys[i][0]) {
ESP_LOGW (TAG, "Hash %d does not equal %d", persistent.aesKeys[i][0], msg.channelHash);
continue;
}
ESP_LOGW (TAG, "Hash does equal %d", msg.channelHash);
if (mac_then_decrypt (persistent.aesKeys[i] + 1, 16, frame.payload + index, frame.payloadLen - index, tmp) != 0) {
ESP_LOGW (TAG, "HMAC failed on grouphash key %d not matching %d", persistent.aesKeys[i][0], msg.channelHash);
continue;
}
hexdump ("RxDumpDec", tmp, frame.payloadLen - index);
decrypted = 1;
break;
}
if (!decrypted) {
return msg;
}
unsigned char plaintextLen = frame.payloadLen - index;
index = 0;
memcpy (&msg.timestamp, tmp + index, 4);
index += 4;
msg.flags = tmp[index++];
memcpy (msg.text, tmp + index, plaintextLen - index);
return msg;
}
void printGroupMessage (GroupTextMessage msg) {
printf ("Message with channel hash %d, flags %d: %s\n", msg.channelHash,
msg.flags, msg.text);
}