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 "qemu-common.h"
16 #include "qapi/error.h"
17 #include "qapi/qmp/json-lexer.h"
18 #include "qapi/qmp/json-parser.h"
19 #include "qapi/qmp/json-streamer.h"
21 #define MAX_TOKEN_SIZE (64ULL << 20)
22 #define MAX_TOKEN_COUNT (2ULL << 20)
23 #define MAX_NESTING (1ULL << 10)
25 static void json_message_free_token(void *token, void *opaque)
30 static void json_message_free_tokens(JSONMessageParser *parser)
33 g_queue_foreach(parser->tokens, json_message_free_token, NULL);
34 g_queue_free(parser->tokens);
35 parser->tokens = NULL;
39 void json_message_process_token(JSONLexer *lexer, GString *input,
40 JSONTokenType type, int x, int y)
42 JSONMessageParser *parser = container_of(lexer, JSONMessageParser, lexer);
49 parser->brace_count++;
52 parser->brace_count--;
55 parser->bracket_count++;
58 parser->bracket_count--;
61 error_setg(&err, "JSON parse error, stray '%s'", input->str);
67 token = g_malloc(sizeof(JSONToken) + input->len + 1);
69 memcpy(token->str, input->str, input->len);
70 token->str[input->len] = 0;
74 parser->token_size += input->len;
76 g_queue_push_tail(parser->tokens, token);
78 if (parser->brace_count < 0 ||
79 parser->bracket_count < 0 ||
80 (parser->brace_count == 0 &&
81 parser->bracket_count == 0)) {
82 json = json_parser_parse(parser->tokens, parser->ap, &err);
83 parser->tokens = NULL;
88 * Security consideration, we limit total memory allocated per object
89 * and the maximum recursion depth that a message can force.
91 if (parser->token_size > MAX_TOKEN_SIZE) {
92 error_setg(&err, "JSON token size limit exceeded");
95 if (g_queue_get_length(parser->tokens) > MAX_TOKEN_COUNT) {
96 error_setg(&err, "JSON token count limit exceeded");
99 if (parser->bracket_count + parser->brace_count > MAX_NESTING) {
100 error_setg(&err, "JSON nesting depth limit exceeded");
107 parser->brace_count = 0;
108 parser->bracket_count = 0;
109 json_message_free_tokens(parser);
110 parser->tokens = g_queue_new();
111 parser->token_size = 0;
112 parser->emit(parser->opaque, json, err);
115 void json_message_parser_init(JSONMessageParser *parser,
116 void (*emit)(void *opaque, QObject *json,
118 void *opaque, va_list *ap)
121 parser->opaque = opaque;
123 parser->brace_count = 0;
124 parser->bracket_count = 0;
125 parser->tokens = g_queue_new();
126 parser->token_size = 0;
128 json_lexer_init(&parser->lexer, !!ap);
131 void json_message_parser_feed(JSONMessageParser *parser,
132 const char *buffer, size_t size)
134 json_lexer_feed(&parser->lexer, buffer, size);
137 void json_message_parser_flush(JSONMessageParser *parser)
139 json_lexer_flush(&parser->lexer);
142 void json_message_parser_destroy(JSONMessageParser *parser)
144 json_lexer_destroy(&parser->lexer);
145 json_message_free_tokens(parser);