2 * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 #include "internal/json_enc.h"
11 #include "internal/nelem.h"
19 static int wbuf_flush(struct json_write_buf *wbuf);
21 static int wbuf_init(struct json_write_buf *wbuf, BIO *bio, size_t alloc)
23 wbuf->buf = OPENSSL_malloc(alloc);
24 if (wbuf->buf == NULL)
33 static void wbuf_cleanup(struct json_write_buf *wbuf)
35 OPENSSL_free(wbuf->buf);
40 static void wbuf_set_bio(struct json_write_buf *wbuf, BIO *bio)
45 /* Empty write buffer. */
46 static ossl_inline void wbuf_clean(struct json_write_buf *wbuf)
51 /* Available data remaining in buffer. */
52 static ossl_inline size_t wbuf_avail(struct json_write_buf *wbuf)
54 return wbuf->alloc - wbuf->cur;
57 /* Add character to write buffer, returning 0 on flush failure. */
58 static ossl_inline int wbuf_write_char(struct json_write_buf *wbuf, char c)
60 if (wbuf_avail(wbuf) == 0) {
61 if (!wbuf_flush(wbuf))
65 wbuf->buf[wbuf->cur++] = c;
70 * Write zero-terminated string to write buffer, returning 0 on flush failure.
72 static int wbuf_write_str(struct json_write_buf *wbuf, const char *s)
76 while ((c = *s++) != 0)
77 if (!wbuf_write_char(wbuf, c))
83 /* Flush write buffer, returning 0 on I/O failure. */
84 static int wbuf_flush(struct json_write_buf *wbuf)
86 size_t written = 0, total_written = 0;
88 while (total_written < wbuf->cur) {
89 if (!BIO_write_ex(wbuf->bio,
90 wbuf->buf + total_written,
91 wbuf->cur - total_written,
94 wbuf->buf + total_written,
95 wbuf->cur - total_written);
100 total_written += written;
108 * OSSL_JSON_ENC: Stack Management
109 * ===============================
112 static int json_ensure_stack_size(OSSL_JSON_ENC *json, size_t num_bytes)
114 unsigned char *stack;
116 if (json->stack_bytes >= num_bytes)
119 if (num_bytes <= OSSL_NELEM(json->stack_small)) {
120 stack = json->stack_small;
122 if (json->stack == json->stack_small)
125 stack = OPENSSL_realloc(json->stack, num_bytes);
131 json->stack_bytes = num_bytes;
135 /* Push one bit onto the stack. Returns 0 on allocation failure. */
136 static int json_push(OSSL_JSON_ENC *json, unsigned int v)
141 if (json->stack_end_byte >= json->stack_bytes) {
143 = (json->stack_bytes == 0)
144 ? OSSL_NELEM(json->stack_small)
145 : (json->stack_bytes * 2);
147 if (!json_ensure_stack_size(json, new_size))
150 json->stack_bytes = new_size;
154 json->stack[json->stack_end_byte] |= (v << json->stack_end_bit);
156 json->stack[json->stack_end_byte] &= ~(1U << json->stack_end_bit);
158 json->stack_end_bit = (json->stack_end_bit + 1) % CHAR_BIT;
159 if (json->stack_end_bit == 0)
160 ++json->stack_end_byte;
166 * Pop a bit from the stack. Returns 0 if stack is empty. Use json_peek() to get
167 * the value before calling this.
169 static int json_pop(OSSL_JSON_ENC *json)
171 if (json->stack_end_byte == 0 && json->stack_end_bit == 0)
174 if (json->stack_end_bit == 0) {
175 --json->stack_end_byte;
176 json->stack_end_bit = CHAR_BIT - 1;
178 --json->stack_end_bit;
185 * Returns the bit on the top of the stack, or -1 if the stack is empty.
187 static int json_peek(OSSL_JSON_ENC *json)
191 obyte = json->stack_end_byte;
192 obit = json->stack_end_bit;
203 return (json->stack[obyte] & (1U << obit)) != 0;
207 * OSSL_JSON_ENC: Initialisation
208 * =============================
217 static ossl_inline int in_ijson(const OSSL_JSON_ENC *json)
219 return (json->flags & OSSL_JSON_FLAG_IJSON) != 0;
222 static ossl_inline int in_seq(const OSSL_JSON_ENC *json)
224 return (json->flags & OSSL_JSON_FLAG_SEQ) != 0;
227 static ossl_inline int in_pretty(const OSSL_JSON_ENC *json)
229 return (json->flags & OSSL_JSON_FLAG_PRETTY) != 0;
232 int ossl_json_init(OSSL_JSON_ENC *json, BIO *bio, uint32_t flags)
234 memset(json, 0, sizeof(*json));
237 if (!wbuf_init(&json->wbuf, bio, 4096))
240 json->state = STATE_PRE_COMMA;
241 return ossl_json_reset(json);
244 void ossl_json_cleanup(OSSL_JSON_ENC *json)
246 wbuf_cleanup(&json->wbuf);
248 if (json->stack != json->stack_small)
249 OPENSSL_free(json->stack);
254 int ossl_json_flush_cleanup(OSSL_JSON_ENC *json)
256 int ok = ossl_json_flush(json);
258 ossl_json_cleanup(json);
262 int ossl_json_reset(OSSL_JSON_ENC *json)
264 wbuf_clean(&json->wbuf);
265 json->stack_end_byte = 0;
266 json->stack_end_bit = 0;
271 int ossl_json_flush(OSSL_JSON_ENC *json)
273 return wbuf_flush(&json->wbuf);
276 int ossl_json_set_sink(OSSL_JSON_ENC *json, BIO *bio)
278 wbuf_set_bio(&json->wbuf, bio);
282 int ossl_json_in_error(OSSL_JSON_ENC *json)
292 static void json_write_qstring(OSSL_JSON_ENC *json, const char *str);
293 static void json_indent(OSSL_JSON_ENC *json);
295 static ossl_inline int json_in_error(const OSSL_JSON_ENC *json)
300 static void json_raise_error(OSSL_JSON_ENC *json)
305 static void json_undefer(OSSL_JSON_ENC *json)
307 if (!json->defer_indent)
313 static void json_write_char(OSSL_JSON_ENC *json, char ch)
315 if (json_in_error(json))
319 if (!wbuf_write_char(&json->wbuf, ch))
320 json_raise_error(json);
323 static void json_write_str(OSSL_JSON_ENC *json, const char *s)
325 if (json_in_error(json))
329 if (!wbuf_write_str(&json->wbuf, s))
330 json_raise_error(json);
333 static void json_indent(OSSL_JSON_ENC *json)
337 json->defer_indent = 0;
339 if (!in_pretty(json))
342 json_write_char(json, '\n');
344 depth = json->stack_end_byte * 8 + json->stack_end_bit;
345 for (i = 0; i < depth * 4; ++i)
346 json_write_str(json, " ");
349 static int json_pre_item(OSSL_JSON_ENC *json)
353 if (json_in_error(json))
356 switch (json->state) {
357 case STATE_PRE_COMMA:
361 json_raise_error(json);
366 json_write_char(json, ',');
367 if (json_in_error(json))
373 if (s < 0 && in_seq(json))
374 json_write_char(json, '\x1E');
376 json->state = STATE_PRE_ITEM;
384 json_raise_error(json);
391 static void json_post_item(OSSL_JSON_ENC *json)
393 int s = json_peek(json);
395 json->state = STATE_PRE_COMMA;
397 if (s < 0 && in_seq(json))
398 json_write_char(json, '\n');
402 * Begin a composite structure (object or array).
404 * type: 0=object, 1=array.
406 static void composite_begin(OSSL_JSON_ENC *json, int type, char ch)
408 if (!json_pre_item(json)
409 || !json_push(json, type))
410 json_raise_error(json);
412 json_write_char(json, ch);
413 json->defer_indent = 1;
417 * End a composite structure (object or array).
419 * type: 0=object, 1=array. Errors on mismatch.
421 static void composite_end(OSSL_JSON_ENC *json, int type, char ch)
423 int was_defer = json->defer_indent;
425 if (json_in_error(json))
428 json->defer_indent = 0;
430 if (json_peek(json) != type)
433 if (type == 0 && json->state == STATE_PRE_ITEM) {
434 json_raise_error(json);
444 json_write_char(json, ch);
445 json_post_item(json);
448 /* Begin a new JSON object. */
449 void ossl_json_object_begin(OSSL_JSON_ENC *json)
451 composite_begin(json, 0, '{');
452 json->state = STATE_PRE_KEY;
455 /* End a JSON obejct. Must be matched with a call to ossl_json_object_begin(). */
456 void ossl_json_object_end(OSSL_JSON_ENC *json)
458 composite_end(json, 0, '}');
461 /* Begin a new JSON array. */
462 void ossl_json_array_begin(OSSL_JSON_ENC *json)
464 composite_begin(json, 1, '[');
465 json->state = STATE_PRE_ITEM;
468 /* End a JSON array. Must be matched with a call to ossl_json_array_end(). */
469 void ossl_json_array_end(OSSL_JSON_ENC *json)
471 composite_end(json, 1, ']');
475 * Encode a JSON key within an object. Pass a zero-terminated string, which can
476 * be freed immediately following the call to this function.
478 void ossl_json_key(OSSL_JSON_ENC *json, const char *key)
480 if (json_in_error(json))
483 if (json_peek(json) != 0) {
485 json_raise_error(json);
489 if (json->state == STATE_PRE_COMMA) {
490 json_write_char(json, ',');
491 json->state = STATE_PRE_KEY;
495 if (json->state != STATE_PRE_KEY) {
496 json_raise_error(json);
500 json_write_qstring(json, key);
501 if (json_in_error(json))
504 json_write_char(json, ':');
506 json_write_char(json, ' ');
508 json->state = STATE_PRE_ITEM;
511 /* Encode a JSON 'null' value. */
512 void ossl_json_null(OSSL_JSON_ENC *json)
514 if (!json_pre_item(json))
517 json_write_str(json, "null");
518 json_post_item(json);
521 void ossl_json_bool(OSSL_JSON_ENC *json, int v)
523 if (!json_pre_item(json))
526 json_write_str(json, v > 0 ? "true" : "false");
527 json_post_item(json);
530 #define POW_53 (((int64_t)1) << 53)
532 /* Encode a JSON integer from a uint64_t. */
533 static void json_u64(OSSL_JSON_ENC *json, uint64_t v, int noquote)
535 char buf[22], *p = buf + sizeof(buf) - 1;
536 int quote = !noquote && in_ijson(json) && v > (uint64_t)(POW_53 - 1);
538 if (!json_pre_item(json))
542 json_write_char(json, '"');
547 for (*p = '\0'; v > 0; v /= 10)
550 json_write_str(json, p);
553 json_write_char(json, '"');
555 json_post_item(json);
558 void ossl_json_u64(OSSL_JSON_ENC *json, uint64_t v)
560 json_u64(json, v, 0);
563 /* Encode a JSON integer from an int64_t. */
564 void ossl_json_i64(OSSL_JSON_ENC *json, int64_t value)
570 ossl_json_u64(json, (uint64_t)value);
574 if (!json_pre_item(json))
577 quote = in_ijson(json)
578 && (value > POW_53 - 1 || value < -POW_53 + 1);
581 json_write_char(json, '"');
583 json_write_char(json, '-');
585 uv = (value == INT64_MIN)
586 ? ((uint64_t)-(INT64_MIN + 1)) + 1
588 json_u64(json, uv, /*noquote=*/1);
590 if (quote && !json_in_error(json))
591 json_write_char(json, '"');
594 /* Encode a JSON number from a 64-bit floating point value. */
595 void ossl_json_f64(OSSL_JSON_ENC *json, double value)
599 if (!json_pre_item(json))
602 if (isnan(value) || isinf(value)) {
603 json_raise_error(json);
607 snprintf(buf, sizeof(buf), "%1.17g", value);
608 json_write_str(json, buf);
609 json_post_item(json);
613 * Encode a JSON UTF-8 string from a zero-terminated string. The string passed
614 * can be freed immediately following the call to this function.
616 static ossl_inline int hex_digit(int v)
618 return v >= 10 ? 'a' + (v - 10) : '0' + v;
621 static ossl_inline void
622 json_write_qstring_inner(OSSL_JSON_ENC *json, const char *str, size_t str_len,
629 if (json_in_error(json))
632 json_write_char(json, '"');
634 for (j = 0; (nul_term && *str != '\0')
635 || (!nul_term && j < str_len); ++str, ++j) {
638 case '\n': o = "\\n"; break;
639 case '\r': o = "\\r"; break;
640 case '\t': o = "\\t"; break;
641 case '\b': o = "\\b"; break;
642 case '\f': o = "\\f"; break;
643 case '"': o = "\\\""; break;
644 case '\\': o = "\\\\"; break;
646 if ((unsigned char)c >= 0x80) {
647 json_raise_error(json);
650 if ((unsigned char)c < 0x20 || (unsigned char)c >= 0x7f) {
653 for (i = 0; i < 4; ++i)
654 obuf[2 + i] = hex_digit((c >> ((3 - i) * 4)) & 0xF);
658 json_write_char(json, c);
664 json_write_str(json, o);
667 json_write_char(json, '"');
671 json_write_qstring(OSSL_JSON_ENC *json, const char *str)
673 json_write_qstring_inner(json, str, 0, 1);
677 json_write_qstring_len(OSSL_JSON_ENC *json, const char *str, size_t str_len)
679 json_write_qstring_inner(json, str, str_len, 0);
682 void ossl_json_str(OSSL_JSON_ENC *json, const char *str)
684 if (!json_pre_item(json))
687 json_write_qstring(json, str);
688 json_post_item(json);
691 void ossl_json_str_len(OSSL_JSON_ENC *json, const char *str, size_t str_len)
693 if (!json_pre_item(json))
696 json_write_qstring_len(json, str, str_len);
697 json_post_item(json);
701 * Encode binary data as a lowercase hex string. data_len is the data length in
704 void ossl_json_str_hex(OSSL_JSON_ENC *json, const void *data, size_t data_len)
706 const unsigned char *b = data, *end = b + data_len;
709 if (!json_pre_item(json))
712 json_write_char(json, '"');
714 for (; b < end; ++b) {
716 json_write_char(json, hex_digit(c >> 4));
717 json_write_char(json, hex_digit(c & 0x0F));
720 json_write_char(json, '"');
721 json_post_item(json);