summaryrefslogtreecommitdiffstats
path: root/ini/elapi_ini.c
blob: 52af8dcc8b0dce6974f8b528e4c7011fd8511626 (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
/* Copyright */

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include "elapi_collection.h"
#include "elapi_ini.h"
#include "elapi_tools.h"
#include "elapi_debug.h"

/* STATIC INTERNAL FUNCTIONS */

#define RET_PAIR        0
#define RET_COMMENT     1
#define RET_SECTION     2
#define RET_INVALID     3
#define RET_EMPTY       4
#define RET_EOF         5
#define RET_ERROR       6


#define NAME_OVERHEAD   10
#define MAX_KEY         65535
#define MAX_VALUE       65535
#define BUFFER_SIZE     MAX_KEY + MAX_VALUE + 3

#define SLASH           "/"


/* Special handler to extract configuration value */
static int value_extractor(char *property,
                           int property_len,
                           int type,
                           void *data,
                           int length,
                           void *custom_data,
                           int *stop)
{
    void *allocated = NULL;

    DEBUG_STRING("value_extractor","Entry.");
    DEBUG_STRING("Property:",property);
    DEBUG_NUMBER("Property length:",property_len);
    DEBUG_NUMBER("Type:",type);
    DEBUG_NUMBER("Length:",length);

    allocated = malloc(length);
    if(allocated == NULL) return errno; 
    memcpy(allocated, data, length);    

    *((int **)(custom_data)) = allocated;
    *stop = 1;

    DEBUG_STRING("value_extractor","Success Exit.");

    return EOK;
}


/* Process value */
static int process_value(char *buff, void *value, int *length, int *type)
{
    int len = 0;
    int i = 0;
    int esc = 0;
    unsigned char hex = 0;
    int mod = 0;
    char *dp = NULL;
    char *dp2 = NULL;
    int use_long = 0;
    int use_unsigned = 0;
    long l_result = 0;
    unsigned long ul_result = 0;
    unsigned u_result = 0;
    int result = 0;
    double dbl = 0.;
    char *errconv = NULL;
    
    DEBUG_STRING("process_value","Entry")

    len = strlen(buff);
    if(len == 0) {
        DEBUG_STRING("Empty value","")
        return RET_INVALID;
    }

    if(len >= MAX_VALUE) {
        DEBUG_STRING("Value too big","")
        return RET_INVALID;
    }

    /* Is this a string ? */
    if((*buff == '"') && (*(buff+len-1) == '"')) {
        buff++;
        len-=2;
        *length = 0;
        *type = ELAPI_TYPE_STRING; 
        esc = 0;
        for(i=0;i<len;i++) {
            if(esc == 1) {
                esc = 0;
            } 
            else if(*(buff+i)=='\\') {
                esc = 1;
                continue;
            }    
            *((char *)(value+(*length))) = *(buff+i);
            (*length)++;
        }
        *((char *)(value+(*length))) = '\0';
        (*length)++;
        return RET_PAIR;
    }

    /* Is this a binary ? */
    if((*buff == '\'') && (*(buff+len-1) == '\'')) {
        buff++;
        len-=2;
        if((len/2) *2 != len) {
            DEBUG_STRING("Invalid length for binary data","")
            return RET_INVALID;
        }
        *length = 0;
        *type = ELAPI_TYPE_BINARY; 
        for(i=0;i<len;i+=2) {
            if((!isxdigit(*(buff+i))) || (!isxdigit(*(buff+i+1)))) {
                DEBUG_STRING("Invalid encoding for binary data","")
                return RET_INVALID;
            }

            if(isdigit(*(buff+i))) {
                if(isdigit(*(buff+i+1))) hex = 16 * (*(buff+i) - '0') + (*(buff+i+1) - '0');
                else hex = 16 * (*(buff+i) - '0') + (tolower(*(buff+i+1)) - 'a' + 10);
            }
            else {
                if(isdigit(*(buff+i+1))) hex = 16 * (tolower(*(buff+i)) - 'a') + (*(buff+i+1) - '0');
                else hex = 16 * (tolower(*(buff+i)) - 'a' + 10) + (tolower(*(buff+i+1)) - 'a' + 10);
            }

            *((char *)(value+(*length))) = (char)(hex);
            (*length)++;
        }
        return RET_PAIR;
    }

    /* Is this a positive or negative number? */
    if(*buff == '-') {
        mod = -1;
        buff++;
        len--;
        use_unsigned = 0;
    }

    /* Check for decimal point */
    dp = strchr(buff,'.');
    if(dp != NULL) {
        dp2 = strchr(dp+1,'.');
        if(dp2 != NULL) {
            DEBUG_STRING("More than one decimal point for double","")
            return RET_INVALID;
		}
    }
    else {
        /* No decimal point so check for long */
        if(*(buff+len-1) == 'L') {
            use_long = 1; 
            *(buff+len-1) = '\0';
            len--;
        }

        if(*(buff+len-1) == 'U') {
            if(mod < 0) {
                DEBUG_STRING("Signed/unsigned missmatch","")
                return RET_INVALID;
            }            
            use_unsigned = 1; 
            *(buff+len-1) = '\0';
            len--;
        }
    }
            
    /* Check that the rest are digits */
    for(i=0;i<len;i++) {
        if(!(isdigit(*(buff+i)) || (*(buff+i) == '.'))) {
            DEBUG_STRING("Invalid symbol in the number","")
            return RET_INVALID;
        }
    }

    if(mod == -1) {
        buff--;
        len++;
        *buff = '-';
    }

    /* Copy longs and ints */
    if(dp == NULL) {
        errno = 0;
        if(use_unsigned) {
            if(use_long) {
                *type = ELAPI_TYPE_ULONG;
                ul_result = (unsigned long) strtol(buff,(char **)(NULL),10);
                if(errno != 0) {
                    DEBUG_STRING("Number is probably too long","");
                    return RET_INVALID;
                }
                *length = sizeof(long);
                memcpy(value, (void *)(&ul_result),*length);
            }
            else {
                *type = ELAPI_TYPE_UNSIGNED;
                u_result = (unsigned int) strtol(buff,(char **)(NULL),10);
                if(errno != 0) {
                    DEBUG_STRING("Number is probably too long","");
                    return RET_INVALID;
                }
                *length = sizeof(unsigned);
                memcpy(value, (void *)(&u_result),*length);
            }
        }
        else {
            if(use_long) {
                *type = ELAPI_TYPE_LONG;
                l_result = (long) strtol(buff,(char **)(NULL),10);
                if(errno != 0) {
                    DEBUG_STRING("Number is probably too long","");
                    return RET_INVALID;
                }
                *length = sizeof(long);
                memcpy(value, (void *)(&l_result),*length);
            }
            else {
                *type = ELAPI_TYPE_INTEGER;
                result = (int) strtol(buff,(char **)(NULL),10);
                if(errno != 0) {
                    DEBUG_STRING("Number is probably too long","");
                    return RET_INVALID;
                }
                *length = sizeof(int);
                memcpy(value, (void *)(&result),*length);
            }
        }
    }
    /* Deal with double */
    else {
        if(len > 20) {
            DEBUG_STRING("Number is too long","");
            return RET_INVALID;
        }

        errno = 0;
        dbl = (double)(strtod(buff,&errconv));
        if(errno != 0) {
            DEBUG_STRING("Invalid double","");
            return RET_INVALID;
        }
        DEBUG_STRING("Value to convert:",buff);
        DEBUG_DOUBLE("Got double:",dbl)
        *type = ELAPI_TYPE_DOUBLE;
        *length = sizeof(double);
        memcpy(value, (void *)(&dbl),*length);
    }
     

    DEBUG_STRING("process_value","Success");

    return RET_PAIR;

    
}
/* Reads a line from the file */
static int read_line(FILE *file,char *key,void *value, int *length, int *type) 
{

    char *res = NULL;
    char buf[BUFFER_SIZE+1];
    int len = 0;
    char *buffer = NULL;
    int i = 0;
    int status = RET_INVALID;
    char *eq = NULL;

    DEBUG_STRING("read_line","Entry")

    buffer = buf;

    /* Get data from file */
    res = fgets(buffer,BUFFER_SIZE,file);
    if(res == NULL) {
        DEBUG_STRING("Read nothing","")
        return RET_EOF;
    }

    len = strlen(buffer);
    if(len == 0) {
        DEBUG_STRING("Nothing was read.","")
        return RET_EMPTY;
    }
    
    /* Added \r just in case we deal with Windows in future */ 
    if((*(buffer + len - 1) != '\n') && (*(buffer + len - 1) != '\r')) {
        DEBUG_STRING("String it too big!","")
        return RET_INVALID;
    }

    /* Ingnore comments */
    if(*buffer == ';') {
        DEBUG_STRING("Comment",buf)
        return RET_INVALID;
    }

    /* Empty line */
    if(*buffer == '\n') {
        DEBUG_STRING("Empty line",buf)
        return RET_INVALID;
    }

    /* Trucate trailing spaces and CRs */
    while(isspace(*(buffer + len - 1))) {
        *(buffer + len - 1) = '\0';
        len--;
    }

    /* Trucate leading spaces  */
    while(isspace(*buffer)) {
        buffer++;
        len--;
    }

    /* Section */
    if(*buffer == '[') {
        if(*(buffer+len-1) != ']') {
            DEBUG_STRING("Invalid format for section",buf)
            return RET_ERROR;
        }
        buffer++;
        len--;
        while(isspace(*(buffer))) {
            buffer++;
            len--;
        }
        if(len == 0) {
            DEBUG_STRING("Invalid format for section",buf)
            return RET_ERROR;
        }

        *(buffer + len - 1) = '\0';
        len--;
        while(isspace(*(buffer + len - 1))) {
            *(buffer + len - 1) = '\0';
            len--;
        }
        if(len >= MAX_KEY) {
            DEBUG_STRING("Section name is too long",buf)
            return RET_ERROR;
        }

        memcpy(key,buffer,len+1);
        return RET_SECTION;                
    }

    /* Assume we are dealing with the K-V here */
    /* Find "=" */
    eq = strchr(buffer,'=');
    if(eq == NULL) {
        DEBUG_STRING("No equal sign",buf)
        return RET_INVALID;
    }

    /* Strip spaces around "=" */
    i = eq - buffer - 1;
    while((i >= 0) && isspace(*(buffer + i))) i--;
    if(i<0) {
        DEBUG_STRING("No key",buf)
        return RET_INVALID;
    }

    /* Copy key into provided buffer */ 
    if(i >= MAX_KEY) {
        DEBUG_STRING("Section name is too long",buf)
        return RET_INVALID;
    }
    memcpy(key,buffer,i+1);
    *(key+i+1) = '\0';
    DEBUG_STRING("KEY:",key);
    
    eq++;
    while(isspace(*eq)) eq++;
    DEBUG_STRING("VALUE:",eq);

    /* Now process value */
    status = process_value(eq,value,length,type);
    
    DEBUG_NUMBER("Type:",*type);
    DEBUG_NUMBER("Data length:",*length);
    
    return status;
}



/* Add to collection or update */
static int add_or_update(struct collection_item *current_section,
                         char *key,
                         void *value,
                         int length,
                         int type)
{
    int found = ELAPI_NOMATCH;
	int error = EOK;

    DEBUG_STRING("add_or_update", "Entry");

    (void)is_item_in_collection(current_section,key,ELAPI_TYPE_ANY,ELAPI_TRAVERSE_IGNORE,&found);

    if(found == ELAPI_MATCH) {
        DEBUG_STRING("Updating...", "");
        error = update_property(current_section,key,type,value,length,ELAPI_TRAVERSE_IGNORE);
    }
    else {
        DEBUG_STRING("Adding...", "");
        error = add_any_property(current_section,NULL,key,type,value,length);
    }

    DEBUG_NUMBER("add_or_update returning", error);
    return error;
}
/***************************************************************************/
/* Function to read single ini file and pupulate 
 * the provided collection with subcollcetions from the file */
int ini_to_collection(char *filename, struct collection_item *ini_config)
{
    FILE *file;
    int error;    
    int status;
    int section_count = 0; 
    char key[MAX_KEY];
    char value[MAX_VALUE];
    struct collection_item *current_section = (struct collection_item *)(NULL);
    int length;
    int type;

    DEBUG_STRING("ini_to_collection", "Entry");

    /* Open file for reading */
    file = fopen(filename,"r");
    if(file == NULL) {
        error = errno;
        DEBUG_NUMBER("Failed to open file - but this is OK", error);
        return EOK;
    }

    /* Read file lines */
    while((status = read_line(file,key,(void *)(value),&length,&type)) != RET_EOF) {
        
        switch(status) {
            case RET_PAIR:
                        /* Do we have a section at the top of the file ? */
                        if(section_count == 0) {
                            /* Check if collection already exists */
                            error = get_collection_reference(ini_config,&current_section,INI_DEFAULT_SECTION);
                            if(error != EOK) {
                                /* Create default collection */
                                if((error=create_collection(&current_section,INI_DEFAULT_SECTION)) || 
                                   (error=add_collection_to_collection(ini_config,NULL,NULL,
                                                                       current_section,
                                                                       ELAPI_ADD_MODE_REFERENCE))) {
                                    DEBUG_NUMBER("Failed to create collection", error);
                                    fclose(file);
                                    destroy_collection(current_section);
                                    return error;
                                }
                            }
                            section_count++;
                        }

                        /* Put value into the collection */
                        if((error=add_or_update(current_section,key,value,length,type))) {
                            DEBUG_NUMBER("Failed to add pair to collection", error);
                            fclose(file);
                            destroy_collection(current_section);
                            return error;
                        }
                        break;

            case RET_SECTION:
                        /* Read a new section */
                        destroy_collection(current_section);
                        current_section = (struct collection_item *)(NULL);

                        error = get_collection_reference(ini_config,&current_section,key);
                        if(error != EOK) {
                            /* Create default collection */
                            if((error=create_collection(&current_section,key)) || 
                               (error=add_collection_to_collection(ini_config,NULL,NULL,
                                                                   current_section,
                                                                   ELAPI_ADD_MODE_REFERENCE))) {
                                DEBUG_NUMBER("Failed to add collection", error);
                                fclose(file);
                                destroy_collection(current_section);
                                return error;
                            }
                        }
                        section_count++;
                        break;

            case RET_EMPTY:
                        DEBUG_STRING("Empty string", "");                      
                        break;

            case RET_COMMENT:
                        DEBUG_STRING("Comment", "");  
                        break;

            case RET_ERROR:
                        DEBUG_STRING("Invalid section format", "");  
                        return EINVAL;

            case RET_INVALID:
            default:
                        DEBUG_STRING("Invalid string", "");                      
                        break;
        }
    }
     
    /* Close file */                   
    fclose(file);

    DEBUG_COLLECTION(ini_config);

    destroy_collection(current_section);

    DEBUG_COLLECTION(ini_config);
    
    DEBUG_STRING("ini_to_collection", "Success Exit");

    return EOK;
}


/*********************************************************************/

/* read ini file and create collection out of it */
int config_to_collection(char *application, char *config_file, char *config_dir, struct collection_item **ini_config)
{
    int error=EOK;
    char *file_name;

    DEBUG_STRING("config_to_collection", "Entry");

    *ini_config = (struct collection_item *)(NULL);

    /* Create collection */
    if((error=create_collection(ini_config,application))) {
        DEBUG_NUMBER("Failed to create collection", error);
        destroy_collection(*ini_config);
        return error;
    }

    /* Read master file */
    if((error = ini_to_collection(config_file,*ini_config))) {
        DEBUG_NUMBER("Failed to read master file", error);
        destroy_collection(*ini_config);
        return error;
    }

    /* Get specific application file */
    file_name = malloc(strlen(config_dir) + strlen(application) + NAME_OVERHEAD);
    if(file_name == NULL) {
        error = errno;
        DEBUG_NUMBER("Failed to allocate memory for file name", error);
        destroy_collection(*ini_config);
        return error;
    }

    sprintf(file_name,"%s%s%s.conf",config_dir, SLASH, application);
    DEBUG_STRING("Opening file:", file_name);

    /* Read master file */
	error = ini_to_collection(file_name,*ini_config);
    free(file_name);
    if(error) {
        DEBUG_NUMBER("Failed to read specific application file", error);
        destroy_collection(*ini_config);
        return error;
    }

    DEBUG_STRING("config_to_collection", "Exit");
    return EOK;
}

/* Function to get value from the configration handle */
int get_value_from_config(void *value, 
                          int type, 
                          char *section, 
                          char *name,
                          struct collection_item *ini_config)
{
    int error = EOK;
    struct collection_item *section_handle = (struct collection_item *)(NULL);
    char *to_find;
    char default_section[] = INI_DEFAULT_SECTION;

    DEBUG_STRING("get_value_from_config", "Entry");

    if(section == NULL) to_find = default_section;
    else to_find = section;

    DEBUG_STRING("Getting Name:", name);
    DEBUG_STRING("In Section:", section);

    /* Get Subcollection */
    error = get_collection_reference(ini_config,&section_handle,to_find);
    if(section_handle == (struct collection_item *)(NULL)) {
        /* We have not found section - return success */
        DEBUG_STRING("get_value_from_config", "No such section");
        return EOK; 
    }

    /* If we have the section then get the data */
    error = get_item_and_do(section_handle, name,type, ELAPI_TRAVERSE_ONELEVEL, value_extractor, value);

    DEBUG_STRING("get_value_from_config", "Exit");
    return error;
}