2 * JSON streaming support
4 * Copyright IBM, Corp. 2009
9 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
10 * See the COPYING.LIB file in the top-level directory.
14 #include "qemu/osdep.h"
15 #include "qapi/error.h"
16 #include "json-parser-int.h"
18 #define MAX_TOKEN_SIZE (64ULL << 20)
19 #define MAX_TOKEN_COUNT (2ULL << 20)
20 #define MAX_NESTING (1 << 10)
22 static void json_message_free_tokens(JSONMessageParser *parser)
26 while ((token = g_queue_pop_head(&parser->tokens))) {
31 void json_message_process_token(JSONLexer *lexer, GString *input,
32 JSONTokenType type, int x, int y)
34 JSONMessageParser *parser = container_of(lexer, JSONMessageParser, lexer);
41 parser->brace_count++;
44 parser->brace_count--;
47 parser->bracket_count++;
50 parser->bracket_count--;
53 error_setg(&err, "JSON parse error, stray '%s'", input->str);
55 case JSON_END_OF_INPUT:
56 if (g_queue_is_empty(&parser->tokens)) {
59 json = json_parser_parse(&parser->tokens, parser->ap, &err);
66 * Security consideration, we limit total memory allocated per object
67 * and the maximum recursion depth that a message can force.
69 if (parser->token_size + input->len + 1 > MAX_TOKEN_SIZE) {
70 error_setg(&err, "JSON token size limit exceeded");
73 if (g_queue_get_length(&parser->tokens) + 1 > MAX_TOKEN_COUNT) {
74 error_setg(&err, "JSON token count limit exceeded");
77 if (parser->bracket_count + parser->brace_count > MAX_NESTING) {
78 error_setg(&err, "JSON nesting depth limit exceeded");
82 token = json_token(type, x, y, input);
83 parser->token_size += input->len;
85 g_queue_push_tail(&parser->tokens, token);
87 if ((parser->brace_count > 0 || parser->bracket_count > 0)
88 && parser->bracket_count >= 0 && parser->bracket_count >= 0) {
92 json = json_parser_parse(&parser->tokens, parser->ap, &err);
95 parser->brace_count = 0;
96 parser->bracket_count = 0;
97 json_message_free_tokens(parser);
98 parser->token_size = 0;
99 parser->emit(parser->opaque, json, err);
102 void json_message_parser_init(JSONMessageParser *parser,
103 void (*emit)(void *opaque, QObject *json,
105 void *opaque, va_list *ap)
108 parser->opaque = opaque;
110 parser->brace_count = 0;
111 parser->bracket_count = 0;
112 g_queue_init(&parser->tokens);
113 parser->token_size = 0;
115 json_lexer_init(&parser->lexer, !!ap);
118 void json_message_parser_feed(JSONMessageParser *parser,
119 const char *buffer, size_t size)
121 json_lexer_feed(&parser->lexer, buffer, size);
124 void json_message_parser_flush(JSONMessageParser *parser)
126 json_lexer_flush(&parser->lexer);
127 assert(g_queue_is_empty(&parser->tokens));
130 void json_message_parser_destroy(JSONMessageParser *parser)
132 json_lexer_destroy(&parser->lexer);
133 json_message_free_tokens(parser);