utils: Refactor get_name's functionality into util for global access

This commit is contained in:
William A. Kennington III 2014-08-24 19:49:27 -07:00 committed by Guus Sliepen
parent 78bf82cf33
commit 826ad11e41
3 changed files with 42 additions and 29 deletions

View file

@ -402,41 +402,16 @@ void load_all_nodes(void) {
char *get_name(void) {
char *name = NULL;
char *returned_name;
get_config_string(lookup_config(config_tree, "Name"), &name);
if(!name)
return NULL;
if(*name == '$') {
char *envname = getenv(name + 1);
char hostname[32] = "";
if(!envname) {
if(strcmp(name + 1, "HOST")) {
logger(DEBUG_ALWAYS, LOG_ERR, "Invalid Name: environment variable %s does not exist\n", name + 1);
return false;
}
if(gethostname(hostname, sizeof hostname) || !*hostname) {
logger(DEBUG_ALWAYS, LOG_ERR, "Could not get hostname: %s\n", sockstrerror(sockerrno));
return false;
}
hostname[31] = 0;
envname = hostname;
}
free(name);
name = xstrdup(envname);
for(char *c = name; *c; c++)
if(!isalnum(*c))
*c = '_';
}
if(!check_id(name)) {
logger(DEBUG_ALWAYS, LOG_ERR, "Invalid name for myself!");
free(name);
return false;
}
return name;
returned_name = replace_name(name);
free(name);
return returned_name;
}
bool setup_myself_reloadable(void) {

View file

@ -19,6 +19,7 @@
*/
#include "system.h"
#include "xalloc.h"
#include "../src/logger.h"
#include "utils.h"
@ -179,3 +180,38 @@ unsigned int bitfield_to_int(const void *bitfield, size_t size) {
memcpy(&value, bitfield, size);
return value;
}
char *replace_name(const char *name) {
char *ret_name;
if (name[0] == '$') {
char *envname = getenv(name + 1);
char hostname[HOST_NAME_MAX+1];
if (!envname) {
if (strcmp(name + 1, "HOST")) {
logger(DEBUG_ALWAYS, LOG_ERR, "Invalid Name: environment variable %s does not exist\n", name + 1);
return NULL;
}
if (gethostname(hostname, sizeof hostname) || !*hostname) {
logger(DEBUG_ALWAYS, LOG_ERR, "Could not get hostname: %s\n", sockstrerror(sockerrno));
return NULL;
}
hostname[HOST_NAME_MAX] = 0;
envname = hostname;
}
ret_name = xstrdup(envname);
for (char *c = ret_name; *c; c++)
if (!isalnum(*c))
*c = '_';
} else {
ret_name = xstrdup(name);
}
if (!check_id(ret_name)) {
logger(DEBUG_ALWAYS, LOG_ERR, "Invalid name for myself!");
free(ret_name);
return NULL;
}
return ret_name;
}

View file

@ -50,4 +50,6 @@ extern const char *winerror(int);
extern unsigned int bitfield_to_int(const void *bitfield, size_t size);
char *replace_name(const char *name);
#endif /* __TINC_UTILS_H__ */