LibTMJ 2.0.0
A library for loading JSON Tiled maps
Loading...
Searching...
No Matches
decode.c
Go to the documentation of this file.
1#include <stdbool.h>
2#include <stdlib.h>
3#include <string.h>
4
5#include "decode.h"
6#include "log.h"
7
8#ifdef LIBTMJ_ZSTD
9
10uint8_t* tmj_zstd_decompress(const uint8_t* data, size_t data_size, size_t* decompressed_size) {
11 logmsg(TMJ_LOG_DEBUG, "Decode (zstd): Decompressing buffer of size %zu", data_size);
12
13 if (data == NULL) {
14 logmsg(TMJ_LOG_ERR, "Decode (zstd): Cannot decompress NULL buffer");
15
16 return NULL;
17 }
18
19 size_t ret_size = ZSTD_getFrameContentSize(data, data_size);
20
21 if (ret_size == ZSTD_CONTENTSIZE_ERROR) {
22 logmsg(TMJ_LOG_ERR, "Decode (zstd): Unable to decompress non-zstd buffer");
23
24 return NULL;
25 }
26
27 if (ret_size == ZSTD_CONTENTSIZE_UNKNOWN) {
28 logmsg(TMJ_LOG_ERR, "Decode (zstd): Unable to determine uncompressed size of compressed data");
29
30 return NULL;
31 }
32
33 void* ret = malloc(ret_size);
34
35 if (ret == NULL) {
36 logmsg(TMJ_LOG_ERR, "Decode (zstd): Unable to allocate buffer for decompressed data, the system is out of memory");
37
38 return NULL;
39 }
40
41 size_t dsize = ZSTD_decompress(ret, ret_size, data, data_size);
42
43 logmsg(TMJ_LOG_DEBUG, "Decode (zstd): Decompressed byte total: %zu", dsize);
44
45 if (ZSTD_isError(dsize)) {
46 logmsg(TMJ_LOG_ERR, "Decode (zstd): Decompression error: %s", ZSTD_getErrorName(dsize));
47
48 free(ret);
49
50 return NULL;
51 }
52
53 *decompressed_size = ret_size;
54
55 return ret;
56}
57
58#endif
59
60#ifdef LIBTMJ_ZLIB
61
62uint8_t* tmj_zlib_decompress(const uint8_t* data, size_t data_size, size_t* decompressed_size) {
63 logmsg(TMJ_LOG_DEBUG, "Decode (zlib): Decompressing buffer of size %zu", data_size);
64
65 if (data == NULL) {
66 logmsg(TMJ_LOG_ERR, "Decode (zlib): Cannot decompress NULL buffer");
67
68 return NULL;
69 }
70
71 const size_t INFLATE_BLOCK_SIZE = 262144;
72
73 uint8_t* out = malloc(INFLATE_BLOCK_SIZE);
74
75 if (out == NULL) {
76 logmsg(TMJ_LOG_ERR, "Decode (zlib): Unable to allocate buffer for decompressed data, the system is out of memory");
77
78 return NULL;
79 }
80
81 z_stream stream = {0};
82
83 stream.zalloc = Z_NULL;
84 stream.zfree = Z_NULL;
85 stream.opaque = Z_NULL;
86
87 stream.avail_in = data_size;
88 stream.avail_out = INFLATE_BLOCK_SIZE;
89
90 stream.next_in = data; // NOLINT(clang-diagnostic-incompatible-pointer-types-discards-qualifiers)
91 stream.next_out = out;
92
93 // 15 + 32 for zlib and gzip decoding with automatic header detection, according to the manual
94 int ret = inflateInit2(&stream, 15 + 32);
95
96 switch (ret) {
97 case Z_OK:
98 logmsg(TMJ_LOG_DEBUG, "Decode (zlib): inflate initialization OK");
99 break;
100
101 case Z_MEM_ERROR:
102 logmsg(TMJ_LOG_ERR, "Decode (zlib): Unable to initialize inflate, the system is out of memory");
103
104 goto fail_zlib;
105
106 case Z_VERSION_ERROR:
107 logmsg(TMJ_LOG_ERR, "Decode (zlib): Unable to initialize inflate, incompatible zlib library version");
108
109 goto fail_zlib;
110
111 case Z_STREAM_ERROR:
113 "Decode (zlib): Unable to initialize inflate, invalid parameter(s) to inflate initialization "
114 "routine");
115
116 goto fail_zlib;
117
118 default:
119 goto fail_zlib;
120 }
121
122 size_t realloc_scale = 2;
123
124 // Iteratively inflate, growing the output buffer by 1 block each time we run out of space
125 //
126 // Note from the manual: "If inflate returns Z_OK and with zero avail_out,
127 // it must be called again after making room in the output buffer because
128 // there might be more output pending."
129 // Unsure if this is actually necessary, or if we can rely on Z_BUF_ERROR to tell us when to resize
130 int stat = inflate(&stream, Z_NO_FLUSH);
131
132 while (stat != Z_STREAM_END) {
133 switch (stat) {
134 case Z_BUF_ERROR:
135 // If we hit Z_BUF_ERROR with buffer space left, something's fucked
136 if (stream.avail_out != 0) {
137 logmsg(TMJ_LOG_ERR, "Decode (zlib): No progress possible");
138
139 goto fail_zlib;
140 }
141
142 logmsg(TMJ_LOG_DEBUG, "Decode (zlib): Z_BUF_ERROR");
143 case Z_OK:
144 logmsg(TMJ_LOG_DEBUG, "Decode (zlib): inflate OK");
145
146 void* tmp = realloc(out, INFLATE_BLOCK_SIZE * realloc_scale);
147
148 if (tmp == NULL) {
149 logmsg(TMJ_LOG_ERR, "Decode (zlib): Unable to grow inflate output buffer, the system is out memory");
150
151 goto fail_zlib;
152 }
153
154 out = tmp;
155
156 stream.avail_out = INFLATE_BLOCK_SIZE;
157
158 stream.next_out = out + stream.total_out;
159
160 realloc_scale++;
161
162 break;
163
164 case Z_NEED_DICT:
165 logmsg(TMJ_LOG_ERR, "Decode (zlib): Unable to complete inflate, preset dictionary required");
166
167 goto fail_zlib;
168
169 case Z_DATA_ERROR:
170 logmsg(TMJ_LOG_ERR, "Decode (zlib): Unable to complete inflate, input data appears corrupted");
171
172 goto fail_zlib;
173
174 case Z_STREAM_ERROR:
175 logmsg(TMJ_LOG_ERR, "Decode (zlib): Unable to complete inflate, stream structure inconsistent");
176
177 goto fail_zlib;
178
179 case Z_MEM_ERROR:
180 logmsg(TMJ_LOG_ERR, "Decode (zlib): Unable to complete inflate, the system is out of memory");
181
182 goto fail_zlib;
183
184 default:
185 goto fail_zlib;
186 }
187
188 stat = inflate(&stream, Z_NO_FLUSH);
189 }
190
191 logmsg(TMJ_LOG_DEBUG, "Decode (zlib): Completed inflate, %zd bytes written to output buffer", stream.total_out);
192
193 if (inflateEnd(&stream) != Z_OK) {
194 logmsg(TMJ_LOG_ERR, "Decode (zlib): Completed inflate, but could not clean up; stream state was inconsistent");
195
196 goto fail_zlib;
197 }
198
199 *decompressed_size = stream.total_out;
200
201 return out;
202
203fail_zlib:
204 if (stream.msg) {
205 logmsg(TMJ_LOG_ERR, "Decode (zlib): zlib error: '%s'", stream.msg);
206 }
207
208 inflateEnd(&stream);
209
210 free(out);
211
212 return NULL;
213}
214
215uint8_t* tmj_zlib_compress(const uint8_t* data, size_t data_size, int level, size_t* compressed_size) {
216 logmsg(TMJ_LOG_DEBUG, "Decode (zlib): Compressing buffer of size %zu", data_size);
217
218 if (data == NULL) {
219 logmsg(TMJ_LOG_ERR, "Decode (zlib): Cannot compress NULL buffer");
220
221 return NULL;
222 }
223
224 const size_t DEFLATE_BLOCK_SIZE = 262144;
225
226 uint8_t* out = malloc(DEFLATE_BLOCK_SIZE);
227
228 if (out == NULL) {
229 logmsg(TMJ_LOG_ERR, "Decode (zlib): Unable to allocate buffer for compressed data, the system is out of memory");
230
231 return NULL;
232 }
233
234 z_stream stream = {0};
235
236 stream.zalloc = Z_NULL;
237 stream.zfree = Z_NULL;
238 stream.opaque = Z_NULL;
239
240 stream.avail_in = data_size;
241 stream.avail_out = DEFLATE_BLOCK_SIZE;
242
243 stream.next_in = data; // NOLINT(clang-diagnostic-incompatible-pointer-types-discards-qualifiers)
244 stream.next_out = out;
245
246 int ret = deflateInit(&stream, level);
247
248 switch (ret) {
249 case Z_OK:
250 logmsg(TMJ_LOG_DEBUG, "Decode (zlib): deflate initialization OK");
251 break;
252
253 case Z_MEM_ERROR:
254 logmsg(TMJ_LOG_ERR, "Decode (zlib): Unable to initialize deflate, the system is out of memory");
255
256 goto fail_zlib;
257
258 case Z_VERSION_ERROR:
259 logmsg(TMJ_LOG_ERR, "Decode (zlib): Unable to initialize deflate, incompatible zlib library version");
260
261 goto fail_zlib;
262
263 case Z_STREAM_ERROR:
265 "Decode (zlib): Unable to initialize deflate, invalid parameter(s) to deflate initialization "
266 "routine");
267
268 goto fail_zlib;
269
270 default:
271 goto fail_zlib;
272 }
273
274 size_t realloc_scale = 2;
275
276 // Iteratively deflate, growing the output buffer by 1 block each time we run out of space
277 int flush = Z_NO_FLUSH;
278 int stat = deflate(&stream, flush);
279
280 while (stat != Z_STREAM_END) {
281 switch (stat) {
282 case Z_BUF_ERROR:
283 if (stream.avail_out != 0) {
284 logmsg(TMJ_LOG_ERR, "Decode (zlib): No progress possible");
285
286 return NULL;
287 }
288
289 logmsg(TMJ_LOG_DEBUG, "Decode (zlib): Z_BUF_ERROR");
290 case Z_OK:
291 logmsg(TMJ_LOG_DEBUG, "Decode (zlib): deflate OK");
292
293 if (stream.avail_out == 0) { // more space needed
294 void* tmp = realloc(out, DEFLATE_BLOCK_SIZE * realloc_scale);
295
296 if (tmp == NULL) {
297 logmsg(TMJ_LOG_ERR, "Decode (zlib): Unable to grow deflate output buffer, the system is out memory");
298
299 goto fail_zlib;
300 }
301
302 out = tmp;
303
304 stream.avail_out = DEFLATE_BLOCK_SIZE;
305
306 stream.next_out = out + stream.total_out;
307
308 realloc_scale++;
309 } else { // finished!
310 flush = Z_FINISH;
311 }
312
313 break;
314
315 case Z_STREAM_ERROR:
316 logmsg(TMJ_LOG_ERR, "Decode (zlib): Unable to complete deflate, stream structure inconsistent");
317
318 goto fail_zlib;
319
320 default:
321 goto fail_zlib;
322 }
323
324 stat = deflate(&stream, flush);
325 }
326
327 logmsg(TMJ_LOG_DEBUG, "Decode (zlib): Completed deflate, %zd bytes written to output buffer", stream.total_out);
328
329 if (deflateEnd(&stream) != Z_OK) {
330 logmsg(TMJ_LOG_ERR, "Decode (zlib): Completed deflate, but could not clean up; stream state was inconsistent");
331
332 goto fail_zlib;
333 }
334
335 *compressed_size = stream.total_out;
336
337 return out;
338
339fail_zlib:
340 if (stream.msg) {
341 logmsg(TMJ_LOG_ERR, "Decode (zlib): zlib error: '%s'", stream.msg);
342 }
343
344 deflateEnd(&stream);
345
346 free(out);
347
348 return NULL;
349}
350
351#endif
352
353// Thanks to John's article for explaining Base64: https://nachtimwald.com/2017/11/18/base64-encode-and-decode-in-c/
354
355// clang-format off
356const char b64_encode_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
357const unsigned char b64_decode_table[] = { 255, 255, 255, 255, 255, 255, 255, 255, 255,
358255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
359255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
360255, 255, 62, 255, 255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255,
361255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
36215, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255, 255, 26,
36327, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46,
36447, 48, 49, 50, 51, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
365255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
366255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
367255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
368255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
369255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
370255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
371255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
372255, 255, 255, 255, 255, 255, 255, 255, 255, };
373// clang-format on
374
375// Not used, but included here for reference, to explain how the decode table was generated
376// void b64_generate_decode_table(){
377// memset(&b64_decode_table, -1, 256);
378//
379// for(size_t i = 0; i < 256; i++){
380// b64_decode_table[b64_encode_table[i]] = i;
381// }
382//}
383
387size_t b64_decode_size(const char* data) {
388 if (data == NULL) {
389 return 0;
390 }
391
392 size_t len = strlen(data);
393
394 if (len == 0) {
395 return 0;
396 }
397
398 size_t ret = len / 4 * 3;
399
400 // Check to see if the last 2 characters are padding bytes
401 if (data[len - 1] == '=') {
402 ret--;
403
404 if (data[len - 2] == '=') {
405 ret--;
406 }
407 }
408
409 return ret;
410}
411
412bool b64_is_alnum(char c) {
413 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9');
414}
415
416uint8_t* tmj_b64_decode(const char* data, size_t* decoded_size) {
417 if (data == NULL) {
418 logmsg(TMJ_LOG_ERR, "Decode (b64): Unable to decode null input");
419
420 return NULL;
421 }
422
423 size_t len = strlen(data);
424
425 if (len % 4 != 0) {
426 logmsg(TMJ_LOG_ERR, "Decode (b64): Invalid Base64 string, input length is not a multiple of 4");
427
428 return NULL;
429 }
430
431 size_t dSize = b64_decode_size(data);
432 uint8_t* out = malloc(dSize);
433
434 if (out == NULL) {
435 logmsg(TMJ_LOG_ERR, "Decode (b64): Unable to allocate output buffer, the system is out of memory");
436
437 return NULL;
438 }
439
440 // Validate the input
441 for (size_t i = 0; i < len; i++) {
442 if (b64_is_alnum(data[i])) {
443 continue;
444 }
445
446 if (data[i] == '+' || data[i] == '/') {
447 continue;
448 }
449
450 // Allow '=' only if it's one of the last two chars, and only allow it
451 // in the len - 2 position if the last char is also a '='.
452 if ((i == len - 1 || i == len - 2) && data[i] == '=' && data[len - 1] == '=') {
453 continue;
454 }
455
456 logmsg(TMJ_LOG_ERR, "Decode (b64): Invalid Base64 character, '%c'", data[i]);
457
458 free(out);
459
460 return NULL;
461 }
462
463 for (size_t i = 0, j = 0; i < len; i += 4, j += 3) {
464 // Pack decoded 6-bit values into an integer
465 uint32_t p = b64_decode_table[data[i]];
466 p = (p << 6) | b64_decode_table[data[i + 1]];
467 p = data[i + 2] == '=' ? p << 6 : (p << 6) | b64_decode_table[data[i + 2]];
468 p = data[i + 3] == '=' ? p << 6 : (p << 6) | b64_decode_table[data[i + 3]];
469
470 // Reinterpret into 8-bit bytes
471 out[j] = (p >> 16) & 0xFF;
472 if (data[i + 2] != '=') {
473 out[j + 1] = (p >> 8) & 0xFF;
474 }
475 if (data[i + 3] != '=') {
476 out[j + 2] = p & 0xFF;
477 }
478 }
479
480 *decoded_size = dSize;
481
482 return out;
483}
484
485size_t b64_encoded_size(size_t inlen) {
486 size_t ret;
487
488 ret = inlen;
489 if (inlen % 3 != 0)
490 ret += 3 - (inlen % 3);
491 ret /= 3;
492 ret *= 4;
493
494 return ret;
495}
496
497char* tmj_b64_encode(uint8_t* data, size_t size) {
498 if (data == NULL || size == 0) {
499 logmsg(TMJ_LOG_ERR, "Encode (b64): Unable to encode null input");
500
501 return NULL;
502 }
503
504 size_t enc_size = b64_encoded_size(size);
505 char* out = malloc(enc_size + 1);
506
507 if (out == NULL) {
508 logmsg(TMJ_LOG_ERR, "Encode (b64): Unable to allocate output buffer, the system is out of memory");
509
510 return NULL;
511 }
512
513 out[enc_size] = '\0';
514
515 for (size_t i = 0, j = 0; i < size; i += 3, j += 4) {
516 size_t v = data[i];
517 v = i + 1 < size ? v << 8 | data[i + 1] : v << 8;
518 v = i + 2 < size ? v << 8 | data[i + 2] : v << 8;
519
520 out[j] = b64_encode_table[(v >> 18) & 0x3F];
521 out[j + 1] = b64_encode_table[(v >> 12) & 0x3F];
522 if (i + 1 < size) {
523 out[j + 2] = b64_encode_table[(v >> 6) & 0x3F];
524 } else {
525 out[j + 2] = '=';
526 }
527 if (i + 2 < size) {
528 out[j + 3] = b64_encode_table[v & 0x3F];
529 } else {
530 out[j + 3] = '=';
531 }
532 }
533
534 return out;
535}
const unsigned char b64_decode_table[]
Definition decode.c:357
bool b64_is_alnum(char c)
Definition decode.c:412
size_t b64_encoded_size(size_t inlen)
Definition decode.c:485
const char b64_encode_table[]
Definition decode.c:356
size_t b64_decode_size(const char *data)
Calculates the size of the data decoded from the given base64 string.
Definition decode.c:387
char * tmj_b64_encode(uint8_t *data, size_t size)
Encodes a base64 string.
Definition decode.c:497
uint8_t * tmj_b64_decode(const char *data, size_t *decoded_size)
Decodes a base64 string.
Definition decode.c:416
uint8_t * tmj_zstd_decompress(const uint8_t *data, size_t data_size, size_t *decompressed_size)
Decompresses a zstd-compressed buffer of bytes.
Definition decode.c:10
uint8_t * tmj_zlib_compress(const uint8_t *data, size_t data_size, int level, size_t *compressed_size)
Compresses a buffer of bytes with zlib.
Definition decode.c:215
uint8_t * tmj_zlib_decompress(const uint8_t *data, size_t data_size, size_t *decompressed_size)
Decompresses a zlib/gzip-compressed buffer of bytes.
Definition decode.c:62
void logmsg(tmj_log_priority priority, char *msg,...)
Processes log messages and passes them to the active logging callback, if there is one.
Definition log.c:23
@ TMJ_LOG_ERR
Definition tmj.h:506
@ TMJ_LOG_DEBUG
Definition tmj.h:503