diff options
author | Plex <thinkplex@riseup.net> | 2021-10-25 16:35:18 +0200 |
---|---|---|
committer | Plex <thinkplex@riseup.net> | 2021-10-25 16:35:18 +0200 |
commit | 53a085962964f4db118619a5e2156c901aba55a6 (patch) | |
tree | fa64b9942a1a663e77edec8276986ac7d3c0ee36 /mctypes.c | |
parent | d33fabf0c5e1ea9a4e3118836dc459fa971d7a1d (diff) |
serialization underway
Diffstat (limited to 'mctypes.c')
-rw-r--r-- | mctypes.c | 45 |
1 files changed, 39 insertions, 6 deletions
@@ -7,13 +7,13 @@ varint writeVarInt(unsigned int x) { varint n = malloc(sizeof(u_int8_t)); unsigned int size = 1; - while(1) { + while (1) { n = reallocarray(n, size, sizeof(u_int8_t)); - n[size-1] = x & 0x7F; + n[size - 1] = x & 0x7F; x >>= 7; - if(x == 0) + if (x == 0) return n; - n[size-1] |= 0x80; + n[size - 1] |= 0x80; size++; } return n; @@ -24,9 +24,42 @@ int readVarInt(varint x) unsigned int offset = 0; unsigned int res = 0; do { - if(offset == 5) exit(EXIT_FAILURE); - res |= (x[offset] & 0b01111111) << offset*7; + if (offset == 5) + exit(EXIT_FAILURE); + res |= (x[offset] & 0b01111111) << offset * 7; offset++; } while ((x[offset-1] & 0b10000000) != 0); return (int) res; } + +size_t serializeHandshake(handshake hs, void *buf) +{ + size_t size = 0; + size_t vi_size; + buf = malloc(size); + + for (vi_size = 1; (hs.protocol_version[vi_size - 1] & 0x80) != 0; vi_size++); + buf = realloc(buf, size+vi_size); + memcpy(buf + size, hs.protocol_version, vi_size); + size += vi_size; + + for (vi_size = 1; (hs.server_address.length[vi_size - 1] & 0x80) != 0; vi_size++); + buf = realloc(buf, size+vi_size); + memcpy(buf + size, hs.server_address.length, vi_size); + size += vi_size; + + buf = realloc(buf, size+readVarInt(hs.server_address.length)); + memcpy(buf + size, hs.server_address.content, readVarInt(hs.server_address.length)); + size += readVarInt(hs.server_address.length); + + buf = realloc(buf, size+sizeof(unsigned short)); + memcpy(buf + size, &hs.server_port, sizeof(unsigned short)); + size += sizeof(unsigned short); + + for (vi_size = 1; (hs.next_state[vi_size - 1] & 0x80) != 0; vi_size++); + buf = realloc(buf, size+vi_size); + memcpy(buf + size, hs.next_state, vi_size); + size += vi_size; + + return size; +} |