aboutsummaryrefslogtreecommitdiff
path: root/mctypes.c
diff options
context:
space:
mode:
authorPlex <thinkplex@riseup.net>2022-02-04 19:16:30 +0100
committerPlex <thinkplex@riseup.net>2022-02-04 19:16:30 +0100
commit28b41ee492805971632e1d65ab9f855ce837767b (patch)
tree8fee2d3206bb74fd1117536576a391a8d1725e33 /mctypes.c
parentc71e08d9daa3444318c6f768894b97b1b6d65bc9 (diff)
Factored the usage() function
Diffstat (limited to 'mctypes.c')
-rw-r--r--mctypes.c42
1 files changed, 33 insertions, 9 deletions
diff --git a/mctypes.c b/mctypes.c
index c4df793..3be3209 100644
--- a/mctypes.c
+++ b/mctypes.c
@@ -1,24 +1,28 @@
#include "mctypes.h"
#include <stdlib.h>
#include <string.h>
+#include <stdio.h>
varint to_varint(unsigned int x)
{
- varint n = malloc(sizeof(u_int8_t));
- unsigned int size = 1;
+ varint n = NULL;
+ unsigned int size = 0;
while (1) {
n = reallocarray(n, size, sizeof(u_int8_t));
- n[size - 1] = x & 0x7F;
+ if(n == NULL){
+ exit(1);
+ }
+ n[size] = x & 0x7F;
x >>= 7;
if (x == 0)
return n;
- n[size - 1] |= 0x80;
+ n[size] |= 0x80;
size++;
}
return n;
}
-int from_varint(varint x)
+int from_varint(const varint x)
{
unsigned int offset = 0;
unsigned int res = 0;
@@ -31,7 +35,7 @@ int from_varint(varint x)
return (int) res;
}
-size_t size_varint(varint x)
+size_t size_varint(const varint x)
{
size_t v_size;
for (v_size = 1; (x[v_size - 1] & 0x80) != 0; v_size++);
@@ -42,11 +46,11 @@ size_t serialize_handshake(handshake hs, void **buf)
{
size_t size = 0;
size_t varint_s;
- *buf = malloc(size);
+ // *buf = malloc(size);
varint_s = size_varint(hs.protocol_version);
*buf = realloc(*buf, size + varint_s);
- memcpy(*buf + size, hs.protocol_version, varint_s);
+ memmove(*buf + size, hs.protocol_version, varint_s);
size += varint_s;
varint_s = size_varint(hs.server_address.length);
@@ -71,7 +75,7 @@ size_t serialize_handshake(handshake hs, void **buf)
return size;
}
-size_t serialize_packet(packet p, void **buf)
+size_t serialize_packet(const packet p, void **buf)
{
size_t v_size = size_varint(p.length);
size_t p_size = from_varint(p.length) + v_size; // total size of packet
@@ -93,21 +97,41 @@ size_t serialize_packet(packet p, void **buf)
varint deserialize_varint(void **raw)
{
varint v = NULL;
+ // void *f = *raw;
unsigned short i = 0;
do {
v = reallocarray(v, i+1, sizeof(u_int8_t));
+ if(v == NULL){
+ exit(1);
+ }
memcpy(v+i, *raw, sizeof(u_int8_t));
(*raw)++;
i++;
} while ((v[i-1] & 0x80) != 0);
+ // free(f);
return v;
}
string deserialize_string(void **raw)
{
string s;
+ // void *f = *raw;
s.length = deserialize_varint(raw);
s.content = malloc(from_varint(s.length));
memcpy(s.content, *raw, from_varint(s.length));
return s;
};
+
+void free_packet(packet p)
+{
+ free(p.length);
+ free(p.id);
+ free(p.data);
+}
+
+void free_handshake(handshake h)
+{
+ free(h.protocol_version);
+ free(h.server_address.length);
+ free(h.next_state);
+}