2 * JSON streaming support
4 * Copyright IBM, Corp. 2009
7 * Anthony Liguori <aliguori@us.ibm.com>
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-common.h"
15 #include "qapi/qmp/json-lexer.h"
16 #include "qapi/qmp/json-streamer.h"
18 #define MAX_TOKEN_SIZE (64ULL << 20)
19 #define MAX_NESTING (1ULL << 10)
21 static void json_message_free_tokens(JSONMessageParser
*parser
)
24 g_queue_free(parser
->tokens
);
25 parser
->tokens
= NULL
;
29 static void json_message_process_token(JSONLexer
*lexer
, GString
*input
,
30 JSONTokenType type
, int x
, int y
)
32 JSONMessageParser
*parser
= container_of(lexer
, JSONMessageParser
, lexer
);
37 parser
->brace_count
++;
40 parser
->brace_count
--;
43 parser
->bracket_count
++;
46 parser
->bracket_count
--;
52 token
= g_malloc(sizeof(JSONToken
) + input
->len
+ 1);
54 memcpy(token
->str
, input
->str
, input
->len
);
55 token
->str
[input
->len
] = 0;
59 parser
->token_size
+= input
->len
;
61 g_queue_push_tail(parser
->tokens
, token
);
63 if (type
== JSON_ERROR
) {
65 } else if (parser
->brace_count
< 0 ||
66 parser
->bracket_count
< 0 ||
67 (parser
->brace_count
== 0 &&
68 parser
->bracket_count
== 0)) {
70 } else if (parser
->token_size
> MAX_TOKEN_SIZE
||
71 parser
->bracket_count
+ parser
->brace_count
> MAX_NESTING
) {
72 /* Security consideration, we limit total memory allocated per object
73 * and the maximum recursion depth that a message can force.
82 * Clear out token list and tell the parser to emit an error
83 * indication by passing it a NULL list
85 json_message_free_tokens(parser
);
87 /* send current list of tokens to parser and reset tokenizer */
88 parser
->brace_count
= 0;
89 parser
->bracket_count
= 0;
90 /* parser->emit takes ownership of parser->tokens. */
91 parser
->emit(parser
, parser
->tokens
);
92 parser
->tokens
= g_queue_new();
93 parser
->token_size
= 0;
96 void json_message_parser_init(JSONMessageParser
*parser
,
97 void (*func
)(JSONMessageParser
*, GQueue
*))
100 parser
->brace_count
= 0;
101 parser
->bracket_count
= 0;
102 parser
->tokens
= g_queue_new();
103 parser
->token_size
= 0;
105 json_lexer_init(&parser
->lexer
, json_message_process_token
);
108 int json_message_parser_feed(JSONMessageParser
*parser
,
109 const char *buffer
, size_t size
)
111 return json_lexer_feed(&parser
->lexer
, buffer
, size
);
114 int json_message_parser_flush(JSONMessageParser
*parser
)
116 return json_lexer_flush(&parser
->lexer
);
119 void json_message_parser_destroy(JSONMessageParser
*parser
)
121 json_lexer_destroy(&parser
->lexer
);
122 json_message_free_tokens(parser
);