aboutsummaryrefslogtreecommitdiff
path: root/i2ctcp/i2ctcpv1.c
diff options
context:
space:
mode:
authorElwin Hammer <elwinhammer@gmail.com>2024-05-29 21:41:24 +0200
committerGitHub <noreply@github.com>2024-05-29 21:41:24 +0200
commit1f78927e2e399a504368fb9b407de12d06dddcb5 (patch)
treef80ba30274ca75704075610a39fc28930f7ac4fa /i2ctcp/i2ctcpv1.c
parentd7616546dd5e8ba35c2b1b1ece736bca60e0b990 (diff)
parent8894d20ff0d1c1dde69879a21e756e01bcfa5262 (diff)
Merge pull request #11 from lonkaars/masterprot/software-puzzle
Bring software-puzzle up-to-date
Diffstat (limited to 'i2ctcp/i2ctcpv1.c')
-rw-r--r--i2ctcp/i2ctcpv1.c54
1 files changed, 54 insertions, 0 deletions
diff --git a/i2ctcp/i2ctcpv1.c b/i2ctcp/i2ctcpv1.c
new file mode 100644
index 0000000..36a5dbd
--- /dev/null
+++ b/i2ctcp/i2ctcpv1.c
@@ -0,0 +1,54 @@
+#include <mpack.h>
+#include <stdio.h>
+
+// MIN() macro
+#include <sys/param.h>
+
+#include "i2ctcpv1.h"
+
+int i2ctcp_read(i2ctcp_msg_t * target, const char * buf, size_t buf_sz) {
+ // a new reader is used per buffer block passed to this function
+ mpack_reader_t reader;
+ mpack_reader_init_data(&reader, buf, buf_sz);
+
+ // at start of message
+ if (target->_rdata == 0) {
+ // NOTE: The entire start of a message needs to be readable from the buffer
+ // at this point. When target->addr can be read and target->length is past
+ // the end of the current buffer block, this function will crash and burn.
+ // This is a highly unlikely scenario, as i2ctcp_read is called for each
+ // chunk of a TCP frame, and frames (should) include only one puzzle bus
+ // message. The check here is kind of optional.
+ if (buf_sz < 4) return -1;
+
+ target->addr = mpack_expect_u16(&reader);
+ target->length = target->_rdata = mpack_expect_bin(&reader);
+ target->data = (char *) malloc(target->length);
+ }
+
+ // continue reading chunks of target->data until the amount of bytes
+ // specified in target->length
+ size_t to_read = MIN(mpack_reader_remaining(&reader, NULL), target->_rdata);
+ char * data = target->data + target->length - target->_rdata;
+ mpack_read_bytes(&reader, data, to_read);
+ target->_rdata -= to_read;
+
+ // if rdata = 0, the message was completely read
+ return target->_rdata;
+}
+
+void i2ctcp_read_reset(i2ctcp_msg_t * target) {
+ target->_rdata = 0;
+}
+
+bool i2ctcp_write(const i2ctcp_msg_t * target, char ** buf, size_t * buf_sz) {
+ mpack_writer_t writer;
+ mpack_writer_init_growable(&writer, buf, buf_sz);
+
+ mpack_write_u16(&writer, target->addr);
+ mpack_write_bin(&writer, target->data, target->length);
+
+ // finish writing
+ return mpack_writer_destroy(&writer) == mpack_ok;
+}
+