From 360bcb941a8b4f82da829dce070fb0fd2874a743 Mon Sep 17 00:00:00 2001 From: Aaron LI Date: Sat, 6 Oct 2018 23:06:21 +0800 Subject: [PATCH] fixed gethostname() and freeaddrinfo() calls (#73) * util: Fix gethostname() and freeaddrinfo() calls I was passing the wrong size to the 'gethostname()' call because the 'hostname' is now dynamically allocated and cannot use 'sizeof' to get its size. This mistake causes that the obtained hostname is empty. The 'freeaddrinfo()' was placed at the wrong place. Fix it. Fallback to '_POSIX_HOST_NAME_MAX' if 'sysconf()' fails. Always null-terminate the 'hostname'. * util: Simplify hostname() as no need to call getaddrinfo() There is no need to call 'getaddrinfo()' to determine the hostname of the machine, gethostname() is enough. This simplify the 'hostname()' a lot. Trim a trailing whitespace by the way. --- src/util.c | 49 +++++++++++++++++-------------------------------- 1 file changed, 17 insertions(+), 32 deletions(-) diff --git a/src/util.c b/src/util.c index b3f8eef..4d14b13 100644 --- a/src/util.c +++ b/src/util.c @@ -6,7 +6,6 @@ #include #include -// hostname #include #include #include @@ -17,49 +16,35 @@ #include #include -char* hostname_backup; +static char* hostname_backup = NULL; void hostname(char** out) { - struct addrinfo hints; - struct addrinfo* info; - char* hostname; - char* dot; - int host_name_max; - int result; - - if ((host_name_max = sysconf(_SC_HOST_NAME_MAX)) == -1) + if (hostname_backup != NULL) { - perror("sysconf(_SC_HOST_NAME_MAX)"); - exit(1); + *out = hostname_backup; + return; } - if ((hostname = malloc(host_name_max+1)) == NULL) + int maxlen = sysconf(_SC_HOST_NAME_MAX); + if (maxlen < 0) + { + maxlen = _POSIX_HOST_NAME_MAX; + } + + if ((hostname_backup = malloc(maxlen + 1)) == NULL) { perror("malloc"); exit(1); } - gethostname(hostname, sizeof(hostname)); - memset(&hints, 0, sizeof hints); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; - hints.ai_flags = AI_CANONNAME; - result = getaddrinfo(hostname, "http", &hints, &info); - - if ((result == 0) && (info != NULL)) + if (gethostname(hostname_backup, maxlen) < 0) { - dot = strchr(info->ai_canonname, '.'); - *out = strndup(info->ai_canonname, dot - info->ai_canonname); + perror("gethostname"); + exit(1); } - else - { - *out = strdup(""); - } - - hostname_backup = *out; - freeaddrinfo(info); - free(hostname); + hostname_backup[maxlen] = '\0'; + *out = hostname_backup; } void free_hostname() @@ -115,7 +100,7 @@ void load(struct desktop* desktop, struct input* login) char* line = malloc((config.max_login_len * (sizeof (char))) + 1); - if (line == NULL) + if (line == NULL) { fclose(file); return;