2008-03-27 23:09:11 +00:00
|
|
|
/* configfile.c: parsing of config files
|
|
|
|
*
|
|
|
|
* Copyright (C) 2008 Lars Hjemli
|
|
|
|
*
|
|
|
|
* Licensed under GNU General Public License v2
|
|
|
|
* (see COPYING for full license text)
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include <ctype.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include "configfile.h"
|
|
|
|
|
2013-03-04 07:52:33 +00:00
|
|
|
static int next_char(FILE *f)
|
2008-03-27 23:09:11 +00:00
|
|
|
{
|
|
|
|
int c = fgetc(f);
|
2013-03-03 15:04:29 +00:00
|
|
|
if (c == '\r') {
|
2008-03-27 23:09:11 +00:00
|
|
|
c = fgetc(f);
|
2013-03-03 15:04:29 +00:00
|
|
|
if (c != '\n') {
|
2008-03-27 23:09:11 +00:00
|
|
|
ungetc(c, f);
|
|
|
|
c = '\r';
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return c;
|
|
|
|
}
|
|
|
|
|
2013-03-04 07:52:33 +00:00
|
|
|
static void skip_line(FILE *f)
|
2008-03-27 23:09:11 +00:00
|
|
|
{
|
|
|
|
int c;
|
|
|
|
|
2013-03-04 04:21:33 +00:00
|
|
|
while ((c = next_char(f)) && c != '\n' && c != EOF)
|
2008-03-27 23:09:11 +00:00
|
|
|
;
|
|
|
|
}
|
|
|
|
|
2013-03-04 07:52:33 +00:00
|
|
|
static int read_config_line(FILE *f, char *line, const char **value, int bufsize)
|
2008-03-27 23:09:11 +00:00
|
|
|
{
|
|
|
|
int i = 0, isname = 0;
|
|
|
|
|
|
|
|
*value = NULL;
|
2013-03-04 04:21:33 +00:00
|
|
|
while (i < bufsize - 1) {
|
2008-03-27 23:09:11 +00:00
|
|
|
int c = next_char(f);
|
2013-03-03 15:04:29 +00:00
|
|
|
if (!isname && (c == '#' || c == ';')) {
|
2008-03-27 23:09:11 +00:00
|
|
|
skip_line(f);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if (!isname && isspace(c))
|
|
|
|
continue;
|
|
|
|
|
2013-03-03 15:04:29 +00:00
|
|
|
if (c == '=' && !*value) {
|
2008-03-27 23:09:11 +00:00
|
|
|
line[i] = 0;
|
2013-03-03 15:04:29 +00:00
|
|
|
*value = &line[i + 1];
|
|
|
|
} else if (c == '\n' && !isname) {
|
2008-03-27 23:09:11 +00:00
|
|
|
i = 0;
|
|
|
|
continue;
|
2013-03-03 15:04:29 +00:00
|
|
|
} else if (c == '\n' || c == EOF) {
|
2008-03-27 23:09:11 +00:00
|
|
|
line[i] = 0;
|
|
|
|
break;
|
|
|
|
} else {
|
2013-03-03 15:04:29 +00:00
|
|
|
line[i] = c;
|
2008-03-27 23:09:11 +00:00
|
|
|
}
|
|
|
|
isname = 1;
|
|
|
|
i++;
|
|
|
|
}
|
2013-03-03 15:04:29 +00:00
|
|
|
line[i + 1] = 0;
|
2008-03-27 23:09:11 +00:00
|
|
|
return i;
|
|
|
|
}
|
|
|
|
|
|
|
|
int parse_configfile(const char *filename, configfile_value_fn fn)
|
|
|
|
{
|
|
|
|
static int nesting;
|
|
|
|
int len;
|
|
|
|
char line[256];
|
|
|
|
const char *value;
|
|
|
|
FILE *f;
|
|
|
|
|
|
|
|
/* cancel deeply nested include-commands */
|
|
|
|
if (nesting > 8)
|
|
|
|
return -1;
|
|
|
|
if (!(f = fopen(filename, "r")))
|
|
|
|
return -1;
|
|
|
|
nesting++;
|
2013-03-04 04:21:33 +00:00
|
|
|
while ((len = read_config_line(f, line, &value, sizeof(line))) > 0)
|
2008-03-27 23:09:11 +00:00
|
|
|
fn(line, value);
|
|
|
|
nesting--;
|
|
|
|
fclose(f);
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|