Whamcloud - gitweb
LU-12513 utils: change cy_valueint to 64 bits
[fs/lustre-release.git] / lnet / utils / lnetconfig / cyaml.c
1 /*
2  * LGPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU Lesser General Public License as
8  * published by the Free Software Foundation; either version 2.1 of the
9  * License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library. If not, see <http://www.gnu.org/licenses/>.
18  *
19  * LGPL HEADER END
20  *
21  * Copyright (c) 2014, 2017, Intel Corporation.
22  *
23  * Author:
24  *   Amir Shehata <amir.shehata@intel.com>
25  */
26
27 /*
28  *  The cYAML tree is constructed as an n-tree.
29  *  root -> cmd 1
30  *          ||
31  *          \/
32  *          cmd 2 -> attr1 -> attr2
33  *                              ||
34  *                              \/
35  *                            attr2.1 -> attr2.1.1 -> attr2.1.2
36  */
37
38 #include <yaml.h>
39 #include <stdio.h>
40 #include <string.h>
41 #include <stdio.h>
42 #include <math.h>
43 #include <stdlib.h>
44 #include <float.h>
45 #include <limits.h>
46 #include <ctype.h>
47 #include "libcfs/util/list.h"
48 #include <cyaml.h>
49
50 #define INDENT          4
51 #define EXTRA_IND       2
52
53 /*
54  * cYAML_print_info
55  *   This structure contains print information
56  *   required when printing the node
57  */
58 struct cYAML_print_info {
59         int level;
60         int array_first_elem;
61         int extra_ind;
62 };
63
64 /*
65  *  cYAML_ll
66  *  Linked list of different trees representing YAML
67  *  documents.
68  */
69 struct cYAML_ll {
70         struct list_head list;
71         struct cYAML *obj;
72         struct cYAML_print_info *print_info;
73 };
74
75 static void print_value(FILE *f, struct list_head *stack);
76
77 enum cYAML_handler_error {
78         CYAML_ERROR_NONE = 0,
79         CYAML_ERROR_UNEXPECTED_STATE = -1,
80         CYAML_ERROR_NOT_SUPPORTED = -2,
81         CYAML_ERROR_OUT_OF_MEM = -3,
82         CYAML_ERROR_BAD_VALUE = -4,
83         CYAML_ERROR_PARSE = -5,
84 };
85
86 enum cYAML_tree_state {
87         TREE_STATE_COMPLETE = 0,
88         TREE_STATE_INITED,
89         TREE_STATE_TREE_STARTED,
90         TREE_STATE_BLK_STARTED,
91         TREE_STATE_KEY,
92         TREE_STATE_KEY_FILLED,
93         TREE_STATE_VALUE,
94         TREE_STATE_SEQ_START,
95 };
96
97 struct cYAML_tree_node {
98         struct cYAML *root;
99         /* cur is the current node we're operating on */
100         struct cYAML *cur;
101         enum cYAML_tree_state state;
102         int from_blk_map_start;
103         /* represents the tree depth */
104         struct list_head ll;
105 };
106
107 typedef enum cYAML_handler_error (*yaml_token_handler)(yaml_token_t *token,
108                                                 struct cYAML_tree_node *);
109
110 static enum cYAML_handler_error yaml_parse_error(yaml_token_t *token,
111                                         struct cYAML_tree_node *tree);
112 static enum cYAML_handler_error yaml_stream_start(yaml_token_t *token,
113                                         struct cYAML_tree_node *tree);
114 static enum cYAML_handler_error yaml_stream_end(yaml_token_t *token,
115                                         struct cYAML_tree_node *tree);
116 static enum cYAML_handler_error yaml_not_supported(yaml_token_t *token,
117                                                 struct cYAML_tree_node *tree);
118 static enum cYAML_handler_error yaml_document_start(yaml_token_t *token,
119                                                 struct cYAML_tree_node *tree);
120 static enum cYAML_handler_error yaml_document_end(yaml_token_t *token,
121                                                struct cYAML_tree_node *tree);
122 static enum cYAML_handler_error yaml_blk_seq_start(yaml_token_t *token,
123                                                 struct cYAML_tree_node *tree);
124 static enum cYAML_handler_error yaml_blk_mapping_start(yaml_token_t *token,
125                                                 struct cYAML_tree_node *tree);
126 static enum cYAML_handler_error yaml_block_end(yaml_token_t *token,
127                                         struct cYAML_tree_node *tree);
128 static enum cYAML_handler_error yaml_key(yaml_token_t *token,
129                                 struct cYAML_tree_node *tree);
130 static enum cYAML_handler_error yaml_value(yaml_token_t *token,
131                                         struct cYAML_tree_node *tree);
132 static enum cYAML_handler_error yaml_scalar(yaml_token_t *token,
133                                         struct cYAML_tree_node *tree);
134 static enum cYAML_handler_error yaml_entry_token(yaml_token_t *token,
135                                         struct cYAML_tree_node *tree);
136
137 /* dispatch table */
138 static yaml_token_handler dispatch_tbl[] = {
139         [YAML_NO_TOKEN] = yaml_parse_error,
140         [YAML_STREAM_START_TOKEN] = yaml_stream_start,
141         [YAML_STREAM_END_TOKEN] = yaml_stream_end,
142         [YAML_VERSION_DIRECTIVE_TOKEN] = yaml_not_supported,
143         [YAML_TAG_DIRECTIVE_TOKEN] = yaml_not_supported,
144         [YAML_DOCUMENT_START_TOKEN] = yaml_document_start,
145         [YAML_DOCUMENT_END_TOKEN] = yaml_document_end,
146         [YAML_BLOCK_SEQUENCE_START_TOKEN] = yaml_blk_seq_start,
147         [YAML_BLOCK_MAPPING_START_TOKEN] = yaml_blk_mapping_start,
148         [YAML_BLOCK_END_TOKEN] = yaml_block_end,
149         [YAML_FLOW_SEQUENCE_START_TOKEN] = yaml_not_supported,
150         [YAML_FLOW_SEQUENCE_END_TOKEN] = yaml_not_supported,
151         [YAML_FLOW_MAPPING_START_TOKEN] = yaml_not_supported,
152         [YAML_FLOW_MAPPING_END_TOKEN] = yaml_not_supported,
153         [YAML_BLOCK_ENTRY_TOKEN] = yaml_entry_token,
154         [YAML_FLOW_ENTRY_TOKEN] = yaml_not_supported,
155         [YAML_KEY_TOKEN] = yaml_key,
156         [YAML_VALUE_TOKEN] = yaml_value,
157         [YAML_ALIAS_TOKEN] = yaml_not_supported,
158         [YAML_ANCHOR_TOKEN] = yaml_not_supported,
159         [YAML_TAG_TOKEN] = yaml_not_supported,
160         [YAML_SCALAR_TOKEN] = yaml_scalar,
161 };
162
163 /* dispatch table */
164 static char *token_type_string[] = {
165         [YAML_NO_TOKEN] = "YAML_NO_TOKEN",
166         [YAML_STREAM_START_TOKEN] = "YAML_STREAM_START_TOKEN",
167         [YAML_STREAM_END_TOKEN] = "YAML_STREAM_END_TOKEN",
168         [YAML_VERSION_DIRECTIVE_TOKEN] = "YAML_VERSION_DIRECTIVE_TOKEN",
169         [YAML_TAG_DIRECTIVE_TOKEN] = "YAML_TAG_DIRECTIVE_TOKEN",
170         [YAML_DOCUMENT_START_TOKEN] = "YAML_DOCUMENT_START_TOKEN",
171         [YAML_DOCUMENT_END_TOKEN] = "YAML_DOCUMENT_END_TOKEN",
172         [YAML_BLOCK_SEQUENCE_START_TOKEN] = "YAML_BLOCK_SEQUENCE_START_TOKEN",
173         [YAML_BLOCK_MAPPING_START_TOKEN] = "YAML_BLOCK_MAPPING_START_TOKEN",
174         [YAML_BLOCK_END_TOKEN] = "YAML_BLOCK_END_TOKEN",
175         [YAML_FLOW_SEQUENCE_START_TOKEN] = "YAML_FLOW_SEQUENCE_START_TOKEN",
176         [YAML_FLOW_SEQUENCE_END_TOKEN] = "YAML_FLOW_SEQUENCE_END_TOKEN",
177         [YAML_FLOW_MAPPING_START_TOKEN] = "YAML_FLOW_MAPPING_START_TOKEN",
178         [YAML_FLOW_MAPPING_END_TOKEN] = "YAML_FLOW_MAPPING_END_TOKEN",
179         [YAML_BLOCK_ENTRY_TOKEN] = "YAML_BLOCK_ENTRY_TOKEN",
180         [YAML_FLOW_ENTRY_TOKEN] = "YAML_FLOW_ENTRY_TOKEN",
181         [YAML_KEY_TOKEN] = "YAML_KEY_TOKEN",
182         [YAML_VALUE_TOKEN] = "YAML_VALUE_TOKEN",
183         [YAML_ALIAS_TOKEN] = "YAML_ALIAS_TOKEN",
184         [YAML_ANCHOR_TOKEN] = "YAML_ANCHOR_TOKEN",
185         [YAML_TAG_TOKEN] = "YAML_TAG_TOKEN",
186         [YAML_SCALAR_TOKEN] = "YAML_SCALAR_TOKEN",
187 };
188
189 static char *state_string[] = {
190         [TREE_STATE_COMPLETE] = "COMPLETE",
191         [TREE_STATE_INITED] = "INITED",
192         [TREE_STATE_TREE_STARTED] = "TREE_STARTED",
193         [TREE_STATE_BLK_STARTED] = "BLK_STARTED",
194         [TREE_STATE_KEY] = "KEY",
195         [TREE_STATE_KEY_FILLED] = "KEY_FILLED",
196         [TREE_STATE_VALUE] = "VALUE",
197         [TREE_STATE_SEQ_START] = "SEQ_START",
198 };
199
200 static void cYAML_ll_free(struct list_head *ll)
201 {
202         struct cYAML_ll *node, *tmp;
203
204         list_for_each_entry_safe(node, tmp, ll, list) {
205                 free(node->print_info);
206                 free(node);
207         }
208 }
209
210 static int cYAML_ll_push(struct cYAML *obj,
211                          const struct cYAML_print_info *print_info,
212                          struct list_head *list)
213 {
214         struct cYAML_ll *node = calloc(1, sizeof(*node));
215         if (node == NULL)
216                 return -1;
217
218         INIT_LIST_HEAD(&node->list);
219
220         if (print_info) {
221                 node->print_info = calloc(1, sizeof(*print_info));
222                 if (node->print_info == NULL) {
223                         free(node);
224                         return -1;
225                 }
226                 *node->print_info = *print_info;
227         }
228         node->obj = obj;
229
230         list_add(&node->list, list);
231
232         return 0;
233 }
234
235 static struct cYAML *cYAML_ll_pop(struct list_head *list,
236                                   struct cYAML_print_info **print_info)
237 {
238         struct cYAML_ll *pop;
239         struct cYAML *obj = NULL;
240
241         if (!list_empty(list)) {
242                 pop = list_entry(list->next, struct cYAML_ll, list);
243
244                 obj = pop->obj;
245                 if (print_info != NULL)
246                         *print_info = pop->print_info;
247                 list_del(&pop->list);
248
249                 if (print_info == NULL)
250                         free(pop->print_info);
251
252                 free(pop);
253         }
254         return obj;
255 }
256
257 static int cYAML_ll_count(struct list_head *ll)
258 {
259         int i = 0;
260         struct list_head *node;
261
262         list_for_each(node, ll)
263                 i++;
264
265         return i;
266 }
267
268 static int cYAML_tree_init(struct cYAML_tree_node *tree)
269 {
270         struct cYAML *obj = NULL, *cur = NULL;
271
272         if (tree == NULL)
273                 return -1;
274
275         obj = calloc(1, sizeof(*obj));
276         if (obj == NULL)
277                 return -1;
278
279         if (tree->root) {
280                 /* append the node */
281                 cur = tree->root;
282                 while (cur->cy_next != NULL)
283                         cur = cur->cy_next;
284                 cur->cy_next = obj;
285         } else {
286                 tree->root = obj;
287         }
288
289         obj->cy_type = CYAML_TYPE_OBJECT;
290
291         tree->cur = obj;
292         tree->state = TREE_STATE_COMPLETE;
293
294         /* free it and start anew */
295         if (!list_empty(&tree->ll))
296                 cYAML_ll_free(&tree->ll);
297
298         return 0;
299 }
300
301 static struct cYAML *create_child(struct cYAML *parent)
302 {
303         struct cYAML *obj;
304
305         if (parent == NULL)
306                 return NULL;
307
308         obj = calloc(1, sizeof(*obj));
309         if (obj == NULL)
310                 return NULL;
311
312         /* set the type to OBJECT and let the value change that */
313         obj->cy_type = CYAML_TYPE_OBJECT;
314
315         parent->cy_child = obj;
316
317         return obj;
318 }
319
320 static struct cYAML *create_sibling(struct cYAML *sibling)
321 {
322         struct cYAML *obj;
323
324         if (sibling == NULL)
325                 return NULL;
326
327         obj = calloc(1, sizeof(*obj));
328         if (obj == NULL)
329                 return NULL;
330
331         /* set the type to OBJECT and let the value change that */
332         obj->cy_type = CYAML_TYPE_OBJECT;
333
334         sibling->cy_next = obj;
335         obj->cy_prev = sibling;
336
337         return obj;
338 }
339
340 /* Parse the input text to generate a number,
341  * and populate the result into item. */
342 static bool parse_number(struct cYAML *item, const char *input)
343 {
344         double n = 0, sign = 1, scale = 0;
345         int subscale = 0, signsubscale = 1;
346         const char *num = input;
347
348         if (*num == '-') {
349                 sign = -1;
350                 num++;
351         }
352
353         if (*num == '0')
354                 num++;
355
356         if (*num >= '1' && *num <= '9') {
357                 do {
358                         n = (n * 10.0) + (*num++ - '0');
359                 } while (*num >= '0' && *num <= '9');
360         }
361
362         if (*num == '.' && num[1] >= '0' && num[1] <= '9') {
363                 num++;
364                 do {
365                         n = (n * 10.0) + (*num++ - '0');
366                         scale--;
367                 } while (*num >= '0' && *num <= '9');
368         }
369
370         if (*num == 'e' || *num == 'E') {
371                 num++;
372                 if (*num == '+') {
373                         num++;
374                 } else if (*num == '-') {
375                         signsubscale = -1;
376                         num++;
377                 }
378                 while (*num >= '0' && *num <= '9')
379                         subscale = (subscale * 10) + (*num++ - '0');
380         }
381
382         /* check to see if the entire string is consumed.  If not then
383          * that means this is a string with a number in it */
384         if (num != (input + strlen(input)))
385                 return false;
386
387         /* number = +/- number.fraction * 10^+/- exponent */
388         n = sign * n * pow(10.0, (scale + subscale * signsubscale));
389
390         item->cy_valuedouble = n;
391         item->cy_valueint = (int)n;
392         item->cy_type = CYAML_TYPE_NUMBER;
393
394         return true;
395 }
396
397 static int assign_type_value(struct cYAML *obj, const char *value)
398 {
399         if (value == NULL)
400                 return -1;
401
402         if (strcmp(value, "null") == 0)
403                 obj->cy_type = CYAML_TYPE_NULL;
404         else if (strcmp(value, "false") == 0) {
405                 obj->cy_type = CYAML_TYPE_FALSE;
406                 obj->cy_valueint = 0;
407         } else if (strcmp(value, "true") == 0) {
408                 obj->cy_type = CYAML_TYPE_TRUE;
409                 obj->cy_valueint = 1;
410         } else if (*value == '-' || (*value >= '0' && *value <= '9')) {
411                 if (parse_number(obj, value) == 0) {
412                         obj->cy_valuestring = strdup(value);
413                         obj->cy_type = CYAML_TYPE_STRING;
414                 }
415         } else {
416                 obj->cy_valuestring = strdup(value);
417                 obj->cy_type = CYAML_TYPE_STRING;
418         }
419
420         return 0;
421 }
422
423 /*
424  * yaml_handle_token
425  *  Builds the YAML tree rpresentation as the tokens are passed in
426  *
427  *  if token == STREAM_START && tree_state != COMPLETE
428  *    something wrong. fail.
429  *  else tree_state = INITIED
430  *  if token == DOCUMENT_START && tree_state != COMPLETE || INITED
431  *    something wrong, fail.
432  *  else tree_state = TREE_STARTED
433  *  if token == DOCUMENT_END
434  *    tree_state = INITED if no STREAM START, else tree_state = COMPLETE
435  *    erase everything on ll
436  *  if token == STREAM_END && tree_state != INITED
437  *    something wrong fail.
438  *  else tree_state = COMPLETED
439  *  if token == YAML_KEY_TOKEN && state != TREE_STARTED
440  *    something wrong, fail.
441  *  if token == YAML_SCALAR_TOKEN && state != KEY || VALUE
442  *    fail.
443  *  else if tree_state == KEY
444  *     create a new sibling under the current head of the ll (if ll is
445  *     empty insert the new node there and it becomes the root.)
446  *    add the scalar value in the "string"
447  *    tree_state = KEY_FILLED
448  *  else if tree_state == VALUE
449  *    try and figure out whether this is a double, int or string and store
450  *    it appropriately
451  *    state = TREE_STARTED
452  * else if token == YAML_BLOCK_MAPPING_START_TOKEN && tree_state != VALUE
453  *   fail
454  * else push the current node on the ll && state = TREE_STARTED
455  * if token == YAML_BLOCK_END_TOKEN && state != TREE_STARTED
456  *   fail.
457  * else pop the current token off the ll and make it the cur
458  * if token == YAML_VALUE_TOKEN && state != KEY_FILLED
459  *   fail.
460  * else state = VALUE
461  *
462  */
463 static enum cYAML_handler_error yaml_parse_error(yaml_token_t *token,
464                                                  struct cYAML_tree_node *tree)
465 {
466         return CYAML_ERROR_PARSE;
467 }
468
469 static enum cYAML_handler_error yaml_stream_start(yaml_token_t *token,
470                                                   struct cYAML_tree_node *tree)
471 {
472         enum cYAML_handler_error rc;
473
474         /* with each new stream initialize a new tree */
475         rc = cYAML_tree_init(tree);
476
477         if (rc != CYAML_ERROR_NONE)
478                 return rc;
479
480         tree->state = TREE_STATE_INITED;
481
482         return CYAML_ERROR_NONE;
483 }
484
485 static enum cYAML_handler_error yaml_stream_end(yaml_token_t *token,
486                                                 struct cYAML_tree_node *tree)
487 {
488         if (tree->state != TREE_STATE_TREE_STARTED &&
489             tree->state != TREE_STATE_COMPLETE &&
490             tree->state != TREE_STATE_INITED)
491                 return CYAML_ERROR_UNEXPECTED_STATE;
492
493         tree->state = TREE_STATE_INITED;
494
495         return CYAML_ERROR_NONE;
496 }
497
498 static enum cYAML_handler_error
499 yaml_document_start(yaml_token_t *token, struct cYAML_tree_node *tree)
500 {
501         if (tree->state != TREE_STATE_INITED)
502                 return CYAML_ERROR_UNEXPECTED_STATE;
503
504         /* go to started state since we're expecting more tokens to come */
505         tree->state = TREE_STATE_TREE_STARTED;
506
507         return CYAML_ERROR_NONE;
508 }
509
510 static enum cYAML_handler_error yaml_document_end(yaml_token_t *token,
511                                                   struct cYAML_tree_node *tree)
512 {
513         if (tree->state != TREE_STATE_COMPLETE)
514                 return CYAML_ERROR_UNEXPECTED_STATE;
515
516         tree->state = TREE_STATE_TREE_STARTED;
517
518         return CYAML_ERROR_NONE;
519 }
520
521 static enum cYAML_handler_error yaml_key(yaml_token_t *token,
522                                          struct cYAML_tree_node *tree)
523 {
524         if (tree->state != TREE_STATE_BLK_STARTED &&
525             tree->state != TREE_STATE_VALUE)
526                 return CYAML_ERROR_UNEXPECTED_STATE;
527
528         if (tree->from_blk_map_start == 0 ||
529             tree->state == TREE_STATE_VALUE)
530                 tree->cur = create_sibling(tree->cur);
531
532         tree->from_blk_map_start = 0;
533
534         tree->state = TREE_STATE_KEY;
535
536         return CYAML_ERROR_NONE;
537 }
538
539 static enum cYAML_handler_error yaml_scalar(yaml_token_t *token,
540                                             struct cYAML_tree_node *tree)
541 {
542         if (tree->state == TREE_STATE_KEY) {
543                 /* assign the scalar value to the key that was created */
544                 tree->cur->cy_string =
545                   strdup((const char *)token->data.scalar.value);
546
547                 tree->state = TREE_STATE_KEY_FILLED;
548         } else if (tree->state == TREE_STATE_VALUE) {
549                 if (assign_type_value(tree->cur,
550                                       (char *)token->data.scalar.value))
551                         /* failed to assign a value */
552                         return CYAML_ERROR_BAD_VALUE;
553                 tree->state = TREE_STATE_BLK_STARTED;
554         } else {
555                 return CYAML_ERROR_UNEXPECTED_STATE;
556         }
557
558         return CYAML_ERROR_NONE;
559 }
560
561 static enum cYAML_handler_error yaml_value(yaml_token_t *token,
562                                            struct cYAML_tree_node *tree)
563 {
564         if (tree->state != TREE_STATE_KEY_FILLED)
565                 return CYAML_ERROR_UNEXPECTED_STATE;
566
567         tree->state = TREE_STATE_VALUE;
568
569         return CYAML_ERROR_NONE;
570 }
571
572 static enum cYAML_handler_error yaml_blk_seq_start(yaml_token_t *token,
573                                                    struct cYAML_tree_node *tree)
574 {
575         if (tree->state != TREE_STATE_VALUE)
576                 return CYAML_ERROR_UNEXPECTED_STATE;
577
578         /* Since a sequenc start event determines that this is the start
579          * of an array, then that means the current node we're at is an
580          * array and we need to flag it as such */
581         tree->cur->cy_type = CYAML_TYPE_ARRAY;
582         tree->state = TREE_STATE_SEQ_START;
583
584         return CYAML_ERROR_NONE;
585 }
586
587 static enum cYAML_handler_error yaml_entry_token(yaml_token_t *token,
588                                                  struct cYAML_tree_node *tree)
589 {
590         struct cYAML *obj;
591
592         if (tree->state != TREE_STATE_SEQ_START &&
593             tree->state != TREE_STATE_BLK_STARTED &&
594             tree->state != TREE_STATE_VALUE)
595                 return CYAML_ERROR_UNEXPECTED_STATE;
596
597         if (tree->state == TREE_STATE_SEQ_START) {
598                 obj = create_child(tree->cur);
599
600                 if (cYAML_ll_push(tree->cur, NULL, &tree->ll))
601                         return CYAML_ERROR_OUT_OF_MEM;
602
603                 tree->cur = obj;
604         } else {
605                 tree->cur = create_sibling(tree->cur);
606                 tree->state = TREE_STATE_SEQ_START;
607         }
608
609         return CYAML_ERROR_NONE;
610 }
611
612 static enum cYAML_handler_error
613 yaml_blk_mapping_start(yaml_token_t *token,
614                        struct cYAML_tree_node *tree)
615 {
616         struct cYAML *obj;
617
618         if (tree->state != TREE_STATE_VALUE &&
619             tree->state != TREE_STATE_INITED &&
620             tree->state != TREE_STATE_SEQ_START &&
621             tree->state != TREE_STATE_TREE_STARTED)
622                 return CYAML_ERROR_UNEXPECTED_STATE;
623
624         /* block_mapping_start means we're entering another block
625          * indentation, so we need to go one level deeper
626          * create a child of cur */
627         obj = create_child(tree->cur);
628
629         /* push cur on the stack */
630         if (cYAML_ll_push(tree->cur, NULL, &tree->ll))
631                 return CYAML_ERROR_OUT_OF_MEM;
632
633         /* adding the new child to cur */
634         tree->cur = obj;
635
636         tree->state = TREE_STATE_BLK_STARTED;
637
638         tree->from_blk_map_start = 1;
639
640         return CYAML_ERROR_NONE;
641 }
642
643 static enum cYAML_handler_error yaml_block_end(yaml_token_t *token,
644                                                struct cYAML_tree_node *tree)
645 {
646         if (tree->state != TREE_STATE_BLK_STARTED &&
647             tree->state != TREE_STATE_VALUE)
648                 return CYAML_ERROR_UNEXPECTED_STATE;
649
650         tree->cur = cYAML_ll_pop(&tree->ll, NULL);
651
652         /* if you have popped all the way to the top level, then move to
653          * the complete state. */
654         if (cYAML_ll_count(&tree->ll) == 0)
655                 tree->state = TREE_STATE_COMPLETE;
656         else if (tree->state == TREE_STATE_VALUE)
657                 tree->state = TREE_STATE_BLK_STARTED;
658
659         return CYAML_ERROR_NONE;
660 }
661
662 static enum cYAML_handler_error yaml_not_supported(yaml_token_t *token,
663                                                    struct cYAML_tree_node *tree)
664 {
665         return CYAML_ERROR_NOT_SUPPORTED;
666 }
667
668 static bool clean_usr_data(struct cYAML *node, void *usr_data, void **out)
669 {
670         cYAML_user_data_free_cb free_cb = usr_data;
671
672         if (free_cb && node && node->cy_user_data) {
673                 free_cb(node->cy_user_data);
674                 node->cy_user_data = NULL;
675         }
676
677         return true;
678 }
679
680 static bool free_node(struct cYAML *node, void *user_data, void **out)
681 {
682         if (!node)
683                 return true;
684
685         if (node->cy_type == CYAML_TYPE_STRING)
686                 free(node->cy_valuestring);
687         if (node->cy_string)
688                 free(node->cy_string);
689
690         free(node);
691         return true;
692 }
693
694 static bool find_obj_iter(struct cYAML *node, void *usr_data, void **out)
695 {
696         char *name = usr_data;
697
698         if (node != NULL && node->cy_string != NULL &&
699             strcmp(node->cy_string, name) == 0) {
700                 *out = node;
701                 return false;
702         }
703
704         return true;
705 }
706
707 struct cYAML *cYAML_get_object_item(struct cYAML *parent, const char *name)
708 {
709         struct cYAML *node = parent, *found = NULL;
710
711         if (!node || !name)
712                 return NULL;
713
714         if (node->cy_string) {
715                 if (strcmp(node->cy_string, name) == 0)
716                         return node;
717         }
718
719         if (node->cy_child)
720                 found = cYAML_get_object_item(node->cy_child, name);
721
722         if (!found && node->cy_next)
723                 found = cYAML_get_object_item(node->cy_next, name);
724
725         return found;
726 }
727
728 struct cYAML *cYAML_get_next_seq_item(struct cYAML *seq, struct cYAML **itm)
729 {
730         if (*itm != NULL && (*itm)->cy_next != NULL) {
731                 *itm = (*itm)->cy_next;
732                 return *itm;
733         }
734
735         if (*itm == NULL && seq->cy_type == CYAML_TYPE_ARRAY) {
736                 *itm = seq->cy_child;
737                 return *itm;
738         }
739
740         return NULL;
741 }
742
743 bool cYAML_is_sequence(struct cYAML *node)
744 {
745         return (node != NULL ? node->cy_type == CYAML_TYPE_ARRAY : 0);
746 }
747
748 void cYAML_tree_recursive_walk(struct cYAML *node, cYAML_walk_cb cb,
749                                       bool cb_first,
750                                       void *usr_data,
751                                       void **out)
752 {
753         if (node == NULL)
754                 return;
755
756         if (cb_first) {
757                 if (!cb(node, usr_data, out))
758                         return;
759         }
760
761         if (node->cy_child)
762                 cYAML_tree_recursive_walk(node->cy_child, cb,
763                                           cb_first, usr_data, out);
764
765         if (node->cy_next)
766                 cYAML_tree_recursive_walk(node->cy_next, cb,
767                                           cb_first, usr_data, out);
768
769         if (!cb_first) {
770                 if (!cb(node, usr_data, out))
771                         return;
772         }
773 }
774
775 struct cYAML *cYAML_find_object(struct cYAML *root, const char *name)
776 {
777         struct cYAML *found = NULL;
778
779         cYAML_tree_recursive_walk(root, find_obj_iter, true,
780                                   (void *)name, (void **)&found);
781
782         return found;
783 }
784
785 void cYAML_clean_usr_data(struct cYAML *node, cYAML_user_data_free_cb free_cb)
786 {
787         cYAML_tree_recursive_walk(node, clean_usr_data, false, free_cb, NULL);
788 }
789
790 void cYAML_free_tree(struct cYAML *node)
791 {
792         cYAML_tree_recursive_walk(node, free_node, false, NULL, NULL);
793 }
794
795 static inline void print_simple(FILE *f, struct cYAML *node,
796                                 struct cYAML_print_info *cpi)
797 {
798         int level = cpi->level;
799         int ind = cpi->extra_ind;
800
801         if (cpi->array_first_elem)
802                 fprintf(f, "%*s- ", INDENT * level, "");
803
804         fprintf(f, "%*s""%s: %" PRId64 "\n", (cpi->array_first_elem) ? 0 :
805                 INDENT * level + ind, "", node->cy_string,
806                 node->cy_valueint);
807 }
808
809 static void print_string(FILE *f, struct cYAML *node,
810                          struct cYAML_print_info *cpi)
811 {
812         char *new_line;
813         int level = cpi->level;
814         int ind = cpi->extra_ind;
815
816         if (cpi->array_first_elem)
817                 fprintf(f, "%*s- ", INDENT * level, "");
818
819         new_line = strchr(node->cy_valuestring, '\n');
820         if (new_line == NULL)
821                 fprintf(f, "%*s""%s: %s\n", (cpi->array_first_elem) ?
822                         0 : INDENT * level + ind, "",
823                         node->cy_string, node->cy_valuestring);
824         else {
825                 int indent = 0;
826                 fprintf(f, "%*s""%s: ", (cpi->array_first_elem) ?
827                         0 : INDENT * level + ind, "",
828                         node->cy_string);
829                 char *l = node->cy_valuestring;
830                 while (new_line) {
831                         *new_line = '\0';
832                         fprintf(f, "%*s""%s\n", indent, "", l);
833                         indent = INDENT * level + ind +
834                                   strlen(node->cy_string) + 2;
835                         *new_line = '\n';
836                         l = new_line+1;
837                         new_line = strchr(l, '\n');
838                 }
839                 fprintf(f, "%*s""%s\n", indent, "", l);
840         }
841 }
842
843 static void print_number(FILE *f, struct cYAML *node,
844                          struct cYAML_print_info *cpi)
845 {
846         double d = node->cy_valuedouble;
847         int level = cpi->level;
848         int ind = cpi->extra_ind;
849
850         if (cpi->array_first_elem)
851                 fprintf(f, "%*s- ", INDENT * level, "");
852
853         if ((fabs(((double)node->cy_valueint) - d) <= DBL_EPSILON) &&
854             (d <= INT_MAX) && (d >= INT_MIN))
855                 fprintf(f, "%*s""%s: %" PRId64 "\n", (cpi->array_first_elem) ? 0 :
856                         INDENT * level + ind, "",
857                         node->cy_string, node->cy_valueint);
858         else {
859                 if ((fabs(floor(d) - d) <= DBL_EPSILON) &&
860                     (fabs(d) < 1.0e60))
861                         fprintf(f, "%*s""%s: %.0f\n",
862                                 (cpi->array_first_elem) ? 0 :
863                                 INDENT * level + ind, "",
864                                 node->cy_string, d);
865                 else if ((fabs(d) < 1.0e-6) || (fabs(d) > 1.0e9))
866                         fprintf(f, "%*s""%s: %e\n",
867                                 (cpi->array_first_elem) ? 0 :
868                                 INDENT * level + ind, "",
869                                 node->cy_string, d);
870                 else
871                         fprintf(f, "%*s""%s: %f\n",
872                                 (cpi->array_first_elem) ? 0 :
873                                 INDENT * level + ind, "",
874                                 node->cy_string, d);
875         }
876 }
877
878 static void print_object(FILE *f, struct cYAML *node,
879                          struct list_head *stack,
880                          struct cYAML_print_info *cpi)
881 {
882         struct cYAML_print_info print_info;
883         struct cYAML *child = node->cy_child;
884
885         if (node->cy_string != NULL)
886                 fprintf(f, "%*s""%s%s:\n", (cpi->array_first_elem) ?
887                         INDENT * cpi->level :
888                         INDENT * cpi->level + cpi->extra_ind,
889                         "", (cpi->array_first_elem) ? "- " : "",
890                         node->cy_string);
891
892         print_info.level = (node->cy_string != NULL) ? cpi->level + 1 :
893           cpi->level;
894         print_info.array_first_elem = (node->cy_string == NULL) ?
895           cpi->array_first_elem : 0;
896         print_info.extra_ind = (cpi->array_first_elem) ? EXTRA_IND :
897           cpi->extra_ind;
898
899         while (child) {
900                 if (cYAML_ll_push(child, &print_info, stack) != 0)
901                         return;
902                 print_value(f, stack);
903                 print_info.array_first_elem = 0;
904                 child = child->cy_next;
905         }
906 }
907
908 static void print_array(FILE *f, struct cYAML *node,
909                         struct list_head *stack,
910                         struct cYAML_print_info *cpi)
911 {
912         struct cYAML_print_info print_info;
913         struct cYAML *child = node->cy_child;
914
915         if (node->cy_string != NULL) {
916                 fprintf(f, "%*s""%s:\n", INDENT * cpi->level + cpi->extra_ind,
917                         "", node->cy_string);
918         }
919
920         print_info.level = (node->cy_string != NULL) ? cpi->level + 1 :
921           cpi->level;
922         print_info.array_first_elem =  1;
923         print_info.extra_ind = EXTRA_IND;
924
925         while (child) {
926                 if (cYAML_ll_push(child, &print_info, stack) != 0)
927                         return;
928                 print_value(f, stack);
929                 child = child->cy_next;
930         }
931 }
932
933 static void print_value(FILE *f, struct list_head *stack)
934 {
935         struct cYAML_print_info *cpi = NULL;
936         struct cYAML *node = cYAML_ll_pop(stack, &cpi);
937
938         if (node == NULL)
939                 return;
940
941         switch (node->cy_type) {
942         case CYAML_TYPE_FALSE:
943         case CYAML_TYPE_TRUE:
944         case CYAML_TYPE_NULL:
945                 print_simple(f, node, cpi);
946                 break;
947         case CYAML_TYPE_STRING:
948                 print_string(f, node, cpi);
949                 break;
950         case CYAML_TYPE_NUMBER:
951                 print_number(f, node, cpi);
952                 break;
953         case CYAML_TYPE_ARRAY:
954                 print_array(f, node, stack, cpi);
955                 break;
956         case CYAML_TYPE_OBJECT:
957                 print_object(f, node, stack, cpi);
958                 break;
959         default:
960         break;
961         }
962
963         if (cpi != NULL)
964                 free(cpi);
965 }
966
967 void cYAML_print_tree(struct cYAML *node)
968 {
969         struct cYAML_print_info print_info;
970         struct list_head list;
971
972         INIT_LIST_HEAD(&list);
973
974         if (node == NULL)
975                 return;
976
977         memset(&print_info, 0, sizeof(struct cYAML_print_info));
978
979         if (cYAML_ll_push(node, &print_info, &list) == 0)
980                 print_value(stdout, &list);
981 }
982
983 void cYAML_print_tree2file(FILE *f, struct cYAML *node)
984 {
985         struct cYAML_print_info print_info;
986         struct list_head list;
987
988         INIT_LIST_HEAD(&list);
989
990         if (node == NULL)
991                 return;
992
993         memset(&print_info, 0, sizeof(struct cYAML_print_info));
994
995         if (cYAML_ll_push(node, &print_info, &list) == 0)
996                 print_value(f, &list);
997 }
998
999 static struct cYAML *insert_item(struct cYAML *parent, char *key,
1000                                  enum cYAML_object_type type)
1001 {
1002         struct cYAML *node = calloc(1, sizeof(*node));
1003
1004         if (node == NULL)
1005                 return NULL;
1006
1007         if (key != NULL)
1008                 node->cy_string = strdup(key);
1009
1010         node->cy_type = type;
1011
1012         cYAML_insert_child(parent, node);
1013
1014         return node;
1015 }
1016
1017 struct cYAML *cYAML_create_seq(struct cYAML *parent, char *key)
1018 {
1019         return insert_item(parent, key, CYAML_TYPE_ARRAY);
1020 }
1021
1022 struct cYAML *cYAML_create_seq_item(struct cYAML *seq)
1023 {
1024         return insert_item(seq, NULL, CYAML_TYPE_OBJECT);
1025 }
1026
1027 struct cYAML *cYAML_create_object(struct cYAML *parent, char *key)
1028 {
1029         return insert_item(parent, key, CYAML_TYPE_OBJECT);
1030 }
1031
1032 struct cYAML *cYAML_create_string(struct cYAML *parent, char *key, char *value)
1033 {
1034         struct cYAML *node = calloc(1, sizeof(*node));
1035         if (node == NULL)
1036                 return NULL;
1037
1038         node->cy_string = strdup(key);
1039         node->cy_valuestring = strdup(value);
1040         node->cy_type = CYAML_TYPE_STRING;
1041
1042         cYAML_insert_child(parent, node);
1043
1044         return node;
1045 }
1046
1047 struct cYAML *cYAML_create_number(struct cYAML *parent, char *key, double value)
1048 {
1049         struct cYAML *node = calloc(1, sizeof(*node));
1050         if (node == NULL)
1051                 return NULL;
1052
1053         node->cy_string = strdup(key);
1054         node->cy_valuedouble = value;
1055         node->cy_valueint = (int)value;
1056         node->cy_type = CYAML_TYPE_NUMBER;
1057
1058         cYAML_insert_child(parent, node);
1059
1060         return node;
1061 }
1062
1063 void cYAML_insert_child(struct cYAML *parent, struct cYAML *node)
1064 {
1065         struct cYAML *cur;
1066
1067         if (parent && node) {
1068                 if (parent->cy_child == NULL) {
1069                         parent->cy_child = node;
1070                         return;
1071                 }
1072
1073                 cur = parent->cy_child;
1074
1075                 while (cur->cy_next)
1076                         cur = cur->cy_next;
1077
1078                 cur->cy_next = node;
1079                 node->cy_prev = cur;
1080         }
1081 }
1082
1083 void cYAML_insert_sibling(struct cYAML *root, struct cYAML *sibling)
1084 {
1085         struct cYAML *last = NULL;
1086         if (root == NULL || sibling == NULL)
1087                 return;
1088
1089         last = root;
1090         while (last->cy_next != NULL)
1091                 last = last->cy_next;
1092
1093         last->cy_next = sibling;
1094 }
1095
1096 void cYAML_build_error(int rc, int seq_no, char *cmd,
1097                        char *entity, char *err_str,
1098                        struct cYAML **root)
1099 {
1100         struct cYAML *r = NULL, *err, *s, *itm, *cmd_obj;
1101         if (root == NULL)
1102                 return;
1103
1104         /* add to the tail of the root that's passed in */
1105         if ((*root) == NULL) {
1106                 *root = cYAML_create_object(NULL, NULL);
1107                 if ((*root) == NULL)
1108                         goto failed;
1109         }
1110
1111         r = *root;
1112
1113         /* look for the command */
1114         cmd_obj = cYAML_get_object_item(r, (const char *)cmd);
1115         if (cmd_obj != NULL && cmd_obj->cy_type == CYAML_TYPE_ARRAY)
1116                 itm = cYAML_create_seq_item(cmd_obj);
1117         else if (cmd_obj == NULL) {
1118                 s = cYAML_create_seq(r, cmd);
1119                 itm = cYAML_create_seq_item(s);
1120         } else if (cmd_obj != NULL && cmd_obj->cy_type != CYAML_TYPE_ARRAY)
1121                 goto failed;
1122
1123         err = cYAML_create_object(itm, entity);
1124         if (err == NULL)
1125                 goto failed;
1126
1127         if (seq_no >= 0 &&
1128             cYAML_create_number(err, "seq_no", seq_no) == NULL)
1129                 goto failed;
1130
1131         if (cYAML_create_number(err, "errno", rc) == NULL)
1132                 goto failed;
1133
1134         if (cYAML_create_string(err, "descr", err_str) == NULL)
1135                 goto failed;
1136
1137         return;
1138
1139 failed:
1140         /* Only reason we get here is if we run out of memory */
1141         cYAML_free_tree(r);
1142         r = NULL;
1143         fprintf(stderr, "error:\n\tfatal: out of memory\n");
1144 }
1145
1146 struct cYAML *cYAML_build_tree(char *yaml_file,
1147                                const char *yaml_blk,
1148                                size_t yaml_blk_size,
1149                                struct cYAML **err_rc,
1150                                bool debug)
1151 {
1152         yaml_parser_t parser;
1153         yaml_token_t token;
1154         struct cYAML_tree_node tree;
1155         enum cYAML_handler_error rc;
1156         yaml_token_type_t token_type;
1157         char err_str[256];
1158         FILE *input = NULL;
1159         int done = 0;
1160
1161         memset(&tree, 0, sizeof(struct cYAML_tree_node));
1162
1163         INIT_LIST_HEAD(&tree.ll);
1164
1165         /* Create the Parser object. */
1166         yaml_parser_initialize(&parser);
1167
1168         /* file always takes precedence */
1169         if (yaml_file != NULL) {
1170                 /* Set a file input. */
1171                 input = fopen(yaml_file, "rb");
1172                 if (input == NULL) {
1173                         snprintf(err_str, sizeof(err_str),
1174                                 "Failed to open file: %s", yaml_file);
1175                         cYAML_build_error(-1, -1, "yaml", "builder",
1176                                           err_str,
1177                                           err_rc);
1178                         return NULL;
1179                 }
1180
1181                 yaml_parser_set_input_file(&parser, input);
1182         } else if (yaml_blk != NULL) {
1183                 yaml_parser_set_input_string(&parser,
1184                                              (const unsigned char *) yaml_blk,
1185                                              yaml_blk_size);
1186         } else
1187                 /* assume that we're getting our input froms stdin */
1188                 yaml_parser_set_input_file(&parser, stdin);
1189
1190         /* Read the event sequence. */
1191         while (!done) {
1192                 /*
1193                  * Go through the parser and build a cYAML representation
1194                  * of the passed in YAML text
1195                  */
1196                 yaml_parser_scan(&parser, &token);
1197
1198                 if (debug)
1199                         fprintf(stderr, "tree.state(%p:%d) = %s, token.type ="
1200                                         " %s: %s\n",
1201                                 &tree, tree.state, state_string[tree.state],
1202                                 token_type_string[token.type],
1203                                 (token.type == YAML_SCALAR_TOKEN) ?
1204                                 (char*)token.data.scalar.value : "");
1205                 rc = dispatch_tbl[token.type](&token, &tree);
1206                 if (rc != CYAML_ERROR_NONE) {
1207                         snprintf(err_str, sizeof(err_str),
1208                                 "Failed to handle token:%d "
1209                                 "[state=%d, rc=%d]",
1210                                 token.type, tree.state, rc);
1211                         cYAML_build_error(-1, -1, "yaml", "builder",
1212                                           err_str,
1213                                           err_rc);
1214                 }
1215                 /* Are we finished? */
1216                 done = (rc != CYAML_ERROR_NONE ||
1217                         token.type == YAML_STREAM_END_TOKEN ||
1218                         token.type == YAML_NO_TOKEN);
1219
1220                 token_type = token.type;
1221
1222                 yaml_token_delete(&token);
1223         }
1224
1225         /* Destroy the Parser object. */
1226         yaml_parser_delete(&parser);
1227
1228         if (input != NULL)
1229                 fclose(input);
1230
1231         if (token_type == YAML_STREAM_END_TOKEN &&
1232             rc == CYAML_ERROR_NONE)
1233                 return tree.root;
1234
1235         cYAML_free_tree(tree.root);
1236
1237         return NULL;
1238 }