keyval.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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 | help
  17. * key = key-fragment { '.' key-fragment }
  18. * key-fragment = qapi-name | index
  19. * qapi-name = '__' / [a-z0-9.-]+ / '_' / [A-Za-z][A-Za-z0-9_-]* /
  20. * index = / [0-9]+ /
  21. * val = { / [^,]+ / | ',,' }
  22. * help = 'help' | '?'
  23. *
  24. * Semantics defined by reduction to JSON:
  25. *
  26. * key-vals specifies a JSON object, i.e. a tree whose root is an
  27. * object, inner nodes other than the root are objects or arrays,
  28. * and leaves are strings.
  29. *
  30. * Each key-val = key-fragment '.' ... '=' val specifies a path from
  31. * root to a leaf (left of '='), and the leaf's value (right of
  32. * '=').
  33. *
  34. * A path from the root is defined recursively:
  35. * L '.' key-fragment is a child of the node denoted by path L
  36. * key-fragment is a child of the tree root
  37. * If key-fragment is numeric, the parent is an array and the child
  38. * is its key-fragment-th member, counting from zero.
  39. * Else, the parent is an object, and the child is its member named
  40. * key-fragment.
  41. *
  42. * This constrains inner nodes to be either array or object. The
  43. * constraints must be satisfiable. Counter-example: a.b=1,a=2 is
  44. * not, because root.a must be an object to satisfy a.b=1 and a
  45. * string to satisfy a=2.
  46. *
  47. * Array subscripts can occur in any order, but the set of
  48. * subscripts must not have gaps. For instance, a.1=v is not okay,
  49. * because root.a[0] is missing.
  50. *
  51. * If multiple key-val denote the same leaf, the last one determines
  52. * the value.
  53. *
  54. * Key-fragments must be valid QAPI names or consist only of decimal
  55. * digits.
  56. *
  57. * The length of any key-fragment must be between 1 and 127.
  58. *
  59. * If any key-val is help, the object is to be treated as a help
  60. * request.
  61. *
  62. * Design flaw: there is no way to denote an empty array or non-root
  63. * object. While interpreting "key absent" as empty seems natural
  64. * (removing a key-val from the input string removes the member when
  65. * there are more, so why not when it's the last), it doesn't work:
  66. * "key absent" already means "optional object/array absent", which
  67. * isn't the same as "empty object/array present".
  68. *
  69. * Design flaw: scalar values can only be strings; there is no way to
  70. * denote numbers, true, false or null. The special QObject input
  71. * visitor returned by qobject_input_visitor_new_keyval() mostly hides
  72. * this by automatically converting strings to the type the visitor
  73. * expects. Breaks down for type 'any', where the visitor's
  74. * expectation isn't clear. Code visiting 'any' needs to do the
  75. * conversion itself, but only when using this keyval visitor.
  76. * Awkward. Note that we carefully restrict alternate types to avoid
  77. * similar ambiguity.
  78. *
  79. * Alternative syntax for use with an implied key:
  80. *
  81. * key-vals = [ key-val-1st { ',' key-val } [ ',' ] ]
  82. * key-val-1st = val-no-key | key-val
  83. * val-no-key = / [^=,]+ / - help
  84. *
  85. * where val-no-key is syntactic sugar for implied-key=val-no-key.
  86. *
  87. * Note that you can't use the sugared form when the value contains
  88. * '=' or ','.
  89. */
  90. #include "qemu/osdep.h"
  91. #include "qapi/error.h"
  92. #include "qobject/qdict.h"
  93. #include "qobject/qlist.h"
  94. #include "qobject/qstring.h"
  95. #include "qemu/cutils.h"
  96. #include "qemu/keyval.h"
  97. #include "qemu/help_option.h"
  98. /*
  99. * Convert @key to a list index.
  100. * Convert all leading decimal digits to a (non-negative) number,
  101. * capped at INT_MAX.
  102. * If @end is non-null, assign a pointer to the first character after
  103. * the number to *@end.
  104. * Else, fail if any characters follow.
  105. * On success, return the converted number.
  106. * On failure, return a negative value.
  107. * Note: since only digits are converted, no two keys can map to the
  108. * same number, except by overflow to INT_MAX.
  109. */
  110. static int key_to_index(const char *key, const char **end)
  111. {
  112. int ret;
  113. unsigned long index;
  114. if (*key < '0' || *key > '9') {
  115. return -EINVAL;
  116. }
  117. ret = qemu_strtoul(key, end, 10, &index);
  118. if (ret) {
  119. return ret == -ERANGE ? INT_MAX : ret;
  120. }
  121. return index <= INT_MAX ? index : INT_MAX;
  122. }
  123. /*
  124. * Ensure @cur maps @key_in_cur the right way.
  125. * If @value is null, it needs to map to a QDict, else to this
  126. * QString.
  127. * If @cur doesn't have @key_in_cur, put an empty QDict or @value,
  128. * respectively.
  129. * Else, if it needs to map to a QDict, and already does, do nothing.
  130. * Else, if it needs to map to this QString, and already maps to a
  131. * QString, replace it by @value.
  132. * Else, fail because we have conflicting needs on how to map
  133. * @key_in_cur.
  134. * In any case, take over the reference to @value, i.e. if the caller
  135. * wants to hold on to a reference, it needs to qobject_ref().
  136. * Use @key up to @key_cursor to identify the key in error messages.
  137. * On success, return the mapped value.
  138. * On failure, store an error through @errp and return NULL.
  139. */
  140. static QObject *keyval_parse_put(QDict *cur,
  141. const char *key_in_cur, QString *value,
  142. const char *key, const char *key_cursor,
  143. Error **errp)
  144. {
  145. QObject *old, *new;
  146. old = qdict_get(cur, key_in_cur);
  147. if (old) {
  148. if (qobject_type(old) != (value ? QTYPE_QSTRING : QTYPE_QDICT)) {
  149. error_setg(errp, "Parameters '%.*s.*' used inconsistently",
  150. (int)(key_cursor - key), key);
  151. qobject_unref(value);
  152. return NULL;
  153. }
  154. if (!value) {
  155. return old; /* already QDict, do nothing */
  156. }
  157. new = QOBJECT(value); /* replacement */
  158. } else {
  159. new = value ? QOBJECT(value) : QOBJECT(qdict_new());
  160. }
  161. qdict_put_obj(cur, key_in_cur, new);
  162. return new;
  163. }
  164. /*
  165. * Parse one parameter from @params.
  166. *
  167. * If we're looking at KEY=VALUE, store result in @qdict.
  168. * The first fragment of KEY applies to @qdict. Subsequent fragments
  169. * apply to nested QDicts, which are created on demand. @implied_key
  170. * is as in keyval_parse().
  171. *
  172. * If we're looking at "help" or "?", set *help to true.
  173. *
  174. * On success, return a pointer to the next parameter, or else to '\0'.
  175. * On failure, return NULL.
  176. */
  177. static const char *keyval_parse_one(QDict *qdict, const char *params,
  178. const char *implied_key, bool *help,
  179. Error **errp)
  180. {
  181. const char *key, *key_end, *val_end, *s, *end;
  182. size_t len;
  183. char key_in_cur[128];
  184. QDict *cur;
  185. int ret;
  186. QObject *next;
  187. GString *val;
  188. key = params;
  189. val_end = NULL;
  190. len = strcspn(params, "=,");
  191. if (len && key[len] != '=') {
  192. if (starts_with_help_option(key) == len) {
  193. *help = true;
  194. s = key + len;
  195. if (*s == ',') {
  196. s++;
  197. }
  198. return s;
  199. }
  200. if (implied_key) {
  201. /* Desugar implied key */
  202. key = implied_key;
  203. val_end = params + len;
  204. len = strlen(implied_key);
  205. }
  206. }
  207. key_end = key + len;
  208. /*
  209. * Loop over key fragments: @s points to current fragment, it
  210. * applies to @cur. @key_in_cur[] holds the previous fragment.
  211. */
  212. cur = qdict;
  213. s = key;
  214. for (;;) {
  215. /* Want a key index (unless it's first) or a QAPI name */
  216. if (s != key && key_to_index(s, &end) >= 0) {
  217. len = end - s;
  218. } else {
  219. ret = parse_qapi_name(s, false);
  220. len = ret < 0 ? 0 : ret;
  221. }
  222. assert(s + len <= key_end);
  223. if (!len || (s + len < key_end && s[len] != '.')) {
  224. assert(key != implied_key);
  225. error_setg(errp, "Invalid parameter '%.*s'",
  226. (int)(key_end - key), key);
  227. return NULL;
  228. }
  229. if (len >= sizeof(key_in_cur)) {
  230. assert(key != implied_key);
  231. error_setg(errp, "Parameter%s '%.*s' is too long",
  232. s != key || s + len != key_end ? " fragment" : "",
  233. (int)len, s);
  234. return NULL;
  235. }
  236. if (s != key) {
  237. next = keyval_parse_put(cur, key_in_cur, NULL,
  238. key, s - 1, errp);
  239. if (!next) {
  240. return NULL;
  241. }
  242. cur = qobject_to(QDict, next);
  243. assert(cur);
  244. }
  245. memcpy(key_in_cur, s, len);
  246. key_in_cur[len] = 0;
  247. s += len;
  248. if (*s != '.') {
  249. break;
  250. }
  251. s++;
  252. }
  253. if (key == implied_key) {
  254. assert(!*s);
  255. val = g_string_new_len(params, val_end - params);
  256. s = val_end;
  257. if (*s == ',') {
  258. s++;
  259. }
  260. } else {
  261. if (*s != '=') {
  262. error_setg(errp, "Expected '=' after parameter '%.*s'",
  263. (int)(s - key), key);
  264. return NULL;
  265. }
  266. s++;
  267. val = g_string_new(NULL);
  268. for (;;) {
  269. if (!*s) {
  270. break;
  271. } else if (*s == ',') {
  272. s++;
  273. if (*s != ',') {
  274. break;
  275. }
  276. }
  277. g_string_append_c(val, *s++);
  278. }
  279. }
  280. if (!keyval_parse_put(cur, key_in_cur, qstring_from_gstring(val),
  281. key, key_end, errp)) {
  282. return NULL;
  283. }
  284. return s;
  285. }
  286. static char *reassemble_key(GSList *key)
  287. {
  288. GString *s = g_string_new("");
  289. GSList *p;
  290. for (p = key; p; p = p->next) {
  291. g_string_prepend_c(s, '.');
  292. g_string_prepend(s, (char *)p->data);
  293. }
  294. return g_string_free(s, FALSE);
  295. }
  296. /*
  297. * Recursive worker for keyval_merge.
  298. *
  299. * @str is the path that led to the * current dictionary (to be used for
  300. * error messages). It is modified internally but restored before the
  301. * function returns.
  302. */
  303. static void keyval_do_merge(QDict *dest, const QDict *merged, GString *str, Error **errp)
  304. {
  305. size_t save_len = str->len;
  306. const QDictEntry *ent;
  307. QObject *old_value;
  308. for (ent = qdict_first(merged); ent; ent = qdict_next(merged, ent)) {
  309. old_value = qdict_get(dest, ent->key);
  310. if (old_value) {
  311. if (qobject_type(old_value) != qobject_type(ent->value)) {
  312. error_setg(errp, "Parameter '%s%s' used inconsistently",
  313. str->str, ent->key);
  314. return;
  315. } else if (qobject_type(ent->value) == QTYPE_QDICT) {
  316. /* Merge sub-dictionaries. */
  317. g_string_append(str, ent->key);
  318. g_string_append_c(str, '.');
  319. keyval_do_merge(qobject_to(QDict, old_value),
  320. qobject_to(QDict, ent->value),
  321. str, errp);
  322. g_string_truncate(str, save_len);
  323. continue;
  324. } else if (qobject_type(ent->value) == QTYPE_QLIST) {
  325. /* Append to old list. */
  326. QList *old = qobject_to(QList, old_value);
  327. QList *new = qobject_to(QList, ent->value);
  328. const QListEntry *item;
  329. QLIST_FOREACH_ENTRY(new, item) {
  330. qobject_ref(item->value);
  331. qlist_append_obj(old, item->value);
  332. }
  333. continue;
  334. } else {
  335. assert(qobject_type(ent->value) == QTYPE_QSTRING);
  336. }
  337. }
  338. qobject_ref(ent->value);
  339. qdict_put_obj(dest, ent->key, ent->value);
  340. }
  341. }
  342. /* Merge the @merged dictionary into @dest.
  343. *
  344. * The dictionaries are expected to be returned by the keyval parser, and
  345. * therefore the only expected scalar type is the string. In case the same
  346. * path is present in both @dest and @merged, the semantics are as follows:
  347. *
  348. * - lists are concatenated
  349. *
  350. * - dictionaries are merged recursively
  351. *
  352. * - for scalar values, @merged wins
  353. *
  354. * In case an error is reported, @dest may already have been modified.
  355. *
  356. * This function can be used to implement semantics analogous to QemuOpts's
  357. * .merge_lists = true case, or to implement -set for options backed by QDicts.
  358. *
  359. * Note: while QemuOpts is commonly used so that repeated keys overwrite
  360. * ("last one wins"), it can also be used so that repeated keys build up
  361. * a list. keyval_merge() can only be used when the options' semantics are
  362. * the former, not the latter.
  363. */
  364. void keyval_merge(QDict *dest, const QDict *merged, Error **errp)
  365. {
  366. GString *str;
  367. str = g_string_new("");
  368. keyval_do_merge(dest, merged, str, errp);
  369. g_string_free(str, TRUE);
  370. }
  371. /*
  372. * Listify @cur recursively.
  373. * Replace QDicts whose keys are all valid list indexes by QLists.
  374. * @key_of_cur is the list of key fragments leading up to @cur.
  375. * On success, return either @cur or its replacement.
  376. * On failure, store an error through @errp and return NULL.
  377. */
  378. static QObject *keyval_listify(QDict *cur, GSList *key_of_cur, Error **errp)
  379. {
  380. GSList key_node;
  381. bool has_index, has_member;
  382. const QDictEntry *ent;
  383. QDict *qdict;
  384. QObject *val;
  385. char *key;
  386. size_t nelt;
  387. QObject **elt;
  388. int index, max_index, i;
  389. QList *list;
  390. key_node.next = key_of_cur;
  391. /*
  392. * Recursively listify @cur's members, and figure out whether @cur
  393. * itself is to be listified.
  394. */
  395. has_index = false;
  396. has_member = false;
  397. for (ent = qdict_first(cur); ent; ent = qdict_next(cur, ent)) {
  398. if (key_to_index(ent->key, NULL) >= 0) {
  399. has_index = true;
  400. } else {
  401. has_member = true;
  402. }
  403. qdict = qobject_to(QDict, ent->value);
  404. if (!qdict) {
  405. continue;
  406. }
  407. key_node.data = ent->key;
  408. val = keyval_listify(qdict, &key_node, errp);
  409. if (!val) {
  410. return NULL;
  411. }
  412. if (val != ent->value) {
  413. qdict_put_obj(cur, ent->key, val);
  414. }
  415. }
  416. if (has_index && has_member) {
  417. key = reassemble_key(key_of_cur);
  418. error_setg(errp, "Parameters '%s*' used inconsistently", key);
  419. g_free(key);
  420. return NULL;
  421. }
  422. if (!has_index) {
  423. return QOBJECT(cur);
  424. }
  425. /* Copy @cur's values to @elt[] */
  426. nelt = qdict_size(cur) + 1; /* one extra, for use as sentinel */
  427. elt = g_new0(QObject *, nelt);
  428. max_index = -1;
  429. for (ent = qdict_first(cur); ent; ent = qdict_next(cur, ent)) {
  430. index = key_to_index(ent->key, NULL);
  431. assert(index >= 0);
  432. if (index > max_index) {
  433. max_index = index;
  434. }
  435. /*
  436. * We iterate @nelt times. If we get one exceeding @nelt
  437. * here, we will put less than @nelt values into @elt[],
  438. * triggering the error in the next loop.
  439. */
  440. if ((size_t)index >= nelt - 1) {
  441. continue;
  442. }
  443. /* Even though dict keys are distinct, indexes need not be */
  444. elt[index] = ent->value;
  445. }
  446. /*
  447. * Make a list from @elt[], reporting the first missing element,
  448. * if any.
  449. * If we dropped an index >= nelt in the previous loop, this loop
  450. * will run into the sentinel and report index @nelt missing.
  451. */
  452. list = qlist_new();
  453. assert(!elt[nelt-1]); /* need the sentinel to be null */
  454. for (i = 0; i < MIN(nelt, max_index + 1); i++) {
  455. if (!elt[i]) {
  456. key = reassemble_key(key_of_cur);
  457. error_setg(errp, "Parameter '%s%d' missing", key, i);
  458. g_free(key);
  459. g_free(elt);
  460. qobject_unref(list);
  461. return NULL;
  462. }
  463. qobject_ref(elt[i]);
  464. qlist_append_obj(list, elt[i]);
  465. }
  466. g_free(elt);
  467. return QOBJECT(list);
  468. }
  469. /*
  470. * Parse @params in QEMU's traditional KEY=VALUE,... syntax.
  471. *
  472. * If @implied_key, the first KEY= can be omitted. @implied_key is
  473. * implied then, and VALUE can't be empty or contain ',' or '='.
  474. *
  475. * A parameter "help" or "?" without a value isn't added to the
  476. * resulting dictionary, but instead is interpreted as help request.
  477. * All other options are parsed and returned normally so that context
  478. * specific help can be printed.
  479. *
  480. * If @p_help is not NULL, store whether help is requested there.
  481. * If @p_help is NULL and help is requested, fail.
  482. *
  483. * On success, return @dict, now filled with the parsed keys and values.
  484. *
  485. * On failure, store an error through @errp and return NULL. Any keys
  486. * and values parsed so far will be in @dict nevertheless.
  487. */
  488. QDict *keyval_parse_into(QDict *qdict, const char *params, const char *implied_key,
  489. bool *p_help, Error **errp)
  490. {
  491. QObject *listified;
  492. const char *s;
  493. bool help = false;
  494. s = params;
  495. while (*s) {
  496. s = keyval_parse_one(qdict, s, implied_key, &help, errp);
  497. if (!s) {
  498. return NULL;
  499. }
  500. implied_key = NULL;
  501. }
  502. if (p_help) {
  503. *p_help = help;
  504. } else if (help) {
  505. error_setg(errp, "Help is not available for this option");
  506. return NULL;
  507. }
  508. listified = keyval_listify(qdict, NULL, errp);
  509. if (!listified) {
  510. return NULL;
  511. }
  512. assert(listified == QOBJECT(qdict));
  513. return qdict;
  514. }
  515. /*
  516. * Parse @params in QEMU's traditional KEY=VALUE,... syntax.
  517. *
  518. * If @implied_key, the first KEY= can be omitted. @implied_key is
  519. * implied then, and VALUE can't be empty or contain ',' or '='.
  520. *
  521. * A parameter "help" or "?" without a value isn't added to the
  522. * resulting dictionary, but instead is interpreted as help request.
  523. * All other options are parsed and returned normally so that context
  524. * specific help can be printed.
  525. *
  526. * If @p_help is not NULL, store whether help is requested there.
  527. * If @p_help is NULL and help is requested, fail.
  528. *
  529. * On success, return a dictionary of the parsed keys and values.
  530. * On failure, store an error through @errp and return NULL.
  531. */
  532. QDict *keyval_parse(const char *params, const char *implied_key,
  533. bool *p_help, Error **errp)
  534. {
  535. QDict *qdict = qdict_new();
  536. QDict *ret = keyval_parse_into(qdict, params, implied_key, p_help, errp);
  537. if (!ret) {
  538. qobject_unref(qdict);
  539. }
  540. return ret;
  541. }