/* yyjson 完成 JSON 解析与编码;本层只执行 Dever 帧与结构预算。 */ #include "wire.h" #include #include #include static int key_order(const void *left, const void *right) { yyjson_val *a = *(yyjson_val *const *)left, *b = *(yyjson_val *const *)right; size_t an = yyjson_get_len(a), bn = yyjson_get_len(b); int compare = memcmp(yyjson_get_str(a), yyjson_get_str(b), an < bn ? an : bn); return compare != 0 ? compare : (an > bn) - (an < bn); } static int bounded(yyjson_val *value, unsigned depth, size_t *remaining) { if (depth > 64 || *remaining == 0) return 0; --*remaining; if (yyjson_is_ctn(value) && depth == 64) return 0; if (yyjson_is_arr(value)) { size_t i, length; yyjson_val *item; yyjson_arr_foreach(value, i, length, item) if (!bounded(item, depth + 1, remaining)) return 0; } else if (yyjson_is_obj(value)) { size_t length = yyjson_obj_size(value); if (length > *remaining) return 0; yyjson_val **keys = length ? malloc(length * sizeof(*keys)) : NULL; if (length && keys == NULL) return 0; size_t i, count; yyjson_val *key, *item; int okay = 1; yyjson_obj_foreach(value, i, count, key, item) { keys[i] = key; if (!bounded(item, depth + 1, remaining)) { okay = 0; break; } } if (okay && length > 1) { qsort(keys, length, sizeof(*keys), key_order); for (i = 1; i < length; ++i) if (key_order(&keys[i-1], &keys[i]) == 0) { okay = 0; break; } } free(keys); return okay; } return 1; } yyjson_doc *dever_parse(const char *data, size_t size, size_t extra_values, unsigned depth) { if (size == 0 || size > DEVER_MAX_BYTES) return NULL; yyjson_doc *doc = yyjson_read(data, size, YYJSON_READ_BIGNUM_AS_RAW); if (doc == NULL) return NULL; size_t remaining = 65536 - extra_values; if (!bounded(yyjson_doc_get_root(doc), depth, &remaining)) { yyjson_doc_free(doc); return NULL; } return doc; } yyjson_doc *dever_receive(void) { unsigned char header[4]; if (fread(header, 1, 4, stdin) != 4) return NULL; size_t size = ((uint32_t)header[0] << 24) | ((uint32_t)header[1] << 16) | ((uint32_t)header[2] << 8) | header[3]; if (size == 0 || size > DEVER_MAX_BYTES) return NULL; char *data = malloc(size); if (data == NULL) return NULL; yyjson_doc *doc = fread(data, 1, size, stdin) == size ? dever_parse(data, size, 0, 0) : NULL; free(data); return doc; } static int send_bytes(char *data, size_t size) { if (data == NULL || size == 0 || size > DEVER_MAX_BYTES) { free(data); return 0; } unsigned char header[4] = {size >> 24, size >> 16, size >> 8, size}; int okay = fwrite(header, 1, 4, stdout) == 4 && fwrite(data, 1, size, stdout) == size && fflush(stdout) == 0; free(data); return okay; } int dever_send(yyjson_mut_doc *doc) { size_t size; char *data = yyjson_mut_write(doc, 0, &size); return send_bytes(data, size); } int dever_send_value(yyjson_val *value) { size_t size; char *data = yyjson_val_write(value, 0, &size); return send_bytes(data, size); }