rulimine/src/lib/config.c

112 lines
2.3 KiB
C
Raw Normal View History

2020-01-22 09:13:19 +03:00
#include <stddef.h>
#include <lib/config.h>
#include <lib/libc.h>
2020-03-30 22:24:36 +03:00
#include <lib/blib.h>
2020-04-14 06:20:55 +03:00
#include <fs/file.h>
2020-01-22 09:13:19 +03:00
#define SEPARATOR '\n'
2020-03-30 22:24:36 +03:00
#define MAX_CONFIG_SIZE 4096
2020-01-22 09:13:19 +03:00
2020-03-30 22:24:36 +03:00
static char *config_addr;
int init_config(int drive, int part) {
2020-04-14 06:20:55 +03:00
struct file_handle f;
2020-03-30 22:24:36 +03:00
2020-04-23 23:23:38 +03:00
if (fopen(&f, drive, part, "/qloader2.cfg")) {
if (fopen(&f, drive, part, "/boot/qloader2.cfg")) {
return -1;
}
2020-03-30 22:24:36 +03:00
}
2020-04-14 06:20:55 +03:00
if (f.size >= MAX_CONFIG_SIZE) {
2020-04-15 23:34:09 +03:00
panic("Config file is too big!\n");
2020-03-30 22:24:36 +03:00
}
config_addr = balloc(MAX_CONFIG_SIZE);
memset(config_addr, 0, MAX_CONFIG_SIZE);
2020-04-14 06:20:55 +03:00
fread(&f, config_addr, 0, f.size);
2020-03-30 22:24:36 +03:00
return 0;
}
2020-04-21 17:23:30 +03:00
int config_get_entry_name(char *ret, size_t index, size_t limit) {
char *p = config_addr;
for (size_t i = 0; i <= index; i++) {
while (*p != ':') {
if (!*p)
return -1;
p++;
}
p++;
if (*(p - 2) != '\n')
i--;
2020-04-21 17:23:30 +03:00
}
size_t i;
for (i = 0; i < (limit - 1); i++) {
if (p[i] == SEPARATOR)
break;
ret[i] = p[i];
}
ret[i] = 0;
return 0;
}
int config_set_entry(size_t index) {
char *p = config_addr;
for (size_t i = 0; i <= index; i++) {
while (*p != ':') {
if (!*p)
return -1;
p++;
}
2020-04-21 19:27:05 +03:00
p++;
if (*(p - 2) != '\n')
i--;
2020-04-21 17:23:30 +03:00
}
config_addr = p;
cont:
2020-04-21 19:27:05 +03:00
while (*p != ':' && *p)
p++;
2020-04-21 17:23:30 +03:00
if (*p && *(p - 1) != '\n')
goto cont;
2020-04-21 19:27:05 +03:00
*p = 0;
2020-04-21 17:23:30 +03:00
return 0;
}
2020-03-30 23:27:15 +03:00
char *config_get_value(char *buf, size_t index, size_t limit, const char *key) {
2020-03-30 22:24:36 +03:00
if (!limit || !buf || !key)
2020-01-22 09:13:19 +03:00
return NULL;
size_t key_len = strlen(key);
2020-03-30 22:24:36 +03:00
for (size_t i = 0; config_addr[i]; i++) {
if (!strncmp(&config_addr[i], key, key_len) && config_addr[i + key_len] == '=') {
if (i && config_addr[i - 1] != SEPARATOR)
2020-01-22 09:13:19 +03:00
continue;
2020-03-30 23:27:15 +03:00
if (index--)
continue;
2020-01-22 09:13:19 +03:00
i += key_len + 1;
size_t j;
2020-03-30 22:24:36 +03:00
for (j = 0; config_addr[i + j] != SEPARATOR && config_addr[i + j]; j++) {
2020-01-22 09:13:19 +03:00
if (j == limit - 1)
break;
2020-03-30 22:24:36 +03:00
buf[j] = config_addr[i + j];
2020-01-22 09:13:19 +03:00
}
buf[j] = 0;
return buf;
}
}
return NULL;
}