From: Michael Tremer Date: Fri, 10 Feb 2023 15:24:53 +0000 (+0000) Subject: networkd: config: Implement reading configuration files X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=5ef56cff5e19dcda00a76a40846fe3def9e6239f;p=network.git networkd: config: Implement reading configuration files Signed-off-by: Michael Tremer --- diff --git a/src/networkd/config.c b/src/networkd/config.c index ef6218e8..17d6d890 100644 --- a/src/networkd/config.c +++ b/src/networkd/config.c @@ -157,9 +157,49 @@ int nw_config_flush(struct nw_config* config) { } static int nw_config_readf(struct nw_config* config, FILE* f) { - // XXX TODO + char* line = NULL; + size_t length = 0; + int r; - return 0; + ssize_t bytes_read = 0; + + char* key = NULL; + char* val = NULL; + + for (;;) { + // Read the next line + bytes_read = getline(&line, &length, f); + if (bytes_read < 0) + break; + + // Key starts at the beginning of the line + key = line; + + // Value starts after '=' + val = strchr(line, '='); + + // Invalid line without a '=' character + if (!val) + continue; + + // Split the string + *val++ = '\0'; + + // Strip any whitespace from value + r = nw_string_strip(val); + if (r) + break; + + // Store the setting + r = nw_config_set(config, key, val); + if (r) + break; + } + + if (line) + free(line); + + return r; } int nw_config_read(struct nw_config* config) { @@ -204,7 +244,7 @@ static int nw_config_writef(struct nw_config* config, FILE* f) { continue; // Write the entry - r = fprintf(f, "%s=\"%s\"\n", entry->key, entry->value); + r = fprintf(f, "%s=%s\n", entry->key, entry->value); if (r < 0) { ERROR("Failed to write configuration: %m\n"); return r; diff --git a/src/networkd/string.h b/src/networkd/string.h index 4ae2dbf2..f3c5b717 100644 --- a/src/networkd/string.h +++ b/src/networkd/string.h @@ -21,6 +21,7 @@ #ifndef NETWORKD_STRING_H #define NETWORKD_STRING_H +#include #include #include #include @@ -79,6 +80,46 @@ static inline int __nw_string_set(char* s, const size_t length, const char* valu return __nw_string_format(s, length, "%s", value); } +static inline int nw_string_lstrip(char* s) { + char* p = s; + + // Count any leading spaces + while (*p && isspace(*p)) + p++; + + // Move the string to the beginning of the buffer + while (*p) + *s++ = *p++; + + // Terminate the string + *s = '\0'; + + return 0; +} + +static inline int nw_string_rstrip(char* s) { + ssize_t l = strlen(s) - 1; + + while (l >= 0 && isspace(s[l])) + s[l--] = '\0'; + + return 0; +} + +static inline int nw_string_strip(char* s) { + int r; + + r = nw_string_lstrip(s); + if (r) + return r; + + r = nw_string_rstrip(s); + if (r) + return r; + + return 0; +} + /* Paths */