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/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 (1ULL << 10)
24 static void json_message_free_token(void *token, void *opaque)
29 static void json_message_free_tokens(JSONMessageParser *parser)
32 g_queue_foreach(parser->tokens, json_message_free_token, NULL);
33 g_queue_free(parser->tokens);
34 parser->tokens = NULL;
38 void json_message_process_token(JSONLexer *lexer, GString *input,
39 JSONTokenType type, int x, int y)
41 JSONMessageParser *parser = container_of(lexer, JSONMessageParser, lexer);
48 parser->brace_count++;
51 parser->brace_count--;
54 parser->bracket_count++;
57 parser->bracket_count--;
63 token = g_malloc(sizeof(JSONToken) + input->len + 1);
65 memcpy(token->str, input->str, input->len);
66 token->str[input->len] = 0;
70 parser->token_size += input->len;
72 g_queue_push_tail(parser->tokens, token);
74 if (type == JSON_ERROR) {
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;
87 if (parser->token_size > MAX_TOKEN_SIZE ||
88 g_queue_get_length(parser->tokens) > MAX_TOKEN_COUNT ||
89 parser->bracket_count + parser->brace_count > MAX_NESTING) {
90 /* Security consideration, we limit total memory allocated per object
91 * and the maximum recursion depth that a message can force.
99 parser->brace_count = 0;
100 parser->bracket_count = 0;
101 json_message_free_tokens(parser);
102 parser->tokens = g_queue_new();
103 parser->token_size = 0;
104 parser->emit(parser->opaque, json, err);
107 void json_message_parser_init(JSONMessageParser *parser,
108 void (*emit)(void *opaque, QObject *json,
110 void *opaque, va_list *ap)
113 parser->opaque = opaque;
115 parser->brace_count = 0;
116 parser->bracket_count = 0;
117 parser->tokens = g_queue_new();
118 parser->token_size = 0;
120 json_lexer_init(&parser->lexer);
123 void json_message_parser_feed(JSONMessageParser *parser,
124 const char *buffer, size_t size)
126 json_lexer_feed(&parser->lexer, buffer, size);
129 void json_message_parser_flush(JSONMessageParser *parser)
131 json_lexer_flush(&parser->lexer);
134 void json_message_parser_destroy(JSONMessageParser *parser)
136 json_lexer_destroy(&parser->lexer);
137 json_message_free_tokens(parser);