summaryrefslogtreecommitdiffstats
path: root/ini/ini_configobj.c
blob: 603aaf421147fd0b01d057763b7eb544aafc37d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
/*
    INI LIBRARY

    Module represents interface to the main INI object.

    Copyright (C) Dmitri Pal <dpal@redhat.com> 2010

    INI Library is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    INI Library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with INI Library.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "config.h"
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
/* For error text */
#include <libintl.h>
#define _(String) gettext (String)
#include "trace.h"
#include "collection.h"
#include "collection_tools.h"
#include "ini_configobj.h"
#include "ini_config_priv.h"
#include "ini_defines.h"
#include "ini_valueobj.h"
#include "ini_configobj.h"

/* Internal structure used during the merge operation */
struct merge_data {
    struct collection_item *ci;
    uint32_t flags;
    int error;
    int found;
};

/* Callback */
void ini_cleanup_cb(const char *property,
                    int property_len,
                    int type,
                    void *data,
                    int length,
                    void *custom_data)
{
    struct value_obj *vo = NULL;

    TRACE_FLOW_ENTRY();
    TRACE_INFO_STRING("Cleaning ", property);

    /* Banary items are the values */
    if(type == COL_TYPE_BINARY) {
        vo = *((struct value_obj **)(data));
        value_destroy(vo);
    }

    TRACE_FLOW_EXIT();
}

/* Clean the search state */
void ini_config_clean_state(struct ini_cfgobj *ini_config)
{
    TRACE_FLOW_ENTRY();

    if (ini_config) {
        if (ini_config->iterator) col_unbind_iterator(ini_config->iterator);
        ini_config->iterator = NULL;
        free(ini_config->section);
        ini_config->section = NULL;
        free(ini_config->name);
        ini_config->name = NULL;
        ini_config->section_len = 0;
        ini_config->name_len = 0;
    }

    TRACE_FLOW_EXIT();
}



/* Traverse the collection and clean the object */
void ini_config_destroy(struct ini_cfgobj *ini_config)
{
    TRACE_FLOW_ENTRY();

    ini_config_clean_state(ini_config);

    if (ini_config) {
        if (ini_config->cfg) {

            col_destroy_collection_with_cb(ini_config->cfg,
                                           ini_cleanup_cb,
                                           NULL);
        }
        if (ini_config->last_comment) {
            ini_comment_destroy(ini_config->last_comment);
        }

        if (ini_config->error_list) {
            col_destroy_collection(ini_config->error_list);
        }

        free(ini_config);
    }

    TRACE_FLOW_EXIT();
}

/* Create a config object */
int ini_config_create(struct ini_cfgobj **ini_config)
{
    int error = EOK;
    struct ini_cfgobj *new_co = NULL;

    TRACE_FLOW_ENTRY();

    if (!ini_config) {
        TRACE_ERROR_NUMBER("Invalid argument", EINVAL);
        return EINVAL;
    }

    new_co = malloc(sizeof(struct ini_cfgobj));
    if (!new_co) {
        TRACE_ERROR_NUMBER("Failed to allocate memory", ENOMEM);
        return ENOMEM;
    }

    new_co->cfg = NULL;
    new_co->boundary = INI_WRAP_BOUNDARY;
    new_co->last_comment = NULL;
    new_co->section = NULL;
    new_co->name = NULL;
    new_co->section_len = 0;
    new_co->name_len = 0;
    new_co->iterator = NULL;
    new_co->error_list = NULL;
    new_co->count = 0;

    /* Create a collection to hold configuration data */
    error = col_create_collection(&(new_co->cfg),
                                  INI_CONFIG_NAME,
                                  COL_CLASS_INI_CONFIG);
    if (error != EOK) {
        TRACE_ERROR_NUMBER("Failed to create collection.", error);
        ini_config_destroy(new_co);
        return error;
    }

    /* Create error list collection */
    error = col_create_collection(&(new_co->error_list),
                                  INI_ERROR,
                                  COL_CLASS_INI_PERROR);
    if (error) {
        TRACE_ERROR_NUMBER("Failed to create error list", error);
        ini_config_destroy(new_co);
        return error;
    }

    *ini_config = new_co;

    TRACE_FLOW_EXIT();
    return error;
}

/* Callback to set the boundary */
int ini_boundary_cb(const char *property,
                     int property_len,
                     int type,
                     void *data,
                     int length,
                     void *custom_data,
                     int *dummy)
{
    int error = EOK;
    struct value_obj *vo = NULL;
    uint32_t boundary;

    TRACE_FLOW_ENTRY();

    boundary = *((uint32_t *)(custom_data));
    /* Banary items are the values */
    if(type == COL_TYPE_BINARY) {
        vo = *((struct value_obj **)(data));
        error = value_set_boundary(vo, boundary);
    }

    TRACE_FLOW_EXIT();
    return error;
}

/* Set the folding boundary for multiline values.
 * Use before serializing and saving to a file if the
 * default boundary of 80 characters does not work for you.
 */
int ini_config_set_wrap(struct ini_cfgobj *ini_config,
                        uint32_t boundary)
{
    int error = EOK;

    TRACE_FLOW_ENTRY();

    if (!ini_config) {
        TRACE_ERROR_NUMBER("Invalid argument", EINVAL);
        return EINVAL;
    }

    ini_config->boundary = boundary;
    error = col_traverse_collection(ini_config->cfg,
                                    COL_TRAVERSE_DEFAULT,
                                    ini_boundary_cb,
                                    (void *)(&(ini_config->boundary)));
    if (error) {
        TRACE_ERROR_NUMBER("Failed to set wrapping boundary", error);
        return error;
    }


    TRACE_FLOW_EXIT();
    return error;
}

/* Configuration copy callback */
static int ini_copy_cb(struct collection_item *item,
                       void *ext_data,
                       int *skip)
{
    int error = EOK;
    struct value_obj *vo = NULL;
    struct value_obj *new_vo = NULL;

    TRACE_FLOW_ENTRY();

    *skip = 0;

    /* Binary items are the values */
    if(col_get_item_type(item) == COL_TYPE_BINARY) {
        vo = *((struct value_obj **)(col_get_item_data(item)));

        error = value_copy(vo, &new_vo);
        if (error) {
            TRACE_ERROR_NUMBER("Failed to copy value", error);
            return error;
        }

        error = col_modify_binary_item(item,
                                       NULL,
                                       &new_vo,
                                       sizeof(struct value_obj *));
        if (error) {
            TRACE_ERROR_NUMBER("Failed to copy value", error);
            value_destroy(new_vo);
            return error;
        }
    }

    TRACE_FLOW_EXIT();
    return error;
}

/* Copy configuration */
int ini_config_copy(struct ini_cfgobj *ini_config,
                    struct ini_cfgobj **ini_new)
{
    int error = EOK;
    struct ini_cfgobj *new_co = NULL;

    TRACE_FLOW_ENTRY();

    if ((!ini_config) ||
        (!ini_new)) {
        TRACE_ERROR_NUMBER("Invalid argument", EINVAL);
        return EINVAL;
    }

    /* Create a new configuration object */
    new_co = malloc(sizeof(struct ini_cfgobj));
    if (!new_co) {
        TRACE_ERROR_NUMBER("Failed to allocate memory", ENOMEM);
        return ENOMEM;
    }

    new_co->cfg = NULL;
    new_co->boundary = ini_config->boundary;
    new_co->last_comment = NULL;
    new_co->section = NULL;
    new_co->name = NULL;
    new_co->section_len = 0;
    new_co->name_len = 0;
    new_co->iterator = NULL;
    new_co->error_list = NULL;
    new_co->count = 0;

    error = col_copy_collection_with_cb(&(new_co->cfg),
                                        ini_config->cfg,
                                        INI_CONFIG_NAME,
                                        COL_COPY_NORMAL,
                                        ini_copy_cb,
                                        NULL);
    if (error) {
        TRACE_ERROR_NUMBER("Failed to copy collection", error);
        ini_config_destroy(new_co);
        return error;
    }

    if (ini_config->last_comment) {
        error = ini_comment_copy(ini_config->last_comment,
                                 &(new_co->last_comment));
        if (error) {
            TRACE_ERROR_NUMBER("Failed to copy comment", error);
            ini_config_destroy(new_co);
            return error;
        }
    }

    *ini_new = new_co;

    TRACE_FLOW_EXIT();
    return error;
}


/* Callback to process merging of the sections */
static int merge_section_handler(const char *property,
                                 int property_len,
                                 int type,
                                 void *data,
                                 int length,
                                 void *custom_data,
                                 int *dummy)
{
    int error = EOK;
    struct value_obj *vo = NULL;
    struct value_obj *new_vo = NULL;
    struct value_obj *vo_old = NULL;
    struct merge_data *passed_data;
    struct collection_item *acceptor = NULL;
    struct collection_item *item = NULL;
    unsigned insertmode;
    uint32_t mergemode;
    int suppress = 0;
    int doinsert = 0;

    TRACE_FLOW_ENTRY();

    if ((type != COL_TYPE_BINARY) ||
        ((type == COL_TYPE_BINARY) &&
         (strncmp(property, INI_SECTION_KEY,
                     sizeof(INI_SECTION_KEY)) == 0))) {
        /* Skip items we do not care about */
        TRACE_FLOW_EXIT();
        return EOK;
    }

    /* Get value */
    vo = *((struct value_obj **)(data));

    /* Copy it */
    error = value_copy(vo, &new_vo);
    if (error) {
        TRACE_ERROR_NUMBER("Failed to copy value", error);
        return error;
    }

    passed_data = (struct merge_data *)(custom_data);
    acceptor = passed_data->ci;
    mergemode = passed_data->flags & INI_MV2S_MASK;

    switch (mergemode) {
    case INI_MV2S_ERROR:     insertmode = COL_INSERT_DUPERROR;
                             doinsert = 1;
                             break;
    case INI_MV2S_PRESERVE:  insertmode = COL_INSERT_DUPERROR;
                             doinsert = 1;
                             suppress = 1;
                             break;
    case INI_MV2S_ALLOW:     insertmode = COL_INSERT_NOCHECK;
                             doinsert = 1;
                             break;
    case INI_MV2S_OVERWRITE: /* Special handling */
    case INI_MV2S_DETECT:
    default:
                             break;
    }

    /* Do not insert but search for dups first */
    if (!doinsert) {
        TRACE_INFO_STRING("Overwrite mode. Looking for:",
                          property);

        error = col_get_item(acceptor,
                             property,
                             COL_TYPE_BINARY,
                             COL_TRAVERSE_DEFAULT,
                             &item);

        if (error) {
            TRACE_ERROR_NUMBER("Failed searching for dup", error);
            value_destroy(new_vo);
            return error;
        }

        /* Check if there is a dup */
        if (item) {
            /* Check if we are in the detect mode */
            if (mergemode == INI_MV2S_DETECT) {
                passed_data->error = EEXIST;
                doinsert = 1;
                insertmode = COL_INSERT_NOCHECK;
            }
            else {

                /* We are in the OVERWRITE mode.
                 * Dup exists - update it.
                 */
                vo_old = *((struct value_obj **)(col_get_item_data(item)));
                error = col_modify_binary_item(item,
                                               NULL,
                                               &new_vo,
                                               sizeof(struct value_obj *));
                if (error) {
                    TRACE_ERROR_NUMBER("Failed updating the value", error);
                    value_destroy(new_vo);
                    return error;
                }

                /* If we failed to update it is better to leak then crash,
                 * so destroy original value only on the successful update.
                 */
                value_destroy(vo_old);
            }
        }
        else {
            /* No dup found so we can insert with no check */
            doinsert = 1;
            insertmode = COL_INSERT_NOCHECK;
        }
    }

    if (doinsert) {
        /* Add value to collection */
        error = col_insert_binary_property(acceptor,
                                           NULL,
                                           COL_DSP_END,
                                           NULL,
                                           0,
                                           insertmode,
                                           property,
                                           &new_vo,
                                           sizeof(struct value_obj *));
        if (error) {
            value_destroy(new_vo);

            if ((suppress) && (error == EEXIST)) {
                /* We are here is we do not allow dups
                 * but found one and need to ignore it.
                 */
                TRACE_INFO_STRING("Preseved exisitng value",
                                  property);
                error = 0;
            }
            else {
                /* Check if this is a critical error or not */
                if ((mergemode == INI_MV2S_ERROR) && (error == EEXIST)) {
                    TRACE_ERROR_NUMBER("Failed to add value object to "
                                       "the section in error mode ", error);
                    passed_data->error = EEXIST;
                    *dummy = 1;
                }
                else {
                    TRACE_ERROR_NUMBER("Failed to add value object"
                                       " to the section", error);
                    return error;
                }
            }
        }
    }

    TRACE_FLOW_EXIT();
    return error;
}


/* Internal function to merge two configs */
static int merge_two_sections(struct collection_item *donor,
                              struct collection_item *acceptor,
                              uint32_t flags)
{
    int error = EOK;
    struct merge_data data;

    TRACE_FLOW_ENTRY();

    data.ci = acceptor;
    data.flags = flags;
    data.error = 0;
    data.found = 0;

    error = col_traverse_collection(donor,
                                    COL_TRAVERSE_ONELEVEL,
                                    merge_section_handler,
                                    (void *)(&data));
    if (error) {
        TRACE_ERROR_NUMBER("Merge values failed", error);
        return error;
    }

    TRACE_FLOW_EXIT();
    return data.error;
}



/* Callback to process the accepting config */
static int acceptor_handler(const char *property,
                            int property_len,
                            int type,
                            void *data,
                            int length,
                            void *custom_data,
                            int *dummy)
{
    int error = EOK;
    struct merge_data *passed_data;
    struct collection_item *acceptor = NULL;
    struct collection_item *donor = NULL;
    uint32_t mergemode;

    TRACE_FLOW_ENTRY();

    /* This callback is called when the dup section is found */
    passed_data = (struct merge_data *)(custom_data);
    passed_data->found = 1;

    donor = passed_data->ci;
    acceptor = *((struct collection_item **)(data));

    mergemode = passed_data->flags & INI_MS_MASK;

    switch (mergemode) {
    case INI_MS_ERROR:      /* Report error and return */
                            TRACE_INFO_STRING("Error ",
                                              "duplicate section");
                            passed_data->error = EEXIST;
                            break;

    case INI_MS_PRESERVE:   /* Preserve what we have */
                            TRACE_INFO_STRING("Preserve mode", "");
                            break;

    case INI_MS_OVERWRITE:  /* Empty existing section */
                            TRACE_INFO_STRING("Ovewrite mode", "");
                            error = empty_section(acceptor);
                            if (error) {
                                TRACE_ERROR_NUMBER("Failed to "
                                                    "empty section",
                                                    error);
                                return error;
                            }
                            error = merge_two_sections(donor,
                                                       acceptor,
                                                       passed_data->flags);
                            if (error) {
                                TRACE_ERROR_NUMBER("Failed to merge "
                                                    "sections", error);
                                if (error == EEXIST) {
                                    passed_data->error = error;
                                }
                                return error;
                            }
                            break;

    case INI_MS_DETECT:     /* Detect mode */
                            TRACE_INFO_STRING("Detect mode", "");
                            passed_data->error = EEXIST;
                            error = merge_two_sections(donor,
                                                       acceptor,
                                                       passed_data->flags);
                            if (error) {
                                if (error != EEXIST) {
                                    TRACE_ERROR_NUMBER("Failed to merge "
                                                       "sections", error);
                                    return error;
                                }
                            }
                            break;

    case INI_MS_MERGE:      /* Merge */
    default:                TRACE_INFO_STRING("Merge mode", "");
                            error = merge_two_sections(donor,
                                                       acceptor,
                                                       passed_data->flags);
                            if (error) {
                                if (error != EEXIST) {
                                    TRACE_ERROR_NUMBER("Failed to merge "
                                                       "sections", error);
                                    return error;
                                }
                                passed_data->error = error;
                            }
                            break;
    }

    *dummy = 1;
    TRACE_FLOW_EXIT();
    return EOK;
}

/* Callback to process the donating config */
static int donor_handler(const char *property,
                         int property_len,
                         int type,
                         void *data,
                         int length,
                         void *custom_data,
                         int *dummy)
{
    int error = EOK;
    struct merge_data *passed_data;
    struct merge_data acceptor_data;
    struct collection_item *new_ci = NULL;

    TRACE_FLOW_ENTRY();

    *dummy = 0;

    /* Opaque data passed to callback is merge data */
    passed_data = (struct merge_data *)(custom_data);

    TRACE_INFO_STRING("Property: ", property);
    TRACE_INFO_NUMBER("Type is: ", type);
    TRACE_INFO_NUMBER("Flags: ", passed_data->flags);

    /* All sections are subcollections */
    if(type == COL_TYPE_COLLECTIONREF) {

        /* Prepare data for the next callback */
        acceptor_data.flags = passed_data->flags;
        acceptor_data.ci = *((struct collection_item **)(data));
        acceptor_data.error = 0;
        acceptor_data.found = 0;

        /* Try to find same section as the current one */
        error = col_get_item_and_do(passed_data->ci,
                                    property,
                                    COL_TYPE_COLLECTIONREF,
                                    COL_TRAVERSE_ONELEVEL,
                                    acceptor_handler,
                                    (void *)(&acceptor_data));
        if (error) {
            TRACE_ERROR_NUMBER("Critical error", error);
            return error;
        }

        /* Was duplicate found ? */
        if (acceptor_data.found) {
            /* Check for logical error. It can be only EEXIST */
            if (acceptor_data.error) {
                /* Save error anyway */
                passed_data->error = acceptor_data.error;
                /* If it is section DETECT or MERGE+DETECT */
                if (((passed_data->flags & INI_MS_MASK) == INI_MS_DETECT) ||
                    (((passed_data->flags & INI_MS_MASK) != INI_MS_ERROR) &&
                     ((passed_data->flags & INI_MV2S_MASK) ==
                       INI_MV2S_DETECT))) {
                    TRACE_INFO_NUMBER("Non-critical error",
                                      acceptor_data.error);
                }
                else {
                    /* In any other mode we need to stop */
                    TRACE_INFO_NUMBER("Merge error detected",
                                      acceptor_data.error);
                    /* Force stop */
                    *dummy = 1;
                }
            }
        }
        else {
            /* Not found? Then create a copy... */
            error = col_copy_collection_with_cb(&new_ci,
                                                acceptor_data.ci,
                                                NULL,
                                                COL_COPY_NORMAL,
                                                ini_copy_cb,
                                                NULL);
            if (error) {
                TRACE_ERROR_NUMBER("Failed to copy collection", error);
                return error;
            }

            /* ... and embed into the existing collection */
            error = col_add_collection_to_collection(passed_data->ci,
                                                     NULL,
                                                     NULL,
                                                     new_ci,
                                                     COL_ADD_MODE_EMBED);
            if (error) {
                TRACE_ERROR_NUMBER("Failed to copy collection", error);
                col_destroy_collection(new_ci);
                return error;
            }
        }
    }

    TRACE_FLOW_EXIT();
    return EOK;
}

static int merge_comment(struct ini_cfgobj *donor,
                         struct ini_cfgobj *acceptor)
{
    int error = EOK;

    TRACE_FLOW_ENTRY();

    if (donor->last_comment) {

        if (acceptor->last_comment) {

            error = ini_comment_add(donor->last_comment,
                                    acceptor->last_comment);
            if (error) {
                TRACE_ERROR_NUMBER("Merge comment failed", error);
                return error;
            }

        }
        else {
            error = ini_comment_copy(donor->last_comment,
                                     &(acceptor->last_comment));
            if (error) {
                TRACE_ERROR_NUMBER("Copy comment failed", error);
                return error;
            }
        }
    }

    TRACE_FLOW_EXIT();
    return EOK;
}



/* Internal function to merge two configs */
static int merge_configs(struct ini_cfgobj *donor,
                         struct ini_cfgobj *acceptor,
                         uint32_t collision_flags)
{
    int error = EOK;
    struct merge_data data;

    TRACE_FLOW_ENTRY();

    data.ci = acceptor->cfg;
    data.flags = collision_flags;
    data.error = 0;
    data.found = 0;

    /* Loop through the donor collection calling
     * donor_handler callback for every section we find.
     */
    error = col_traverse_collection(donor->cfg,
                                    COL_TRAVERSE_ONELEVEL,
                                    donor_handler,
                                    (void *)(&data));
    if (error) {
        TRACE_ERROR_NUMBER("Merge failed", error);
        return error;
    }

    /* Check if we got error */
    if ((data.error) &&
        (((collision_flags & INI_MS_MASK) == INI_MS_ERROR) ||
         ((collision_flags & INI_MV2S_MASK) == INI_MV2S_ERROR))) {
        TRACE_ERROR_NUMBER("Got error in error mode", data.error);
        return data.error;
    }

    /* If boundaries are different re-align the values */
    if (acceptor->boundary != donor->boundary) {
        error = ini_config_set_wrap(acceptor, acceptor->boundary);
        if (error) {
            TRACE_ERROR_NUMBER("Failed to re-align", error);
            return error;
        }
    }

    /* Merge last comment */
    error = merge_comment(donor, acceptor);
    if (error) {
        TRACE_ERROR_NUMBER("Failed to merge comment", error);
        return error;
    }

    /* Check if we got error */
    if ((data.error) &&
        (((collision_flags & INI_MS_MASK) == INI_MS_DETECT) ||
         ((collision_flags & INI_MV2S_MASK) == INI_MV2S_DETECT))) {
        TRACE_ERROR_NUMBER("Got error in error or detect mode", data.error);
        error = data.error;
    }

    TRACE_FLOW_EXIT();
    return error;
}

/* Check if collision flags are valid */
int valid_collision_flags(uint32_t collision_flags)
{
    uint32_t flag;

    TRACE_FLOW_ENTRY();

    flag = collision_flags & INI_MV1S_MASK;
    if ((flag != INI_MV1S_OVERWRITE) &&
        (flag != INI_MV1S_ERROR) &&
        (flag != INI_MV1S_PRESERVE) &&
        (flag != INI_MV1S_ALLOW) &&
        (flag != INI_MV1S_DETECT)) {
        TRACE_ERROR_STRING("Invalid value collision flag","");
        return 0;
    }

    flag = collision_flags & INI_MV2S_MASK;
    if ((flag != INI_MV2S_OVERWRITE) &&
        (flag != INI_MV2S_ERROR) &&
        (flag != INI_MV2S_PRESERVE) &&
        (flag != INI_MV2S_ALLOW) &&
        (flag != INI_MV2S_DETECT)) {
        TRACE_ERROR_STRING("Invalid value cross-section collision flag","");
        return 0;
    }

    flag = collision_flags & INI_MS_MASK;
    if ((flag != INI_MS_MERGE) &&
        (flag != INI_MS_OVERWRITE) &&
        (flag != INI_MS_ERROR) &&
        (flag != INI_MS_PRESERVE) &&
        (flag != INI_MS_DETECT)) {
        TRACE_ERROR_STRING("Invalid section collision flag","");
        return 0;
    }

    TRACE_FLOW_EXIT();
    return 1;
}

/* Merge two configurations together creating a new one */
int ini_config_merge(struct ini_cfgobj *first,
                     struct ini_cfgobj *second,
                     uint32_t collision_flags,
                     struct ini_cfgobj **result)
{
    int error = EOK;
    struct ini_cfgobj *new_co = NULL;

    TRACE_FLOW_ENTRY();

    /* Check input params */
    if ((!first) ||
        (!second) ||
        (!result)) {
        TRACE_ERROR_NUMBER("Invalid argument", EINVAL);
        return EINVAL;
    }

    /* Check collision flags */
    if (!valid_collision_flags(collision_flags)) {
        TRACE_ERROR_NUMBER("Invalid flags.", EINVAL);
        return EINVAL;
    }

    /* NOTE: We assume that the configuration we merge to
     * is consistent regarding duplicate values.
     * For example, if the duplicates are not allowed,
     * the parsing function should have been instructed
     * to not allow duplicates.
     * If in future we decide to be explicite we would need
     * to introduce a "compacting" function and call it here
     * after we create a copy.
     * For now it is treated as a corner case and thus not worth
     * implementing.
     */

    /* Create a new config object */
    error = ini_config_copy(first, &new_co);
    if (error) {
        TRACE_ERROR_NUMBER("Failed to copy configuration", error);
        return error;
    }

    /* Merge configs */
    error = merge_configs(second, new_co, collision_flags);
    if (error) {
        TRACE_ERROR_NUMBER("Failed to merge configuration", error);
        if ((error == EEXIST) &&
            ((((collision_flags & INI_MS_MASK) == INI_MS_DETECT) &&
              ((collision_flags & INI_MV2S_MASK) != INI_MV2S_ERROR)) ||
             (((collision_flags & INI_MS_MASK) != INI_MS_ERROR) &&
              ((collision_flags & INI_MV2S_MASK) == INI_MV2S_DETECT)))) {
            TRACE_ERROR_NUMBER("Got error in detect mode", error);
            /* Fall through! */
        }
        else {
            /* Got an error in any other mode */
            TRACE_ERROR_NUMBER("Got error in non detect mode", error);
            ini_config_destroy(new_co);
            return error;
        }
    }

    *result = new_co;
    TRACE_FLOW_EXIT();
    return error;

}

/* How many errors do we have in the list ? */
unsigned ini_config_error_count(struct ini_cfgobj *cfg_ctx)
{
    unsigned count = 0;

    TRACE_FLOW_ENTRY();

    count = cfg_ctx->count;

    TRACE_FLOW_EXIT();
    return count;

}

/* Free error strings */
void ini_config_free_errors(char **errors)
{
    TRACE_FLOW_ENTRY();

    col_free_property_list(errors);

    TRACE_FLOW_EXIT();
}

/* Get the list of error strings */
int ini_config_get_errors(struct ini_cfgobj *cfg_ctx,
                          char ***errors)
{
    char **errlist = NULL;
    struct collection_iterator *iterator = NULL;
    int error;
    struct collection_item *item = NULL;
    struct ini_parse_error *pe;
    unsigned int count = 0;
    char *line;

    TRACE_FLOW_ENTRY();

    /* If we have something to print print it */
    if ((!errors) || (!cfg_ctx)) {
        TRACE_ERROR_NUMBER("Invalid parameter.", EINVAL);
        return EINVAL;
    }

    errlist = calloc(cfg_ctx->count + 1, sizeof(char *));
    if (!errlist) {
        TRACE_ERROR_NUMBER("Failed to allocate memory for errors.", ENOMEM);
        return ENOMEM;
    }

    /* Bind iterator */
    error =  col_bind_iterator(&iterator,
                               cfg_ctx->error_list,
                               COL_TRAVERSE_DEFAULT);
    if (error) {
        TRACE_ERROR_NUMBER("Faile to bind iterator:", error);
        ini_config_free_errors(errlist);
        return error;
    }

    while(1) {
        /* Loop through a collection */
        error = col_iterate_collection(iterator, &item);
        if (error) {
            TRACE_ERROR_NUMBER("Error iterating collection", error);
            col_unbind_iterator(iterator);
            ini_config_free_errors(errlist);
            return error;
        }

        /* Are we done ? */
        if (item == NULL) break;

        /* Process collection header */
        if (col_get_item_type(item) == COL_TYPE_COLLECTION) {
            continue;
        }
        else {
            /* Put error into provided format */
            pe = (struct ini_parse_error *)(col_get_item_data(item));

            /* Would be nice to have asprintf function...
             * ...but for now we know that all the errors
             * are pretty short and will fir into the predefined
             * error length buffer.
             */
            line = malloc(MAX_ERROR_LINE + 1);
            if (!line) {
                TRACE_ERROR_NUMBER("Failed to get memory for error.", ENOMEM);
                col_unbind_iterator(iterator);
                ini_config_free_errors(errlist);
                return ENOMEM;
            }

            snprintf(line, MAX_ERROR_LINE, LINE_FORMAT,
                     col_get_item_property(item, NULL),
                     pe->error,
                     pe->line,
                     ini_get_error_str(pe->error,
                                       INI_FAMILY_PARSING));

            errlist[count] = line;
            count++;
        }

    }

    /* Do not forget to unbind iterator - otherwise there will be a leak */
    col_unbind_iterator(iterator);

    *errors = errlist;

    TRACE_FLOW_EXIT();
    return error;
}