Skip to content

Commit ea12c72

Browse files
committed
curl_gethostname.c: fix signed/unsigned comparison and avoid a double copy
both introduced in 42be24a
1 parent 47e4537 commit ea12c72

File tree

1 file changed

+17
-22
lines changed

1 file changed

+17
-22
lines changed

lib/curl_gethostname.c

+17-22
Original file line numberDiff line numberDiff line change
@@ -62,46 +62,41 @@ int Curl_gethostname(char *name, GETHOSTNAME_TYPE_ARG2 namelen) {
6262
return -1;
6363

6464
#else
65-
int err = 0;
66-
char* dot = NULL;
67-
char hostname[HOSTNAME_MAX + 1];
65+
int err;
66+
char* dot;
6867

6968
#ifdef DEBUGBUILD
7069

7170
/* Override host name when environment variable CURL_GETHOSTNAME is set */
7271
const char *force_hostname = getenv("CURL_GETHOSTNAME");
7372
if(force_hostname) {
74-
strncpy(hostname, force_hostname, sizeof(hostname));
75-
hostname[sizeof(hostname) - 1] = '\0';
73+
strncpy(name, force_hostname, namelen);
74+
err = 0;
75+
}
76+
else {
77+
name[0] = '\0';
78+
err = gethostname(name, namelen);
7679
}
77-
else
78-
err = gethostname(hostname, sizeof(hostname));
7980

8081
#else /* DEBUGBUILD */
8182

8283
/* The call to system's gethostname() might get intercepted by the
8384
libhostname library when libcurl is built as a non-debug shared
8485
library when running the test suite. */
85-
err = gethostname(hostname, sizeof(hostname));
86+
name[0] = '\0';
87+
err = gethostname(name, namelen);
8688

8789
#endif
8890

89-
if(err != 0)
91+
name[namelen - 1] = '\0';
92+
93+
if(err)
9094
return err;
9195

92-
/* Is the hostname fully qualified? */
93-
dot = strchr(hostname, '.');
94-
if(dot) {
95-
/* Copy only the machine name to the specified buffer */
96-
size_t size = dot - hostname;
97-
strncpy(name, hostname, namelen > size ? size : namelen);
98-
name[(namelen > size ? size : namelen) - 1] = '\0';
99-
}
100-
else {
101-
/* Copy the hostname to the specified buffer */
102-
strncpy(name, hostname, namelen);
103-
name[namelen - 1] = '\0';
104-
}
96+
/* Truncate domain, leave only machine name */
97+
dot = strchr(name, '.');
98+
if(dot)
99+
*dot = '\0';
105100

106101
return 0;
107102
#endif

0 commit comments

Comments
 (0)