#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include "ini.h"
#include "util-common.h"
#ifndef HAVE_STRSEP
char *strsep(char **str, const char *delims)
{
char *token;
if(*str == NULL) {
return NULL;
}
token = *str;
while(**str != '\0') {
if(strchr(delims, **str) != NULL) {
**str = '\0';
(*str)++;
return token;
}
(*str)++;
}
*str = NULL;
return token;
}
#endif
int parse_ini(const char *file, ini_parser_fn cb, void *data)
{
char line[PATH_MAX], *section_name = NULL;
FILE *fp = NULL;
int linenum = 0;
int ret = 0;
fp = fopen(file, "r");
if(fp == NULL) {
return cb(file, 0, NULL, NULL, NULL, data);
}
while(safe_fgets(line, PATH_MAX, fp)) {
char *key, *value;
size_t line_len;
linenum++;
line_len = strtrim(line);
if(line_len == 0 || line[0] == '#') {
continue;
}
if(line[0] == '[' && line[line_len - 1] == ']') {
char *name;
name = strdup(line + 1);
name[line_len - 2] = '\0';
ret = cb(file, linenum, name, NULL, NULL, data);
free(section_name);
section_name = name;
if(ret) {
goto cleanup;
}
continue;
}
key = line;
value = line;
strsep(&value, "=");
strtrim(key);
strtrim(value);
if((ret = cb(file, linenum, section_name, key, value, data)) != 0) {
goto cleanup;
}
}
cleanup:
fclose(fp);
free(section_name);
return ret;
}