1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
|
/*
* Copyright (C) 2024 Thibaut VARÈNE <hacks@slashdirt.org>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/**
* # Zlib bindings
*
* The `zlib` module provides single-call-oriented functions for interacting with zlib data.
*
* @module zlib
*/
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include <zlib.h>
#include "ucode/module.h"
#include "ucode/platform.h"
// https://zlib.net/zlib_how.html
/*
* CHUNK is simply the buffer size for feeding data to and pulling data from
* the zlib routines. Larger buffer sizes would be more efficient, especially
* for inflate(). If the memory is available, buffers sizes on the order of
* 128K or 256K bytes should be used.
*/
#define CHUNK 16384
/* zlib init error message */
static const char * ziniterr(int ret)
{
const char * msg;
switch (ret) {
case Z_ERRNO:
msg = strerror(errno);
break;
case Z_STREAM_ERROR: // can only happen for deflateInit2() by construction
msg = "invalid compression level";
break;
case Z_MEM_ERROR:
msg = "out of memory";
break;
case Z_VERSION_ERROR:
msg = "zlib version mismatch!";
break;
default:
msg = "unknown error";
break;
}
return msg;
}
static uc_stringbuf_t *
uc_zlib_def_object(uc_vm_t *vm, uc_value_t *obj, z_stream *strm)
{
int ret;
bool eof = false;
uc_value_t *rfn, *rbuf;
uc_stringbuf_t *buf = NULL;
rfn = ucv_property_get(obj, "read");
if (!ucv_is_callable(rfn)) {
uc_vm_raise_exception(vm, EXCEPTION_TYPE,
"Input object does not implement read() method");
return NULL;
}
buf = ucv_stringbuf_new();
do {
rbuf = NULL;
uc_vm_stack_push(vm, ucv_get(obj));
uc_vm_stack_push(vm, ucv_get(rfn));
uc_vm_stack_push(vm, ucv_int64_new(CHUNK));
if (uc_vm_call(vm, true, 1) != EXCEPTION_NONE)
goto fail;
rbuf = uc_vm_stack_pop(vm); // read output chunk
/* we only accept strings */
if (rbuf != NULL && ucv_type(rbuf) != UC_STRING) {
uc_vm_raise_exception(vm, EXCEPTION_TYPE,
"Input object read() method returned non-string value");
goto fail;
}
/* check EOF */
eof = (rbuf == NULL || ucv_string_length(rbuf) == 0);
strm->next_in = (unsigned char *)ucv_string_get(rbuf);
strm->avail_in = ucv_string_length(rbuf);
/* run deflate() on input until output buffer not full */
do {
// enlarge buf by CHUNK amount as needed
printbuf_memset(buf, printbuf_length(buf) + CHUNK - 1, 0, 1);
buf->bpos -= CHUNK;
strm->avail_out = CHUNK;
strm->next_out = (unsigned char *)(buf->buf + buf->bpos);;
ret = deflate(strm, eof ? Z_FINISH : Z_NO_FLUSH); // no bad return value here
assert(ret != Z_STREAM_ERROR); // state never clobbered (would be mem corruption)
(void)ret; // XXX make annoying compiler that ignores assert() happy
// update bpos past data written by deflate()
buf->bpos += CHUNK - strm->avail_out;
} while (strm->avail_out == 0);
assert(strm->avail_in == 0); // all input will be used
ucv_put(rbuf); // release rbuf
} while (!eof); // finish compression if all of source has been read in
assert(ret == Z_STREAM_END); // stream will be complete
return buf;
fail:
ucv_put(rbuf);
printbuf_free(buf);
return NULL;
}
static uc_stringbuf_t *
uc_zlib_def_string(uc_vm_t *vm, uc_value_t *str, z_stream *strm)
{
int ret;
uc_stringbuf_t *buf = NULL;
buf = ucv_stringbuf_new();
strm->next_in = (unsigned char *)ucv_string_get(str);
strm->avail_in = ucv_string_length(str);
do {
printbuf_memset(buf, printbuf_length(buf) + CHUNK - 1, 0, 1);
buf->bpos -= CHUNK;
strm->avail_out = CHUNK;
strm->next_out = (unsigned char *)(buf->buf + buf->bpos);
ret = deflate(strm, Z_FINISH);
assert(ret != Z_STREAM_ERROR);
buf->bpos += CHUNK - strm->avail_out;
} while (ret != Z_STREAM_END);
assert(strm->avail_in == 0);
return buf;
}
/**
* Compresses data in Zlib or gzip format.
*
* If the input argument is a plain string, it is directly compressed.
*
* If an array, object or resource value is given, this function will attempt to
* invoke a `read()` method on it to read chunks of input text to incrementally
* compress. Reading will stop if the object's `read()` method returns
* either `null` or an empty string.
*
* Throws an exception on errors.
*
* Returns the compressed data.
*
* @function module:zlib#deflate
*
* @param {string} str_or_resource
* The string or resource object to be parsed as JSON.
*
* @param {?boolean} [gzip=false]
* Add a gzip header if true (creates a gzip-compliant output, otherwise defaults to Zlib)
*
* @param {?number} [level=Z_DEFAULT_COMPRESSION]
* The compression level (0-9).
*
* @returns {?string}
*
* @example
* // deflate content using default compression
* const deflated = deflate(content);
*
* // deflate content using fastest compression
* const deflated = deflate(content, Z_BEST_SPEED);
*/
static uc_value_t *
uc_zlib_deflate(uc_vm_t *vm, size_t nargs)
{
uc_value_t *rv = NULL;
uc_value_t *src = uc_fn_arg(0);
uc_value_t *gzip = uc_fn_arg(1);
uc_value_t *level = uc_fn_arg(2);
uc_stringbuf_t *buf = NULL;
int ret, lvl = Z_DEFAULT_COMPRESSION;
bool gz = false;
z_stream strm = {
.zalloc = Z_NULL,
.zfree = Z_NULL,
.opaque = Z_NULL,
};
if (gzip) {
if (ucv_type(gzip) != UC_BOOLEAN) {
uc_vm_raise_exception(vm, EXCEPTION_TYPE, "Passed gzip flag is not a boolean");
goto out;
}
gz = (int)ucv_boolean_get(gzip);
}
if (level) {
if (ucv_type(level) != UC_INTEGER) {
uc_vm_raise_exception(vm, EXCEPTION_TYPE, "Passed level is not a number");
goto out;
}
lvl = (int)ucv_int64_get(level);
}
ret = deflateInit2(&strm, lvl,
Z_DEFLATED, // only allowed method
gz ? 15+16 : 15, // 15 Zlib default, +16 for gzip
8, // default value
Z_DEFAULT_STRATEGY); // default value
if (ret != Z_OK) {
uc_vm_raise_exception(vm, EXCEPTION_RUNTIME, "Zlib error: %s", ziniterr(ret));
goto out;
}
switch (ucv_type(src)) {
case UC_STRING:
buf = uc_zlib_def_string(vm, src, &strm);
break;
case UC_RESOURCE:
case UC_OBJECT:
case UC_ARRAY:
buf = uc_zlib_def_object(vm, src, &strm);
break;
default:
uc_vm_raise_exception(vm, EXCEPTION_TYPE,
"Passed value is neither a string nor an object");
goto out;
}
if (!buf) {
if (vm->exception.type == EXCEPTION_NONE) // do not clobber previous exception
uc_vm_raise_exception(vm, EXCEPTION_RUNTIME, "Zlib error: %s", strm.msg);
goto out;
}
rv = ucv_stringbuf_finish(buf);
out:
(void)deflateEnd(&strm);
return rv;
}
static uc_stringbuf_t *
uc_zlib_inf_object(uc_vm_t *vm, uc_value_t *obj, z_stream *strm)
{
int ret = Z_STREAM_ERROR; // error out if EOF on first loop
bool eof = false;
uc_value_t *rfn, *rbuf;
uc_stringbuf_t *buf = NULL;
rfn = ucv_property_get(obj, "read");
if (!ucv_is_callable(rfn)) {
uc_vm_raise_exception(vm, EXCEPTION_TYPE,
"Input object does not implement read() method");
return NULL;
}
buf = ucv_stringbuf_new();
do {
rbuf = NULL;
uc_vm_stack_push(vm, ucv_get(obj));
uc_vm_stack_push(vm, ucv_get(rfn));
uc_vm_stack_push(vm, ucv_int64_new(CHUNK));
if (uc_vm_call(vm, true, 1) != EXCEPTION_NONE)
goto fail;
rbuf = uc_vm_stack_pop(vm); // read output chunk
/* we only accept strings */
if (rbuf != NULL && ucv_type(rbuf) != UC_STRING) {
uc_vm_raise_exception(vm, EXCEPTION_TYPE,
"Input object read() method returned non-string value");
goto fail;
}
/* check EOF */
eof = (rbuf == NULL || ucv_string_length(rbuf) == 0);
if (eof)
break;
strm->next_in = (unsigned char *)ucv_string_get(rbuf);
strm->avail_in = ucv_string_length(rbuf);
/* run deflate() on input until output buffer not full */
do {
// enlarge buf by CHUNK amount as needed
printbuf_memset(buf, printbuf_length(buf) + CHUNK - 1, 0, 1);
buf->bpos -= CHUNK;
strm->avail_out = CHUNK;
strm->next_out = (unsigned char *)(buf->buf + buf->bpos);;
ret = inflate(strm, Z_NO_FLUSH);
assert(ret != Z_STREAM_ERROR); // state never clobbered (would be mem corruption)
switch (ret) {
case Z_NEED_DICT:
case Z_DATA_ERROR:
case Z_MEM_ERROR:
goto fail;
}
// update bpos past data written by deflate()
buf->bpos += CHUNK - strm->avail_out;
} while (strm->avail_out == 0);
ucv_put(rbuf); // release rbuf
} while (ret != Z_STREAM_END); // done when inflate() says it's done
if (ret != Z_STREAM_END) { // data error
printbuf_free(buf);
buf = NULL;
}
return buf;
fail:
ucv_put(rbuf);
printbuf_free(buf);
return NULL;
}
static uc_stringbuf_t *
uc_zlib_inf_string(uc_vm_t *vm, uc_value_t *str, z_stream *strm)
{
int ret;
uc_stringbuf_t *buf = NULL;
buf = ucv_stringbuf_new();
strm->next_in = (unsigned char *)ucv_string_get(str);
strm->avail_in = ucv_string_length(str);
do {
printbuf_memset(buf, printbuf_length(buf) + CHUNK - 1, 0, 1);
buf->bpos -= CHUNK;
strm->avail_out = CHUNK;
strm->next_out = (unsigned char *)(buf->buf + buf->bpos);
ret = inflate(strm, Z_FINISH);
assert(ret != Z_STREAM_ERROR);
switch (ret) {
case Z_NEED_DICT:
case Z_DATA_ERROR:
case Z_MEM_ERROR:
printbuf_free(buf);
return NULL;
}
buf->bpos += CHUNK - strm->avail_out;
} while (ret != Z_STREAM_END);
assert(strm->avail_in == 0);
return buf;
}
/**
* Decompresses data in Zlib or gzip format.
*
* If the input argument is a plain string, it is directly decompressed.
*
* If an array, object or resource value is given, this function will attempt to
* invoke a `read()` method on it to read chunks of input text to incrementally
* decompress. Reading will stop if the object's `read()` method returns
* either `null` or an empty string.
*
* Throws an exception on errors.
*
* Returns the decompressed data.
*
* @function module:zlib#inflate
*
* @param {string} str_or_resource
* The string or resource object to be parsed as JSON.
*
* @returns {?string}
*/
static uc_value_t *
uc_zlib_inflate(uc_vm_t *vm, size_t nargs)
{
uc_value_t *rv = NULL;
uc_value_t *src = uc_fn_arg(0);
uc_stringbuf_t *buf = NULL;
int ret;
z_stream strm = {
.zalloc = Z_NULL,
.zfree = Z_NULL,
.opaque = Z_NULL,
.avail_in = 0, // must be initialized before call to inflateInit
.next_in = Z_NULL, // must be initialized before call to inflateInit
};
/* tell inflateInit2 to perform either zlib or gzip decompression: 15+32 */
ret = inflateInit2(&strm, 15+32);
if (ret != Z_OK) {
uc_vm_raise_exception(vm, EXCEPTION_RUNTIME, "Zlib error: %s", ziniterr(ret));
goto out;
}
switch (ucv_type(src)) {
case UC_STRING:
buf = uc_zlib_inf_string(vm, src, &strm);
break;
case UC_RESOURCE:
case UC_OBJECT:
case UC_ARRAY:
buf = uc_zlib_inf_object(vm, src, &strm);
break;
default:
uc_vm_raise_exception(vm, EXCEPTION_TYPE,
"Passed value is neither a string nor an object");
goto out;
}
if (!buf) {
if (vm->exception.type == EXCEPTION_NONE) // do not clobber previous exception
uc_vm_raise_exception(vm, EXCEPTION_RUNTIME, "Zlib error: %s", strm.msg);
goto out;
}
rv = ucv_stringbuf_finish(buf);
out:
(void)inflateEnd(&strm);
return rv;
}
static const uc_function_list_t global_fns[] = {
{ "deflate", uc_zlib_deflate },
{ "inflate", uc_zlib_inflate },
};
void uc_module_init(uc_vm_t *vm, uc_value_t *scope)
{
uc_function_list_register(scope, global_fns);
#define ADD_CONST(x) ucv_object_add(scope, #x, ucv_int64_new(x))
/**
* @typedef
* @name Compression levels
* @description Constants representing predefined compression levels.
* @property {number} Z_NO_COMPRESSION.
* @property {number} Z_BEST_SPEED.
* @property {number} Z_BEST_COMPRESSION.
* @property {number} Z_DEFAULT_COMPRESSION - default compromise between speed and compression (currently equivalent to level 6).
*/
ADD_CONST(Z_NO_COMPRESSION);
ADD_CONST(Z_BEST_SPEED);
ADD_CONST(Z_BEST_COMPRESSION);
ADD_CONST(Z_DEFAULT_COMPRESSION);
}
|