1
0
mirror of https://github.com/moparisthebest/curl synced 2024-12-22 08:08:50 -05:00

curl_gethostname.c: fix signed/unsigned comparison and avoid a double copy

both introduced in 42be24af
This commit is contained in:
Yang Tse 2011-10-13 23:00:24 +02:00
parent 47e4537ac6
commit ea12c72d12

View File

@ -62,46 +62,41 @@ int Curl_gethostname(char *name, GETHOSTNAME_TYPE_ARG2 namelen) {
return -1; return -1;
#else #else
int err = 0; int err;
char* dot = NULL; char* dot;
char hostname[HOSTNAME_MAX + 1];
#ifdef DEBUGBUILD #ifdef DEBUGBUILD
/* Override host name when environment variable CURL_GETHOSTNAME is set */ /* Override host name when environment variable CURL_GETHOSTNAME is set */
const char *force_hostname = getenv("CURL_GETHOSTNAME"); const char *force_hostname = getenv("CURL_GETHOSTNAME");
if(force_hostname) { if(force_hostname) {
strncpy(hostname, force_hostname, sizeof(hostname)); strncpy(name, force_hostname, namelen);
hostname[sizeof(hostname) - 1] = '\0'; err = 0;
}
else {
name[0] = '\0';
err = gethostname(name, namelen);
} }
else
err = gethostname(hostname, sizeof(hostname));
#else /* DEBUGBUILD */ #else /* DEBUGBUILD */
/* The call to system's gethostname() might get intercepted by the /* The call to system's gethostname() might get intercepted by the
libhostname library when libcurl is built as a non-debug shared libhostname library when libcurl is built as a non-debug shared
library when running the test suite. */ library when running the test suite. */
err = gethostname(hostname, sizeof(hostname)); name[0] = '\0';
err = gethostname(name, namelen);
#endif #endif
if(err != 0) name[namelen - 1] = '\0';
if(err)
return err; return err;
/* Is the hostname fully qualified? */ /* Truncate domain, leave only machine name */
dot = strchr(hostname, '.'); dot = strchr(name, '.');
if(dot) { if(dot)
/* Copy only the machine name to the specified buffer */ *dot = '\0';
size_t size = dot - hostname;
strncpy(name, hostname, namelen > size ? size : namelen);
name[(namelen > size ? size : namelen) - 1] = '\0';
}
else {
/* Copy the hostname to the specified buffer */
strncpy(name, hostname, namelen);
name[namelen - 1] = '\0';
}
return 0; return 0;
#endif #endif