From 3f7540c81c07a50edf1ed74e1aac3373a000d40c Mon Sep 17 00:00:00 2001 From: mortenp Date: Thu, 7 Dec 2006 00:33:24 +1100 Subject: [PATCH] Fixed hostnamestr() for hosts that can't find themselves using gethostbyname() (Benoit Dolez) --- ChangeLog | 2 ++ src/strgen.c | 51 +++++++++++++++++++++++++++++++++++++++++++-------- 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/ChangeLog b/ChangeLog index a587a6e3..307c6047 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,5 @@ + o Fixed hostnamestr() for hosts that can't find themselves using + gethostbyname() (Benoit Dolez) o Add 'modnonsubposts' tunable that when set will moderate all posts from non subscribers o Fixed requeue for lists with noarchive enabled diff --git a/src/strgen.c b/src/strgen.c index ed97f5f1..5dc65f39 100644 --- a/src/strgen.c +++ b/src/strgen.c @@ -30,6 +30,7 @@ #include #include #include +#include #include "strgen.h" #include "wrappers.h" @@ -136,16 +137,50 @@ char *concatstr(int count, ...) char *hostnamestr() { - struct hostent *hostlookup; - char hostname[1024]; + struct hostent *hostlookup; + char *hostname = NULL; + size_t len = 512; + + for (;;) { + len *= 2; + free(hostname); + + hostname = malloc(len); + hostname[len-1] = '\0'; + + /* gethostname() is allowed to: + * a) return -1 and undefined in hostname + * b) return 0 and an unterminated string in hostname + * c) return 0 and a NUL-terminated string in hostname + * + * We keep expanding the buffer until the hostname is + * NUL-terminated (and pray that it is not truncated) + * or an error occurs. + */ + if (gethostname(hostname, len - 1)) { + if (errno == ENAMETOOLONG) { + continue; + } + myfree(hostname); + return mystrdup("localhost"); + } + + if (hostname[len-1] == '\0') { + break; + } + } - /* TODO use dynamic allocation */ - gethostname(hostname, sizeof(hostname) - 1); - /* gethostname() is allowed to return an unterminated string */ - hostname[sizeof(hostname)-1] = '\0'; - hostlookup = gethostbyname(hostname); + if (strchr(hostname, '.')) { + /* hostname is FQDN */ + return hostname; + } + + if ((hostlookup = gethostbyname(hostname))) { + myfree(hostname); + return mystrdup(hostlookup->h_name); + } - return mystrdup(hostlookup->h_name); + return hostname; } char *mydirname(const char *path) -- 2.47.3