Reputation: 3641
#include <stdio.h>
#include <unistd.h>
int main (int argc, char *argv[]) {
char buf[4];
int err = gethostname(buf, 4);
printf("name: %s n: %d\n", buf, err); // BUG: err should be -1, and errno should give ENAMETOOLONG
return 0;
}
on OSX, this gives:
name: xyz n: 0
even though my hostname is larger than 3; instead I would expect err to be -1 and errno to be ENAMETOOLONG
;
note that this can also give rise to buffer overflow errors in case user isn't aware of this bug and would expect err to be -1 when buffer was too short (docs say that \0
isn't written to buffer if buffer is too short), so printf as above is unsound even with err == 0. I've observed this while investigating https://github.com/nim-lang/Nim/issues/18088.
is that a bug? if so, where to report it?
Upvotes: 0
Views: 162
Reputation: 754110
The macOS manual says:
ERRORS
The following errors may be returned by these calls:
…
[ENAMETOOLONG]
The current host name is longer than namelen. (For gethostname() only.)
It also documents:
Host names are limited in length to {
sysconf(_SC_HOST_NAME_MAX)
} characters, not including the trailing null, currently 255.
The manual also mentions {_POSIX_HOST_NAME_MAX}
.
See also the POSIX specification of gethostname()
which says:
The
gethostname()
function shall return the standard host name for the current machine. Thenamelen
argument shall specify the size of the array pointed to by the name argument. The returned name shall be null-terminated, except that ifnamelen
is an insufficient length to hold the host name, then the returned name shall be truncated and it is unspecified whether the returned name is null-terminated.Host names are limited to
{HOST_NAME_MAX}
bytes.…
Host names are limited to {HOST_NAME_MAX} bytes.
You should be taking steps to avoid using a string that is too short, and using sysconf()
is one way to do so.
Since POSIX doesn't specify any errors, it is not clear that you have a bug to report, though I agree that the man page implies that you should get an ENAMETOOLONG
error.
Upvotes: 1