2
0

keyval.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. /*
  2. * Parsing KEY=VALUE,... strings
  3. *
  4. * Copyright (C) 2017 Red Hat Inc.
  5. *
  6. * Authors:
  7. * Markus Armbruster <armbru@redhat.com>,
  8. *
  9. * This work is licensed under the terms of the GNU GPL, version 2 or later.
  10. * See the COPYING file in the top-level directory.
  11. */
  12. /*
  13. * KEY=VALUE,... syntax:
  14. *
  15. * key-vals = [ key-val { ',' key-val } [ ',' ] ]
  16. * key-val = key '=' val
  17. * key = key-fragment { '.' key-fragment }
  18. * key-fragment = / [^=,.]* /
  19. * val = { / [^,]* / | ',,' }
  20. *
  21. * Semantics defined by reduction to JSON:
  22. *
  23. * key-vals specifies a JSON object, i.e. a tree whose root is an
  24. * object, inner nodes other than the root are objects or arrays,
  25. * and leaves are strings.
  26. *
  27. * Each key-val = key-fragment '.' ... '=' val specifies a path from
  28. * root to a leaf (left of '='), and the leaf's value (right of
  29. * '=').
  30. *
  31. * A path from the root is defined recursively:
  32. * L '.' key-fragment is a child of the node denoted by path L
  33. * key-fragment is a child of the tree root
  34. * If key-fragment is numeric, the parent is an array and the child
  35. * is its key-fragment-th member, counting from zero.
  36. * Else, the parent is an object, and the child is its member named
  37. * key-fragment.
  38. *
  39. * This constrains inner nodes to be either array or object. The
  40. * constraints must be satisfiable. Counter-example: a.b=1,a=2 is
  41. * not, because root.a must be an object to satisfy a.b=1 and a
  42. * string to satisfy a=2.
  43. *
  44. * Array subscripts can occur in any order, but the set of
  45. * subscripts must not have gaps. For instance, a.1=v is not okay,
  46. * because root.a[0] is missing.
  47. *
  48. * If multiple key-val denote the same leaf, the last one determines
  49. * the value.
  50. *
  51. * Key-fragments must be valid QAPI names or consist only of decimal
  52. * digits.
  53. *
  54. * The length of any key-fragment must be between 1 and 127.
  55. *
  56. * Design flaw: there is no way to denote an empty array or non-root
  57. * object. While interpreting "key absent" as empty seems natural
  58. * (removing a key-val from the input string removes the member when
  59. * there are more, so why not when it's the last), it doesn't work:
  60. * "key absent" already means "optional object/array absent", which
  61. * isn't the same as "empty object/array present".
  62. *
  63. * Design flaw: scalar values can only be strings; there is no way to
  64. * denote numbers, true, false or null. The special QObject input
  65. * visitor returned by qobject_input_visitor_new_keyval() mostly hides
  66. * this by automatically converting strings to the type the visitor
  67. * expects. Breaks down for type 'any', where the visitor's
  68. * expectation isn't clear. Code visiting 'any' needs to do the
  69. * conversion itself, but only when using this keyval visitor.
  70. * Awkward. Note that we carefully restrict alternate types to avoid
  71. * similar ambiguity.
  72. *
  73. * Additional syntax for use with an implied key:
  74. *
  75. * key-vals-ik = val-no-key [ ',' key-vals ]
  76. * val-no-key = / [^=,]* /
  77. *
  78. * where no-key is syntactic sugar for implied-key=val-no-key.
  79. */
  80. #include "qemu/osdep.h"
  81. #include "qapi/error.h"
  82. #include "qapi/qmp/qdict.h"
  83. #include "qapi/qmp/qlist.h"
  84. #include "qapi/qmp/qstring.h"
  85. #include "qemu/cutils.h"
  86. #include "qemu/option.h"
  87. /*
  88. * Convert @key to a list index.
  89. * Convert all leading decimal digits to a (non-negative) number,
  90. * capped at INT_MAX.
  91. * If @end is non-null, assign a pointer to the first character after
  92. * the number to *@end.
  93. * Else, fail if any characters follow.
  94. * On success, return the converted number.
  95. * On failure, return a negative value.
  96. * Note: since only digits are converted, no two keys can map to the
  97. * same number, except by overflow to INT_MAX.
  98. */
  99. static int key_to_index(const char *key, const char **end)
  100. {
  101. int ret;
  102. unsigned long index;
  103. if (*key < '0' || *key > '9') {
  104. return -EINVAL;
  105. }
  106. ret = qemu_strtoul(key, end, 10, &index);
  107. if (ret) {
  108. return ret == -ERANGE ? INT_MAX : ret;
  109. }
  110. return index <= INT_MAX ? index : INT_MAX;
  111. }
  112. /*
  113. * Ensure @cur maps @key_in_cur the right way.
  114. * If @value is null, it needs to map to a QDict, else to this
  115. * QString.
  116. * If @cur doesn't have @key_in_cur, put an empty QDict or @value,
  117. * respectively.
  118. * Else, if it needs to map to a QDict, and already does, do nothing.
  119. * Else, if it needs to map to this QString, and already maps to a
  120. * QString, replace it by @value.
  121. * Else, fail because we have conflicting needs on how to map
  122. * @key_in_cur.
  123. * In any case, take over the reference to @value, i.e. if the caller
  124. * wants to hold on to a reference, it needs to qobject_ref().
  125. * Use @key up to @key_cursor to identify the key in error messages.
  126. * On success, return the mapped value.
  127. * On failure, store an error through @errp and return NULL.
  128. */
  129. static QObject *keyval_parse_put(QDict *cur,
  130. const char *key_in_cur, QString *value,
  131. const char *key, const char *key_cursor,
  132. Error **errp)
  133. {
  134. QObject *old, *new;
  135. old = qdict_get(cur, key_in_cur);
  136. if (old) {
  137. if (qobject_type(old) != (value ? QTYPE_QSTRING : QTYPE_QDICT)) {
  138. error_setg(errp, "Parameters '%.*s.*' used inconsistently",
  139. (int)(key_cursor - key), key);
  140. qobject_unref(value);
  141. return NULL;
  142. }
  143. if (!value) {
  144. return old; /* already QDict, do nothing */
  145. }
  146. new = QOBJECT(value); /* replacement */
  147. } else {
  148. new = value ? QOBJECT(value) : QOBJECT(qdict_new());
  149. }
  150. qdict_put_obj(cur, key_in_cur, new);
  151. return new;
  152. }
  153. /*
  154. * Parse one KEY=VALUE from @params, store result in @qdict.
  155. * The first fragment of KEY applies to @qdict. Subsequent fragments
  156. * apply to nested QDicts, which are created on demand. @implied_key
  157. * is as in keyval_parse().
  158. * On success, return a pointer to the next KEY=VALUE, or else to '\0'.
  159. * On failure, return NULL.
  160. */
  161. static const char *keyval_parse_one(QDict *qdict, const char *params,
  162. const char *implied_key,
  163. Error **errp)
  164. {
  165. const char *key, *key_end, *s, *end;
  166. size_t len;
  167. char key_in_cur[128];
  168. QDict *cur;
  169. int ret;
  170. QObject *next;
  171. QString *val;
  172. key = params;
  173. len = strcspn(params, "=,");
  174. if (implied_key && len && key[len] != '=') {
  175. /* Desugar implied key */
  176. key = implied_key;
  177. len = strlen(implied_key);
  178. }
  179. key_end = key + len;
  180. /*
  181. * Loop over key fragments: @s points to current fragment, it
  182. * applies to @cur. @key_in_cur[] holds the previous fragment.
  183. */
  184. cur = qdict;
  185. s = key;
  186. for (;;) {
  187. /* Want a key index (unless it's first) or a QAPI name */
  188. if (s != key && key_to_index(s, &end) >= 0) {
  189. len = end - s;
  190. } else {
  191. ret = parse_qapi_name(s, false);
  192. len = ret < 0 ? 0 : ret;
  193. }
  194. assert(s + len <= key_end);
  195. if (!len || (s + len < key_end && s[len] != '.')) {
  196. assert(key != implied_key);
  197. error_setg(errp, "Invalid parameter '%.*s'",
  198. (int)(key_end - key), key);
  199. return NULL;
  200. }
  201. if (len >= sizeof(key_in_cur)) {
  202. assert(key != implied_key);
  203. error_setg(errp, "Parameter%s '%.*s' is too long",
  204. s != key || s + len != key_end ? " fragment" : "",
  205. (int)len, s);
  206. return NULL;
  207. }
  208. if (s != key) {
  209. next = keyval_parse_put(cur, key_in_cur, NULL,
  210. key, s - 1, errp);
  211. if (!next) {
  212. return NULL;
  213. }
  214. cur = qobject_to(QDict, next);
  215. assert(cur);
  216. }
  217. memcpy(key_in_cur, s, len);
  218. key_in_cur[len] = 0;
  219. s += len;
  220. if (*s != '.') {
  221. break;
  222. }
  223. s++;
  224. }
  225. if (key == implied_key) {
  226. assert(!*s);
  227. s = params;
  228. } else {
  229. if (*s != '=') {
  230. error_setg(errp, "Expected '=' after parameter '%.*s'",
  231. (int)(s - key), key);
  232. return NULL;
  233. }
  234. s++;
  235. }
  236. val = qstring_new();
  237. for (;;) {
  238. if (!*s) {
  239. break;
  240. } else if (*s == ',') {
  241. s++;
  242. if (*s != ',') {
  243. break;
  244. }
  245. }
  246. qstring_append_chr(val, *s++);
  247. }
  248. if (!keyval_parse_put(cur, key_in_cur, val, key, key_end, errp)) {
  249. return NULL;
  250. }
  251. return s;
  252. }
  253. static char *reassemble_key(GSList *key)
  254. {
  255. GString *s = g_string_new("");
  256. GSList *p;
  257. for (p = key; p; p = p->next) {
  258. g_string_prepend_c(s, '.');
  259. g_string_prepend(s, (char *)p->data);
  260. }
  261. return g_string_free(s, FALSE);
  262. }
  263. /*
  264. * Listify @cur recursively.
  265. * Replace QDicts whose keys are all valid list indexes by QLists.
  266. * @key_of_cur is the list of key fragments leading up to @cur.
  267. * On success, return either @cur or its replacement.
  268. * On failure, store an error through @errp and return NULL.
  269. */
  270. static QObject *keyval_listify(QDict *cur, GSList *key_of_cur, Error **errp)
  271. {
  272. GSList key_node;
  273. bool has_index, has_member;
  274. const QDictEntry *ent;
  275. QDict *qdict;
  276. QObject *val;
  277. char *key;
  278. size_t nelt;
  279. QObject **elt;
  280. int index, max_index, i;
  281. QList *list;
  282. key_node.next = key_of_cur;
  283. /*
  284. * Recursively listify @cur's members, and figure out whether @cur
  285. * itself is to be listified.
  286. */
  287. has_index = false;
  288. has_member = false;
  289. for (ent = qdict_first(cur); ent; ent = qdict_next(cur, ent)) {
  290. if (key_to_index(ent->key, NULL) >= 0) {
  291. has_index = true;
  292. } else {
  293. has_member = true;
  294. }
  295. qdict = qobject_to(QDict, ent->value);
  296. if (!qdict) {
  297. continue;
  298. }
  299. key_node.data = ent->key;
  300. val = keyval_listify(qdict, &key_node, errp);
  301. if (!val) {
  302. return NULL;
  303. }
  304. if (val != ent->value) {
  305. qdict_put_obj(cur, ent->key, val);
  306. }
  307. }
  308. if (has_index && has_member) {
  309. key = reassemble_key(key_of_cur);
  310. error_setg(errp, "Parameters '%s*' used inconsistently", key);
  311. g_free(key);
  312. return NULL;
  313. }
  314. if (!has_index) {
  315. return QOBJECT(cur);
  316. }
  317. /* Copy @cur's values to @elt[] */
  318. nelt = qdict_size(cur) + 1; /* one extra, for use as sentinel */
  319. elt = g_new0(QObject *, nelt);
  320. max_index = -1;
  321. for (ent = qdict_first(cur); ent; ent = qdict_next(cur, ent)) {
  322. index = key_to_index(ent->key, NULL);
  323. assert(index >= 0);
  324. if (index > max_index) {
  325. max_index = index;
  326. }
  327. /*
  328. * We iterate @nelt times. If we get one exceeding @nelt
  329. * here, we will put less than @nelt values into @elt[],
  330. * triggering the error in the next loop.
  331. */
  332. if ((size_t)index >= nelt - 1) {
  333. continue;
  334. }
  335. /* Even though dict keys are distinct, indexes need not be */
  336. elt[index] = ent->value;
  337. }
  338. /*
  339. * Make a list from @elt[], reporting the first missing element,
  340. * if any.
  341. * If we dropped an index >= nelt in the previous loop, this loop
  342. * will run into the sentinel and report index @nelt missing.
  343. */
  344. list = qlist_new();
  345. assert(!elt[nelt-1]); /* need the sentinel to be null */
  346. for (i = 0; i < MIN(nelt, max_index + 1); i++) {
  347. if (!elt[i]) {
  348. key = reassemble_key(key_of_cur);
  349. error_setg(errp, "Parameter '%s%d' missing", key, i);
  350. g_free(key);
  351. g_free(elt);
  352. qobject_unref(list);
  353. return NULL;
  354. }
  355. qobject_ref(elt[i]);
  356. qlist_append_obj(list, elt[i]);
  357. }
  358. g_free(elt);
  359. return QOBJECT(list);
  360. }
  361. /*
  362. * Parse @params in QEMU's traditional KEY=VALUE,... syntax.
  363. * If @implied_key, the first KEY= can be omitted. @implied_key is
  364. * implied then, and VALUE can't be empty or contain ',' or '='.
  365. * On success, return a dictionary of the parsed keys and values.
  366. * On failure, store an error through @errp and return NULL.
  367. */
  368. QDict *keyval_parse(const char *params, const char *implied_key,
  369. Error **errp)
  370. {
  371. QDict *qdict = qdict_new();
  372. QObject *listified;
  373. const char *s;
  374. s = params;
  375. while (*s) {
  376. s = keyval_parse_one(qdict, s, implied_key, errp);
  377. if (!s) {
  378. qobject_unref(qdict);
  379. return NULL;
  380. }
  381. implied_key = NULL;
  382. }
  383. listified = keyval_listify(qdict, NULL, errp);
  384. if (!listified) {
  385. qobject_unref(qdict);
  386. return NULL;
  387. }
  388. assert(listified == QOBJECT(qdict));
  389. return qdict;
  390. }