Whamcloud - gitweb
dccce6c4fc309cd154774b2a69c68ed677be4811
[fs/lustre-release.git] / lnet / utils / cyaml / 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) 2013, 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/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 static void cYAML_ll_free(struct list_head *ll)
164 {
165         struct cYAML_ll *node, *tmp;
166
167         list_for_each_entry_safe(node, tmp, ll, list) {
168                 free(node->print_info);
169                 free(node);
170         }
171 }
172
173 static int cYAML_ll_push(struct cYAML *obj,
174                          const struct cYAML_print_info *print_info,
175                          struct list_head *list)
176 {
177         struct cYAML_ll *node = calloc(1, sizeof(*node));
178         if (node == NULL)
179                 return -1;
180
181         INIT_LIST_HEAD(&node->list);
182
183         if (print_info) {
184                 node->print_info = calloc(1, sizeof(*print_info));
185                 if (node->print_info == NULL) {
186                         free(node);
187                         return -1;
188                 }
189                 *node->print_info = *print_info;
190         }
191         node->obj = obj;
192
193         list_add(&node->list, list);
194
195         return 0;
196 }
197
198 static struct cYAML *cYAML_ll_pop(struct list_head *list,
199                                   struct cYAML_print_info **print_info)
200 {
201         struct cYAML_ll *pop;
202         struct cYAML *obj = NULL;
203
204         if (!list_empty(list)) {
205                 pop = list_entry(list->next, struct cYAML_ll, list);
206
207                 obj = pop->obj;
208                 if (print_info != NULL)
209                         *print_info = pop->print_info;
210                 list_del(&pop->list);
211
212                 if (print_info == NULL)
213                         free(pop->print_info);
214
215                 free(pop);
216         }
217         return obj;
218 }
219
220 static int cYAML_ll_count(struct list_head *ll)
221 {
222         int i = 0;
223         struct list_head *node;
224
225         list_for_each(node, ll)
226                 i++;
227
228         return i;
229 }
230
231 static int cYAML_tree_init(struct cYAML_tree_node *tree)
232 {
233         struct cYAML *obj = NULL, *cur = NULL;
234
235         if (tree == NULL)
236                 return -1;
237
238         obj = calloc(1, sizeof(*obj));
239         if (obj == NULL)
240                 return -1;
241
242         if (tree->root) {
243                 /* append the node */
244                 cur = tree->root;
245                 while (cur->cy_next != NULL)
246                         cur = cur->cy_next;
247                 cur->cy_next = obj;
248         } else {
249                 tree->root = obj;
250         }
251
252         obj->cy_type = CYAML_TYPE_OBJECT;
253
254         tree->cur = obj;
255         tree->state = TREE_STATE_COMPLETE;
256
257         /* free it and start anew */
258         if (!list_empty(&tree->ll))
259                 cYAML_ll_free(&tree->ll);
260
261         return 0;
262 }
263
264 static struct cYAML *create_child(struct cYAML *parent)
265 {
266         struct cYAML *obj;
267
268         if (parent == NULL)
269                 return NULL;
270
271         obj = calloc(1, sizeof(*obj));
272         if (obj == NULL)
273                 return NULL;
274
275         /* set the type to OBJECT and let the value change that */
276         obj->cy_type = CYAML_TYPE_OBJECT;
277
278         parent->cy_child = obj;
279
280         return obj;
281 }
282
283 static struct cYAML *create_sibling(struct cYAML *sibling)
284 {
285         struct cYAML *obj;
286
287         if (sibling == NULL)
288                 return NULL;
289
290         obj = calloc(1, sizeof(*obj));
291         if (obj == NULL)
292                 return NULL;
293
294         /* set the type to OBJECT and let the value change that */
295         obj->cy_type = CYAML_TYPE_OBJECT;
296
297         sibling->cy_next = obj;
298         obj->cy_prev = sibling;
299
300         return obj;
301 }
302
303 /* Parse the input text to generate a number,
304  * and populate the result into item. */
305 static bool parse_number(struct cYAML *item, const char *input)
306 {
307         double n = 0, sign = 1, scale = 0;
308         int subscale = 0, signsubscale = 1;
309         const char *num = input;
310
311         if (*num == '-') {
312                 sign = -1;
313                 num++;
314         }
315
316         if (*num == '0')
317                 num++;
318
319         if (*num >= '1' && *num <= '9') {
320                 do {
321                         n = (n * 10.0) + (*num++ - '0');
322                 } while (*num >= '0' && *num <= '9');
323         }
324
325         if (*num == '.' && num[1] >= '0' && num[1] <= '9') {
326                 num++;
327                 do {
328                         n = (n * 10.0) + (*num++ - '0');
329                         scale--;
330                 } while (*num >= '0' && *num <= '9');
331         }
332
333         if (*num == 'e' || *num == 'E') {
334                 num++;
335                 if (*num == '+') {
336                         num++;
337                 } else if (*num == '-') {
338                         signsubscale = -1;
339                         num++;
340                 }
341                 while (*num >= '0' && *num <= '9')
342                         subscale = (subscale * 10) + (*num++ - '0');
343         }
344
345         /* check to see if the entire string is consumed.  If not then
346          * that means this is a string with a number in it */
347         if (num != (input + strlen(input)))
348                 return false;
349
350         /* number = +/- number.fraction * 10^+/- exponent */
351         n = sign * n * pow(10.0, (scale + subscale * signsubscale));
352
353         item->cy_valuedouble = n;
354         item->cy_valueint = (int)n;
355         item->cy_type = CYAML_TYPE_NUMBER;
356
357         return true;
358 }
359
360 static int assign_type_value(struct cYAML *obj, const char *value)
361 {
362         if (value == NULL)
363                 return -1;
364
365         if (strcmp(value, "null") == 0)
366                 obj->cy_type = CYAML_TYPE_NULL;
367         else if (strcmp(value, "false") == 0) {
368                 obj->cy_type = CYAML_TYPE_FALSE;
369                 obj->cy_valueint = 0;
370         } else if (strcmp(value, "true") == 0) {
371                 obj->cy_type = CYAML_TYPE_TRUE;
372                 obj->cy_valueint = 1;
373         } else if (*value == '-' || (*value >= '0' && *value <= '9')) {
374                 if (parse_number(obj, value) == 0) {
375                         obj->cy_valuestring = strdup(value);
376                         obj->cy_type = CYAML_TYPE_STRING;
377                 }
378         } else {
379                 obj->cy_valuestring = strdup(value);
380                 obj->cy_type = CYAML_TYPE_STRING;
381         }
382
383         return 0;
384 }
385
386 /*
387  * yaml_handle_token
388  *  Builds the YAML tree rpresentation as the tokens are passed in
389  *
390  *  if token == STREAM_START && tree_state != COMPLETE
391  *    something wrong. fail.
392  *  else tree_state = INITIED
393  *  if token == DOCUMENT_START && tree_state != COMPLETE || INITED
394  *    something wrong, fail.
395  *  else tree_state = TREE_STARTED
396  *  if token == DOCUMENT_END
397  *    tree_state = INITED if no STREAM START, else tree_state = COMPLETE
398  *    erase everything on ll
399  *  if token == STREAM_END && tree_state != INITED
400  *    something wrong fail.
401  *  else tree_state = COMPLETED
402  *  if token == YAML_KEY_TOKEN && state != TREE_STARTED
403  *    something wrong, fail.
404  *  if token == YAML_SCALAR_TOKEN && state != KEY || VALUE
405  *    fail.
406  *  else if tree_state == KEY
407  *     create a new sibling under the current head of the ll (if ll is
408  *     empty insert the new node there and it becomes the root.)
409  *    add the scalar value in the "string"
410  *    tree_state = KEY_FILLED
411  *  else if tree_state == VALUE
412  *    try and figure out whether this is a double, int or string and store
413  *    it appropriately
414  *    state = TREE_STARTED
415  * else if token == YAML_BLOCK_MAPPING_START_TOKEN && tree_state != VALUE
416  *   fail
417  * else push the current node on the ll && state = TREE_STARTED
418  * if token == YAML_BLOCK_END_TOKEN && state != TREE_STARTED
419  *   fail.
420  * else pop the current token off the ll and make it the cur
421  * if token == YAML_VALUE_TOKEN && state != KEY_FILLED
422  *   fail.
423  * else state = VALUE
424  *
425  */
426 static enum cYAML_handler_error yaml_parse_error(yaml_token_t *token,
427                                                  struct cYAML_tree_node *tree)
428 {
429         return CYAML_ERROR_PARSE;
430 }
431
432 static enum cYAML_handler_error yaml_stream_start(yaml_token_t *token,
433                                                   struct cYAML_tree_node *tree)
434 {
435         enum cYAML_handler_error rc;
436
437         /* with each new stream initialize a new tree */
438         rc = cYAML_tree_init(tree);
439
440         if (rc != CYAML_ERROR_NONE)
441                 return rc;
442
443         tree->state = TREE_STATE_INITED;
444
445         return CYAML_ERROR_NONE;
446 }
447
448 static enum cYAML_handler_error yaml_stream_end(yaml_token_t *token,
449                                                 struct cYAML_tree_node *tree)
450 {
451         if (tree->state != TREE_STATE_TREE_STARTED)
452                 return CYAML_ERROR_UNEXPECTED_STATE;
453
454         tree->state = TREE_STATE_INITED;
455
456         return CYAML_ERROR_NONE;
457 }
458
459 static enum cYAML_handler_error
460 yaml_document_start(yaml_token_t *token, struct cYAML_tree_node *tree)
461 {
462         if (tree->state != TREE_STATE_INITED)
463                 return CYAML_ERROR_UNEXPECTED_STATE;
464
465         /* go to started state since we're expecting more tokens to come */
466         tree->state = TREE_STATE_TREE_STARTED;
467
468         return CYAML_ERROR_NONE;
469 }
470
471 static enum cYAML_handler_error yaml_document_end(yaml_token_t *token,
472                                                   struct cYAML_tree_node *tree)
473 {
474         if (tree->state != TREE_STATE_COMPLETE)
475                 return CYAML_ERROR_UNEXPECTED_STATE;
476
477         tree->state = TREE_STATE_TREE_STARTED;
478
479         return CYAML_ERROR_NONE;
480 }
481
482 static enum cYAML_handler_error yaml_key(yaml_token_t *token,
483                                          struct cYAML_tree_node *tree)
484 {
485         if (tree->state != TREE_STATE_BLK_STARTED &&
486             tree->state != TREE_STATE_VALUE)
487                 return CYAML_ERROR_UNEXPECTED_STATE;
488
489         if (tree->from_blk_map_start == 0 ||
490             tree->state == TREE_STATE_VALUE)
491                 tree->cur = create_sibling(tree->cur);
492
493         tree->from_blk_map_start = 0;
494
495         tree->state = TREE_STATE_KEY;
496
497         return CYAML_ERROR_NONE;
498 }
499
500 static enum cYAML_handler_error yaml_scalar(yaml_token_t *token,
501                                             struct cYAML_tree_node *tree)
502 {
503         if (tree->state == TREE_STATE_KEY) {
504                 /* assign the scalar value to the key that was created */
505                 tree->cur->cy_string =
506                   strdup((const char *)token->data.scalar.value);
507
508                 tree->state = TREE_STATE_KEY_FILLED;
509         } else if (tree->state == TREE_STATE_VALUE) {
510                 if (assign_type_value(tree->cur,
511                                       (char *)token->data.scalar.value))
512                         /* failed to assign a value */
513                         return CYAML_ERROR_BAD_VALUE;
514                 tree->state = TREE_STATE_BLK_STARTED;
515         } else {
516                 return CYAML_ERROR_UNEXPECTED_STATE;
517         }
518
519         return CYAML_ERROR_NONE;
520 }
521
522 static enum cYAML_handler_error yaml_value(yaml_token_t *token,
523                                            struct cYAML_tree_node *tree)
524 {
525         if (tree->state != TREE_STATE_KEY_FILLED)
526                 return CYAML_ERROR_UNEXPECTED_STATE;
527
528         tree->state = TREE_STATE_VALUE;
529
530         return CYAML_ERROR_NONE;
531 }
532
533 static enum cYAML_handler_error yaml_blk_seq_start(yaml_token_t *token,
534                                                    struct cYAML_tree_node *tree)
535 {
536         if (tree->state != TREE_STATE_VALUE)
537                 return CYAML_ERROR_UNEXPECTED_STATE;
538
539         /* Since a sequenc start event determines that this is the start
540          * of an array, then that means the current node we're at is an
541          * array and we need to flag it as such */
542         tree->cur->cy_type = CYAML_TYPE_ARRAY;
543         tree->state = TREE_STATE_SEQ_START;
544
545         return CYAML_ERROR_NONE;
546 }
547
548 static enum cYAML_handler_error yaml_entry_token(yaml_token_t *token,
549                                                  struct cYAML_tree_node *tree)
550 {
551         struct cYAML *obj;
552
553         if (tree->state != TREE_STATE_SEQ_START &&
554             tree->state != TREE_STATE_BLK_STARTED)
555                 return CYAML_ERROR_UNEXPECTED_STATE;
556
557         if (tree->state == TREE_STATE_SEQ_START) {
558                 obj = create_child(tree->cur);
559
560                 if (cYAML_ll_push(tree->cur, NULL, &tree->ll))
561                         return CYAML_ERROR_OUT_OF_MEM;
562
563                 tree->cur = obj;
564         } else {
565                 tree->cur = create_sibling(tree->cur);
566                 tree->state = TREE_STATE_SEQ_START;
567         }
568
569         return CYAML_ERROR_NONE;
570 }
571
572 static enum cYAML_handler_error
573 yaml_blk_mapping_start(yaml_token_t *token,
574                        struct cYAML_tree_node *tree)
575 {
576         struct cYAML *obj;
577
578         if (tree->state != TREE_STATE_VALUE &&
579             tree->state != TREE_STATE_INITED &&
580             tree->state != TREE_STATE_SEQ_START &&
581             tree->state != TREE_STATE_TREE_STARTED)
582                 return CYAML_ERROR_UNEXPECTED_STATE;
583
584         /* block_mapping_start means we're entering another block
585          * indentation, so we need to go one level deeper
586          * create a child of cur */
587         obj = create_child(tree->cur);
588
589         /* push cur on the stack */
590         if (cYAML_ll_push(tree->cur, NULL, &tree->ll))
591                 return CYAML_ERROR_OUT_OF_MEM;
592
593         /* adding the new child to cur */
594         tree->cur = obj;
595
596         tree->state = TREE_STATE_BLK_STARTED;
597
598         tree->from_blk_map_start = 1;
599
600         return CYAML_ERROR_NONE;
601 }
602
603 static enum cYAML_handler_error yaml_block_end(yaml_token_t *token,
604                                                struct cYAML_tree_node *tree)
605 {
606         if (tree->state != TREE_STATE_BLK_STARTED &&
607             tree->state != TREE_STATE_VALUE)
608                 return CYAML_ERROR_UNEXPECTED_STATE;
609
610         tree->cur = cYAML_ll_pop(&tree->ll, NULL);
611
612         /* if you have popped all the way to the top level, then move to
613          * the complete state. */
614         if (cYAML_ll_count(&tree->ll) == 0)
615                 tree->state = TREE_STATE_COMPLETE;
616         else if (tree->state == TREE_STATE_VALUE)
617                 tree->state = TREE_STATE_BLK_STARTED;
618
619         return CYAML_ERROR_NONE;
620 }
621
622 static enum cYAML_handler_error yaml_not_supported(yaml_token_t *token,
623                                                    struct cYAML_tree_node *tree)
624 {
625         return CYAML_ERROR_NOT_SUPPORTED;
626 }
627
628 static bool clean_usr_data(struct cYAML *node, void *usr_data, void **out)
629 {
630         cYAML_user_data_free_cb free_cb = usr_data;
631
632         if (free_cb && node && node->cy_user_data) {
633                 free_cb(node->cy_user_data);
634                 node->cy_user_data = NULL;
635         }
636
637         return true;
638 }
639
640 static bool free_node(struct cYAML *node, void *user_data, void **out)
641 {
642         if (node)
643                 free(node);
644
645         return true;
646 }
647
648 static bool find_obj_iter(struct cYAML *node, void *usr_data, void **out)
649 {
650         char *name = usr_data;
651
652         if (node != NULL && node->cy_string != NULL &&
653             strcmp(node->cy_string, name) == 0) {
654                 *out = node;
655                 return false;
656         }
657
658         return true;
659 }
660
661 struct cYAML *cYAML_get_object_item(struct cYAML *parent, const char *name)
662 {
663         struct cYAML *node;
664
665         if (parent == NULL || parent->cy_child == NULL || name == NULL)
666                 return NULL;
667
668         node = parent->cy_child;
669
670         while (node != NULL &&
671                 strcmp(node->cy_string, name) != 0) {
672                 node = node->cy_next;
673         }
674
675         return node;
676 }
677
678 struct cYAML *cYAML_get_next_seq_item(struct cYAML *seq, struct cYAML **itm)
679 {
680         if (*itm != NULL && (*itm)->cy_next != NULL) {
681                 *itm = (*itm)->cy_next;
682                 return *itm;
683         }
684
685         if (*itm == NULL && seq->cy_type == CYAML_TYPE_ARRAY) {
686                 *itm = seq->cy_child;
687                 return *itm;
688         }
689
690         return NULL;
691 }
692
693 bool cYAML_is_sequence(struct cYAML *node)
694 {
695         return (node != NULL ? node->cy_type == CYAML_TYPE_ARRAY : 0);
696 }
697
698 void cYAML_tree_recursive_walk(struct cYAML *node, cYAML_walk_cb cb,
699                                       bool cb_first,
700                                       void *usr_data,
701                                       void **out)
702 {
703         if (node == NULL)
704                 return;
705
706         if (cb_first) {
707                 if (!cb(node, usr_data, out))
708                         return;
709         }
710
711         if (node->cy_child)
712                 cYAML_tree_recursive_walk(node->cy_child, cb,
713                                           cb_first, usr_data, out);
714
715         if (node->cy_next)
716                 cYAML_tree_recursive_walk(node->cy_next, cb,
717                                           cb_first, usr_data, out);
718
719         if (!cb_first) {
720                 if (!cb(node, usr_data, out))
721                         return;
722         }
723 }
724
725 struct cYAML *cYAML_find_object(struct cYAML *root, const char *name)
726 {
727         struct cYAML *found = NULL;
728
729         cYAML_tree_recursive_walk(root, find_obj_iter, true,
730                                   (void *)name, (void **)&found);
731
732         return found;
733 }
734
735 void cYAML_clean_usr_data(struct cYAML *node, cYAML_user_data_free_cb free_cb)
736 {
737         cYAML_tree_recursive_walk(node, clean_usr_data, false, free_cb, NULL);
738 }
739
740 void cYAML_free_tree(struct cYAML *node)
741 {
742         cYAML_tree_recursive_walk(node, free_node, false, NULL, NULL);
743 }
744
745 static inline void print_simple(FILE *f, struct cYAML *node,
746                                 struct cYAML_print_info *cpi)
747 {
748         int level = cpi->level;
749         int ind = cpi->extra_ind;
750
751         if (cpi->array_first_elem)
752                 fprintf(f, "%*s- ", INDENT * level, "");
753
754         fprintf(f, "%*s""%s: %d\n", (cpi->array_first_elem) ? 0 :
755                 INDENT * level + ind, "", node->cy_string,
756                 node->cy_valueint);
757 }
758
759 static void print_string(FILE *f, struct cYAML *node,
760                          struct cYAML_print_info *cpi)
761 {
762         char *new_line;
763         int level = cpi->level;
764         int ind = cpi->extra_ind;
765
766         if (cpi->array_first_elem)
767                 fprintf(f, "%*s- ", INDENT * level, "");
768
769         new_line = strchr(node->cy_valuestring, '\n');
770         if (new_line == NULL)
771                 fprintf(f, "%*s""%s: %s\n", (cpi->array_first_elem) ?
772                         0 : INDENT * level + ind, "",
773                         node->cy_string, node->cy_valuestring);
774         else {
775                 int indent = 0;
776                 fprintf(f, "%*s""%s: ", (cpi->array_first_elem) ?
777                         0 : INDENT * level + ind, "",
778                         node->cy_string);
779                 char *l = node->cy_valuestring;
780                 while (new_line) {
781                         *new_line = '\0';
782                         fprintf(f, "%*s""%s\n", indent, "", l);
783                         indent = INDENT * level + ind +
784                                   strlen(node->cy_string) + 2;
785                         *new_line = '\n';
786                         l = new_line+1;
787                         new_line = strchr(l, '\n');
788                 }
789                 fprintf(f, "%*s""%s\n", indent, "", l);
790         }
791 }
792
793 static void print_number(FILE *f, struct cYAML *node,
794                          struct cYAML_print_info *cpi)
795 {
796         double d = node->cy_valuedouble;
797         int level = cpi->level;
798         int ind = cpi->extra_ind;
799
800         if (cpi->array_first_elem)
801                 fprintf(f, "%*s- ", INDENT * level, "");
802
803         if ((fabs(((double)node->cy_valueint) - d) <= DBL_EPSILON) &&
804             (d <= INT_MAX) && (d >= INT_MIN))
805                 fprintf(f, "%*s""%s: %d\n", (cpi->array_first_elem) ? 0 :
806                         INDENT * level + ind, "",
807                         node->cy_string, node->cy_valueint);
808         else {
809                 if ((fabs(floor(d) - d) <= DBL_EPSILON) &&
810                     (fabs(d) < 1.0e60))
811                         fprintf(f, "%*s""%s: %.0f\n",
812                                 (cpi->array_first_elem) ? 0 :
813                                 INDENT * level + ind, "",
814                                 node->cy_string, d);
815                 else if ((fabs(d) < 1.0e-6) || (fabs(d) > 1.0e9))
816                         fprintf(f, "%*s""%s: %e\n",
817                                 (cpi->array_first_elem) ? 0 :
818                                 INDENT * level + ind, "",
819                                 node->cy_string, d);
820                 else
821                         fprintf(f, "%*s""%s: %f\n",
822                                 (cpi->array_first_elem) ? 0 :
823                                 INDENT * level + ind, "",
824                                 node->cy_string, d);
825         }
826 }
827
828 static void print_object(FILE *f, struct cYAML *node,
829                          struct list_head *stack,
830                          struct cYAML_print_info *cpi)
831 {
832         struct cYAML_print_info print_info;
833         struct cYAML *child = node->cy_child;
834
835         if (node->cy_string != NULL)
836                 fprintf(f, "%*s""%s%s:\n", (cpi->array_first_elem) ?
837                         INDENT * cpi->level :
838                         INDENT * cpi->level + cpi->extra_ind,
839                         "", (cpi->array_first_elem) ? "- " : "",
840                         node->cy_string);
841
842         print_info.level = (node->cy_string != NULL) ? cpi->level + 1 :
843           cpi->level;
844         print_info.array_first_elem = (node->cy_string == NULL) ?
845           cpi->array_first_elem : 0;
846         print_info.extra_ind = (cpi->array_first_elem) ? EXTRA_IND :
847           cpi->extra_ind;
848
849         while (child) {
850                 if (cYAML_ll_push(child, &print_info, stack) != 0)
851                         return;
852                 print_value(f, stack);
853                 print_info.array_first_elem = 0;
854                 child = child->cy_next;
855         }
856 }
857
858 static void print_array(FILE *f, struct cYAML *node,
859                         struct list_head *stack,
860                         struct cYAML_print_info *cpi)
861 {
862         struct cYAML_print_info print_info;
863         struct cYAML *child = node->cy_child;
864
865         if (node->cy_string != NULL) {
866                 fprintf(f, "%*s""%s:\n", INDENT * cpi->level + cpi->extra_ind,
867                         "", node->cy_string);
868         }
869
870         print_info.level = (node->cy_string != NULL) ? cpi->level + 1 :
871           cpi->level;
872         print_info.array_first_elem =  1;
873         print_info.extra_ind = EXTRA_IND;
874
875         while (child) {
876                 if (cYAML_ll_push(child, &print_info, stack) != 0)
877                         return;
878                 print_value(f, stack);
879                 child = child->cy_next;
880         }
881 }
882
883 static void print_value(FILE *f, struct list_head *stack)
884 {
885         struct cYAML_print_info *cpi = NULL;
886         struct cYAML *node = cYAML_ll_pop(stack, &cpi);
887
888         switch (node->cy_type) {
889         case CYAML_TYPE_FALSE:
890         case CYAML_TYPE_TRUE:
891         case CYAML_TYPE_NULL:
892                 print_simple(f, node, cpi);
893                 break;
894         case CYAML_TYPE_STRING:
895                 print_string(f, node, cpi);
896                 break;
897         case CYAML_TYPE_NUMBER:
898                 print_number(f, node, cpi);
899                 break;
900         case CYAML_TYPE_ARRAY:
901                 print_array(f, node, stack, cpi);
902                 break;
903         case CYAML_TYPE_OBJECT:
904                 print_object(f, node, stack, cpi);
905                 break;
906         default:
907         break;
908         }
909
910         if (cpi != NULL)
911                 free(cpi);
912 }
913
914 void cYAML_print_tree(struct cYAML *node)
915 {
916         struct cYAML_print_info print_info;
917         struct list_head list;
918
919         INIT_LIST_HEAD(&list);
920
921         if (node == NULL)
922                 return;
923
924         memset(&print_info, 0, sizeof(struct cYAML_print_info));
925
926         if (cYAML_ll_push(node, &print_info, &list) == 0)
927                 print_value(stdout, &list);
928 }
929
930 void cYAML_print_tree2file(FILE *f, struct cYAML *node)
931 {
932         struct cYAML_print_info print_info;
933         struct list_head list;
934
935         INIT_LIST_HEAD(&list);
936
937         if (node == NULL)
938                 return;
939
940         memset(&print_info, 0, sizeof(struct cYAML_print_info));
941
942         if (cYAML_ll_push(node, &print_info, &list) == 0)
943                 print_value(f, &list);
944 }
945
946 static struct cYAML *insert_item(struct cYAML *parent, char *key,
947                                  enum cYAML_object_type type)
948 {
949         struct cYAML *node = calloc(1, sizeof(*node));
950
951         if (node == NULL)
952                 return NULL;
953
954         if (key != NULL)
955                 node->cy_string = strdup(key);
956
957         node->cy_type = type;
958
959         cYAML_insert_child(parent, node);
960
961         return node;
962 }
963
964 struct cYAML *cYAML_create_seq(struct cYAML *parent, char *key)
965 {
966         return insert_item(parent, key, CYAML_TYPE_ARRAY);
967 }
968
969 struct cYAML *cYAML_create_seq_item(struct cYAML *seq)
970 {
971         return insert_item(seq, NULL, CYAML_TYPE_OBJECT);
972 }
973
974 struct cYAML *cYAML_create_object(struct cYAML *parent, char *key)
975 {
976         return insert_item(parent, key, CYAML_TYPE_OBJECT);
977 }
978
979 struct cYAML *cYAML_create_string(struct cYAML *parent, char *key, char *value)
980 {
981         struct cYAML *node = calloc(1, sizeof(*node));
982         if (node == NULL)
983                 return NULL;
984
985         node->cy_string = strdup(key);
986         node->cy_valuestring = strdup(value);
987         node->cy_type = CYAML_TYPE_STRING;
988
989         cYAML_insert_child(parent, node);
990
991         return node;
992 }
993
994 struct cYAML *cYAML_create_number(struct cYAML *parent, char *key, double value)
995 {
996         struct cYAML *node = calloc(1, sizeof(*node));
997         if (node == NULL)
998                 return NULL;
999
1000         node->cy_string = strdup(key);
1001         node->cy_valuedouble = value;
1002         node->cy_valueint = (int)value;
1003         node->cy_type = CYAML_TYPE_NUMBER;
1004
1005         cYAML_insert_child(parent, node);
1006
1007         return node;
1008 }
1009
1010 void cYAML_insert_child(struct cYAML *parent, struct cYAML *node)
1011 {
1012         struct cYAML *cur;
1013
1014         if (parent && node) {
1015                 if (parent->cy_child == NULL) {
1016                         parent->cy_child = node;
1017                         return;
1018                 }
1019
1020                 cur = parent->cy_child;
1021
1022                 while (cur->cy_next)
1023                         cur = cur->cy_next;
1024
1025                 cur->cy_next = node;
1026                 node->cy_prev = cur;
1027         }
1028 }
1029
1030 void cYAML_insert_sibling(struct cYAML *root, struct cYAML *sibling)
1031 {
1032         struct cYAML *last = NULL;
1033         if (root == NULL || sibling == NULL)
1034                 return;
1035
1036         last = root;
1037         while (last->cy_next != NULL)
1038                 last = last->cy_next;
1039
1040         last->cy_next = sibling;
1041 }
1042
1043 void cYAML_build_error(int rc, int seq_no, char *cmd,
1044                        char *entity, char *err_str,
1045                        struct cYAML **root)
1046 {
1047         struct cYAML *r = NULL, *err, *s, *itm, *cmd_obj;
1048         if (root == NULL)
1049                 return;
1050
1051         /* add to the tail of the root that's passed in */
1052         if ((*root) == NULL) {
1053                 *root = cYAML_create_object(NULL, NULL);
1054                 if ((*root) == NULL)
1055                         goto failed;
1056         }
1057
1058         r = *root;
1059
1060         /* look for the command */
1061         cmd_obj = cYAML_get_object_item(r, (const char *)cmd);
1062         if (cmd_obj != NULL && cmd_obj->cy_type == CYAML_TYPE_ARRAY)
1063                 itm = cYAML_create_seq_item(cmd_obj);
1064         else if (cmd_obj == NULL) {
1065                 s = cYAML_create_seq(r, cmd);
1066                 itm = cYAML_create_seq_item(s);
1067         } else if (cmd_obj != NULL && cmd_obj->cy_type != CYAML_TYPE_ARRAY)
1068                 goto failed;
1069
1070         err = cYAML_create_object(itm, entity);
1071         if (err == NULL)
1072                 goto failed;
1073
1074         if (seq_no >= 0 &&
1075             cYAML_create_number(err, "seqno", seq_no) == NULL)
1076                 goto failed;
1077
1078         if (cYAML_create_number(err, "errno", rc) == NULL)
1079                 goto failed;
1080
1081         if (cYAML_create_string(err, "descr", err_str) == NULL)
1082                 goto failed;
1083
1084         return;
1085
1086 failed:
1087         cYAML_free_tree(r);
1088         r = NULL;
1089 }
1090
1091 struct cYAML *cYAML_build_tree(char *yaml_file,
1092                                const char *yaml_blk,
1093                                size_t yaml_blk_size,
1094                                struct cYAML **err_rc)
1095 {
1096         yaml_parser_t parser;
1097         yaml_token_t token;
1098         struct cYAML_tree_node tree;
1099         enum cYAML_handler_error rc;
1100         yaml_token_type_t token_type;
1101         char err_str[256];
1102         FILE *input = NULL;
1103         int done = 0;
1104
1105         memset(&tree, 0, sizeof(struct cYAML_tree_node));
1106
1107         INIT_LIST_HEAD(&tree.ll);
1108
1109         /* Create the Parser object. */
1110         yaml_parser_initialize(&parser);
1111
1112         /* file alwyas takes precedence */
1113         if (yaml_file != NULL) {
1114                 /* Set a file input. */
1115                 input = fopen(yaml_file, "rb");
1116                 if (input == NULL) {
1117                         snprintf(err_str, sizeof(err_str),
1118                                 "Failed to open file: %s", yaml_file);
1119                         cYAML_build_error(-1, -1, "yaml", "builder",
1120                                           err_str,
1121                                           err_rc);
1122                         return NULL;
1123                 }
1124
1125                 yaml_parser_set_input_file(&parser, input);
1126         } else if (yaml_blk != NULL) {
1127                 yaml_parser_set_input_string(&parser,
1128                                              (const unsigned char *) yaml_blk,
1129                                              yaml_blk_size);
1130         } else
1131                 /* assume that we're getting our input froms stdin */
1132                 yaml_parser_set_input_file(&parser, stdin);
1133
1134         /* Read the event sequence. */
1135         while (!done) {
1136                 /*
1137                 * Go through the parser and build a cYAML representation
1138                 * of the passed in YAML text
1139                 */
1140                 yaml_parser_scan(&parser, &token);
1141
1142                 rc = dispatch_tbl[token.type](&token, &tree);
1143                 if (rc != CYAML_ERROR_NONE) {
1144                         snprintf(err_str, sizeof(err_str),
1145                                 "Failed to handle token:%d "
1146                                 "[state=%d, rc=%d]",
1147                                 token.type, tree.state, rc);
1148                         cYAML_build_error(-1, -1, "yaml", "builder",
1149                                           err_str,
1150                                           err_rc);
1151                 }
1152                 /* Are we finished? */
1153                 done = (rc != CYAML_ERROR_NONE ||
1154                         token.type == YAML_STREAM_END_TOKEN ||
1155                         token.type == YAML_NO_TOKEN);
1156
1157                 token_type = token.type;
1158
1159                 yaml_token_delete(&token);
1160         }
1161
1162         /* Destroy the Parser object. */
1163         yaml_parser_delete(&parser);
1164
1165         if (input != NULL)
1166                 fclose(input);
1167
1168         if (token_type == YAML_STREAM_END_TOKEN &&
1169             rc == CYAML_ERROR_NONE)
1170                 return tree.root;
1171
1172         cYAML_free_tree(tree.root);
1173
1174         return NULL;
1175 }