101 lines
2.4 KiB
C
101 lines
2.4 KiB
C
#define _DEFAULT_SOURCE
|
|
|
|
#include <stdio.h>
|
|
#include <errno.h>
|
|
#include <string.h>
|
|
#include <ctype.h>
|
|
#include <stdlib.h>
|
|
#include <px_common.h>
|
|
#include <px_config.h>
|
|
#include <px_log.h>
|
|
|
|
void px_server_config_init(px_server_config_t* conf) {
|
|
memset(conf, 0, sizeof(*conf));
|
|
}
|
|
|
|
static void px_server_config_set(px_server_config_t* cfg, char const* key, char const* value) {
|
|
if (strcmp(key, "listen_address") == 0) {
|
|
cfg->listen_addr = strdup(value);
|
|
} else if (strcmp(key, "listen_port") == 0) {
|
|
cfg->listen_port = strdup(value);
|
|
} else if (strcmp(key, "cert_file") == 0) {
|
|
cfg->cert_file = strdup(value);
|
|
} else if (strcmp(key, "privkey_file") == 0) {
|
|
cfg->pk_file = strdup(value);
|
|
}
|
|
}
|
|
|
|
px_server_config_t* px_server_config_from_file(char const* path) {
|
|
px_server_config_t* cfg = NULL;
|
|
FILE* confstr = NULL;
|
|
size_t const BUFLEN = 1024;
|
|
char filebuf[BUFLEN];
|
|
|
|
confstr = fopen(path, "r");
|
|
if (!confstr) {
|
|
int e = errno;
|
|
px_log_error("could not open conf file %s: %d, %s", path, errno, strerror(errno));
|
|
errno = e;
|
|
return NULL;
|
|
}
|
|
|
|
cfg = PX_NEW_UNINITIALIZED(px_server_config_t);
|
|
if (!cfg) {
|
|
int e = errno;
|
|
px_log_error("could not allocate server config: %d, %s", e, strerror(e));
|
|
errno = e;
|
|
fclose(confstr);
|
|
return NULL;
|
|
}
|
|
px_server_config_init(cfg);
|
|
|
|
while (!feof(confstr)) {
|
|
char* tok;
|
|
filebuf[0] = '\0';
|
|
if (fgets(&filebuf[0], sizeof(filebuf), confstr) == NULL)
|
|
break;
|
|
|
|
if (filebuf[0] == '\0')
|
|
break;
|
|
|
|
// trim any newlines. TODO this needs to be done properly, consider UTF etc
|
|
for (int p = strlen(filebuf) - 1; p >= 0 && !isprint((unsigned char)filebuf[p]); --p)
|
|
filebuf[p] = '\0';
|
|
|
|
//px_log_debug("got config line: %s", filebuf);
|
|
|
|
char* key = strtok_r(filebuf, "=", &tok);
|
|
if (!key || *key == '\0')
|
|
continue;
|
|
char* val = tok;
|
|
if (!val || *val == '\0')
|
|
continue;
|
|
px_log_debug("got key '%s' = '%s'", key, val);
|
|
|
|
px_server_config_set(cfg, key, val);
|
|
}
|
|
|
|
if (errno != 0) {
|
|
int e = errno;
|
|
px_log_error("could not read config file: %d, %s", e, strerror(e));
|
|
errno = e;
|
|
}
|
|
|
|
fclose(confstr);
|
|
return cfg;
|
|
}
|
|
|
|
void px_server_config_destroy(px_server_config_t* cfg) {
|
|
if (!cfg)
|
|
return;
|
|
free(cfg->listen_addr);
|
|
free(cfg->listen_port);
|
|
free(cfg->cert_file);
|
|
free(cfg->pk_file);
|
|
}
|
|
|
|
void px_server_config_delete(px_server_config_t* cfg) {
|
|
px_server_config_destroy(cfg);
|
|
free(cfg);
|
|
}
|