libgluonutil: implement gluonutil_get_primary_domain()

Implemented using readlink() and basename() to the selected domain in
/lib/gluon/domains/${DOMAIN}.json.
This commit is contained in:
lemoer 2020-05-13 02:02:49 +02:00 committed by Matthias Schiffer
parent 0c2a52c19f
commit bcf57467dd

View File

@ -33,6 +33,8 @@
#include <string.h> #include <string.h>
#include <stdlib.h> #include <stdlib.h>
#include <unistd.h> #include <unistd.h>
#include <limits.h>
#include <errno.h>
/** /**
* Merges two JSON objects * Merges two JSON objects
@ -212,6 +214,45 @@ uci_fail:
return ret; return ret;
} }
char * gluonutil_get_primary_domain(void) {
if (!gluonutil_has_domains())
return NULL;
char *domain_code = gluonutil_get_domain();
if (!domain_code)
return NULL;
const char *domain_path_fmt = "/lib/gluon/domains/%s.json";
char domain_path[strlen(domain_path_fmt) + strlen(domain_code)];
snprintf(domain_path, sizeof(domain_path), domain_path_fmt, domain_code);
char primary_domain_path[PATH_MAX+1];
char *primary_domain_code;
ssize_t len = readlink(domain_path, primary_domain_path, PATH_MAX);
if (len < 0) {
// EINVAL = file is not a symlink = the domain itself is the primary domain
if (errno != EINVAL) {
free(domain_code);
return NULL;
}
return domain_code;
}
free(domain_code);
primary_domain_path[len] = '\0';
primary_domain_code = basename(primary_domain_path);
char *ext_begin = strrchr(primary_domain_code, '.');
if (!ext_begin)
return NULL;
// strip .json from filename
*ext_begin = '\0';
return strdup(primary_domain_code);
}
struct json_object * gluonutil_load_site_config(void) { struct json_object * gluonutil_load_site_config(void) {
char *domain_code = NULL; char *domain_code = NULL;