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.
17 #include "qemu-common.h"
18 #include "json-lexer.h"
19 #include "json-streamer.h"
21 #define MAX_TOKEN_SIZE (64ULL << 20)
22 #define MAX_NESTING (1ULL << 10)
24 static void json_message_process_token(JSONLexer
*lexer
, QString
*token
, JSONTokenType type
, int x
, int y
)
26 JSONMessageParser
*parser
= container_of(lexer
, JSONMessageParser
, lexer
);
29 if (type
== JSON_OPERATOR
) {
30 switch (qstring_get_str(token
)[0]) {
32 parser
->brace_count
++;
35 parser
->brace_count
--;
38 parser
->bracket_count
++;
41 parser
->bracket_count
--;
49 qdict_put(dict
, "type", qint_from_int(type
));
51 qdict_put(dict
, "token", token
);
52 qdict_put(dict
, "x", qint_from_int(x
));
53 qdict_put(dict
, "y", qint_from_int(y
));
55 parser
->token_size
+= token
->length
;
57 qlist_append(parser
->tokens
, dict
);
59 if (parser
->brace_count
< 0 ||
60 parser
->bracket_count
< 0 ||
61 (parser
->brace_count
== 0 &&
62 parser
->bracket_count
== 0)) {
63 parser
->brace_count
= 0;
64 parser
->bracket_count
= 0;
65 parser
->emit(parser
, parser
->tokens
);
66 QDECREF(parser
->tokens
);
67 parser
->tokens
= qlist_new();
68 } else if (parser
->token_size
> MAX_TOKEN_SIZE
||
69 parser
->bracket_count
> MAX_NESTING
||
70 parser
->brace_count
> MAX_NESTING
) {
71 /* Security consideration, we limit total memory allocated per object
72 * and the maximum recursion depth that a message can force.
74 parser
->brace_count
= 0;
75 parser
->bracket_count
= 0;
76 parser
->emit(parser
, parser
->tokens
);
77 QDECREF(parser
->tokens
);
78 parser
->tokens
= qlist_new();
82 void json_message_parser_init(JSONMessageParser
*parser
,
83 void (*func
)(JSONMessageParser
*, QList
*))
86 parser
->brace_count
= 0;
87 parser
->bracket_count
= 0;
88 parser
->tokens
= qlist_new();
89 parser
->token_size
= 0;
91 json_lexer_init(&parser
->lexer
, json_message_process_token
);
94 int json_message_parser_feed(JSONMessageParser
*parser
,
95 const char *buffer
, size_t size
)
97 return json_lexer_feed(&parser
->lexer
, buffer
, size
);
100 int json_message_parser_flush(JSONMessageParser
*parser
)
102 return json_lexer_flush(&parser
->lexer
);
105 void json_message_parser_destroy(JSONMessageParser
*parser
)
107 json_lexer_destroy(&parser
->lexer
);
108 QDECREF(parser
->tokens
);