#include #include "scufeng/log.h" #include "networking.h" static const uint8_t fb = 0xfb; static const uint8_t fe = 0xfe; void PaddleChangeDirMsg_encode(const PaddleChangeDirMsg *const msg, uint8_t *buf, const size_t buf_size) { if (buf_size < PADDLE_CHANGE_DIR_MSG_ENCODED_SIZE) { LOG_FATALF("Buffer size too small (%zu), %zu required.", buf_size, PADDLE_CHANGE_DIR_MSG_ENCODED_SIZE); } memcpy(buf, &msg->dir, sizeof(msg->dir)); buf += sizeof(msg->dir); memcpy(buf, &msg->player1, sizeof(msg->player1)); } PaddleChangeDirMsg PaddleChangeDir_decode(const uint8_t *buf, const size_t buf_size) { if (buf_size < PADDLE_CHANGE_DIR_MSG_ENCODED_SIZE) { LOG_FATALF("Buffer size too small (%zu), %zu required.", buf_size, PADDLE_CHANGE_DIR_MSG_ENCODED_SIZE); } PaddleChangeDirMsg msg = {0}; memcpy(&msg.dir, buf, sizeof(msg.dir)); buf += sizeof(msg.dir); memcpy(&msg.player1, buf, sizeof(msg.player1)); return msg; } void send_msg(FILE *s, const uint8_t *const buf, const size_t buf_size) { uint8_t *buf_cpy = (uint8_t *) malloc(sizeof(uint8_t) * buf_size); memcpy(buf_cpy, buf, buf_size); for (uint8_t *p = buf_cpy; p < buf_cpy + buf_size; p++) { if (*p == fb || *p == fe) { *p += SEND_FRAME_MANGLE; } } if (fwrite(&fb, sizeof(fb), 1, s) < 1) { LOG_FATAL("[send_msg] Failed to write fb"); } if (fwrite(&buf_size, sizeof(buf_size), 1, s) < 1) { LOG_FATAL("[send_msg] Failed to write msg_len"); } if (fwrite(buf_cpy, buf_size, 1, s) < 1) { LOG_FATAL("[send_msg] Failed to write msg"); } if (fwrite(&fe, sizeof(fe), 1, s) < 1) { LOG_FATAL("[send_msg] Failed to write fe"); } if (fflush(s) != 0) { LOG_FATAL("[send_msg] Failed to flush stream"); } free(buf_cpy); } bool recv_msg(FILE *s, uint8_t *const buf, const size_t buf_size) { uint8_t _fb; if (fread(&_fb, sizeof(_fb), 1, s) < 1) { LOG_FATAL("[recv_msg] Failed to read _fb"); } if (_fb != fb) { return false; } size_t msg_len; if (fread(&msg_len, sizeof(msg_len), 1, s) < 1) { LOG_FATAL("[recv_msg] Failed to read msg_len"); } if (buf_size < msg_len) { LOG_FATALF("[recv_msg] Buffer too small. msg_len: %zu, buf_size: %zu", msg_len, buf_size); } if (fread(buf, buf_size, 1, s) < 1) { LOG_FATAL("[recv_msg] Failed to read msg"); } for (uint8_t *p = buf; p < buf + buf_size; p++) { if (*p == fb + SEND_FRAME_MANGLE || *p == fe + SEND_FRAME_MANGLE) { *p += RECV_FRAME_MANGLE; } } uint8_t _fe; if (fread(&_fe, sizeof(_fe), 1, s) < 1) { LOG_FATAL("[recv_msg] Failed to read _fe"); } if (_fe != fe) { return false; } return true; }