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 "qapi/qmp/json-lexer.h"
17 #include "qapi/qmp/json-parser.h"
18 #include "qapi/qmp/json-streamer.h"
20 #define MAX_TOKEN_SIZE (64ULL << 20)
21 #define MAX_TOKEN_COUNT (2ULL << 20)
22 #define MAX_NESTING (1 << 10)
24 static void json_message_free_tokens(JSONMessageParser *parser)
28 while ((token = g_queue_pop_head(&parser->tokens))) {
33 void json_message_process_token(JSONLexer *lexer, GString *input,
34 JSONTokenType type, int x, int y)
36 JSONMessageParser *parser = container_of(lexer, JSONMessageParser, lexer);
43 parser->brace_count++;
46 parser->brace_count--;
49 parser->bracket_count++;
52 parser->bracket_count--;
55 error_setg(&err, "JSON parse error, stray '%s'", input->str);
57 case JSON_END_OF_INPUT:
58 if (g_queue_is_empty(&parser->tokens)) {
61 json = json_parser_parse(&parser->tokens, parser->ap, &err);
68 * Security consideration, we limit total memory allocated per object
69 * and the maximum recursion depth that a message can force.
71 if (parser->token_size + input->len + 1 > MAX_TOKEN_SIZE) {
72 error_setg(&err, "JSON token size limit exceeded");
75 if (g_queue_get_length(&parser->tokens) + 1 > MAX_TOKEN_COUNT) {
76 error_setg(&err, "JSON token count limit exceeded");
79 if (parser->bracket_count + parser->brace_count > MAX_NESTING) {
80 error_setg(&err, "JSON nesting depth limit exceeded");
84 token = json_token(type, x, y, input);
85 parser->token_size += input->len;
87 g_queue_push_tail(&parser->tokens, token);
89 if ((parser->brace_count > 0 || parser->bracket_count > 0)
90 && parser->bracket_count >= 0 && parser->bracket_count >= 0) {
94 json = json_parser_parse(&parser->tokens, parser->ap, &err);
97 parser->brace_count = 0;
98 parser->bracket_count = 0;
99 json_message_free_tokens(parser);
100 parser->token_size = 0;
101 parser->emit(parser->opaque, json, err);
104 void json_message_parser_init(JSONMessageParser *parser,
105 void (*emit)(void *opaque, QObject *json,
107 void *opaque, va_list *ap)
110 parser->opaque = opaque;
112 parser->brace_count = 0;
113 parser->bracket_count = 0;
114 g_queue_init(&parser->tokens);
115 parser->token_size = 0;
117 json_lexer_init(&parser->lexer, !!ap);
120 void json_message_parser_feed(JSONMessageParser *parser,
121 const char *buffer, size_t size)
123 json_lexer_feed(&parser->lexer, buffer, size);
126 void json_message_parser_flush(JSONMessageParser *parser)
128 json_lexer_flush(&parser->lexer);
129 assert(g_queue_is_empty(&parser->tokens));
132 void json_message_parser_destroy(JSONMessageParser *parser)
134 json_lexer_destroy(&parser->lexer);
135 json_message_free_tokens(parser);