libsrx: two new helpers, unquoute() and fgetkey()

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
This commit is contained in:
Joachim Wiberg
2024-04-15 15:36:41 +02:00
parent 76c8c69231
commit 551f1ae548
3 changed files with 59 additions and 33 deletions
+10 -33
View File
@@ -82,47 +82,24 @@ static char *fqdn(const char *value, char *str, size_t len)
return str;
}
static char *unquote(char *buf)
{
char q = buf[0];
char *ptr;
if (q != '"' && q != '\'')
return buf;
ptr = &buf[strlen(buf) - 1];
if (*ptr == q) {
*ptr = 0;
buf++;
}
return buf;
}
static char *os_name_version(char *str, size_t len)
{
char buf[256];
FILE *fp;
char *val;
if (!str || !len)
return NULL;
fp = fopen("/etc/os-release", "r");
if (!fp)
return NULL;
str[0] = 0;
while (fgets(buf, sizeof(buf), fp)) {
chomp(buf);
if (!strncmp(buf, "NAME=", 5))
snprintf(str, len, "-V \"%.32s ", unquote(&buf[5]));
if (!strncmp(buf, "VERSION=", 8)) {
strlcat(str, unquote(&buf[8]), len);
strlcat(str, "\"", len);
break;
}
val = fgetkey("/etc/os-release", "NAME");
if (val)
snprintf(str, len, "-V \"%.32s ", val);
val = fgetkey("/etc/os-release", "VERSION");
if (val) {
strlcat(str, val, len);
strlcat(str, "\"", len);
}
fclose(fp);
if (strlen(str) > 0 && str[strlen(str) - 1] != '"') {
str[0] = 0;
+46
View File
@@ -215,3 +215,49 @@ int writesf(const char *str, const char *mode, const char *fmt, ...)
return fclose(fp);
}
char *unquote(char *buf)
{
char q = buf[0];
char *ptr;
if (q != '"' && q != '\'')
return buf;
ptr = &buf[strlen(buf) - 1];
if (*ptr == q) {
*ptr = 0;
buf++;
}
return buf;
}
/*
* Reads file, line by line, lookging for key="val".
* Returns val, or NULL.
*/
char *fgetkey(const char *file, const char *key)
{
static char line[256];
int len = strlen(key);
char *ptr = NULL;
FILE *fp;
fp = fopen(file, "r");
if (!fp)
return NULL;
while (fgets(line, sizeof(line), fp)) {
chomp(line);
if (strncmp(line, key, len))
continue;
if (line[len] != '=')
continue;
ptr = unquote(line + len + 1); /* Skip 'key=' */
break;
}
fclose(fp);
return ptr;
}
+3
View File
@@ -26,4 +26,7 @@ int writedf(int value, const char *mode, const char *fmt, ...)
int writesf(const char *str, const char *mode, const char *fmt, ...)
__attribute__ ((format (printf, 3, 4)));
char *unquote(char *buf);
char *fgetkey(const char *file, const char *key);
#endif /* CONFD_HELPERS_H_ */