Denis Vlasenko | d686482 | 2008-02-25 23:24:32 +0000 | [diff] [blame] | 1 | /* vi: set sw=4 ts=4: */ |
| 2 | /* |
| 3 | * Safe gethostname implementation for busybox |
| 4 | * |
| 5 | * Copyright (C) 2008 Tito Ragusa <farmatito@tiscali.it> |
| 6 | * |
Denys Vlasenko | 0ef64bd | 2010-08-16 20:14:46 +0200 | [diff] [blame] | 7 | * Licensed under GPLv2 or later, see file LICENSE in this source tree. |
Denis Vlasenko | d686482 | 2008-02-25 23:24:32 +0000 | [diff] [blame] | 8 | */ |
Denis Vlasenko | d686482 | 2008-02-25 23:24:32 +0000 | [diff] [blame] | 9 | /* |
| 10 | * SUSv2 guarantees that "Host names are limited to 255 bytes" |
| 11 | * POSIX.1-2001 guarantees that "Host names (not including the terminating |
| 12 | * null byte) are limited to HOST_NAME_MAX bytes" (64 bytes on my box). |
| 13 | * |
| 14 | * RFC1123 says: |
| 15 | * |
| 16 | * The syntax of a legal Internet host name was specified in RFC-952 |
| 17 | * [DNS:4]. One aspect of host name syntax is hereby changed: the |
| 18 | * restriction on the first character is relaxed to allow either a |
| 19 | * letter or a digit. Host software MUST support this more liberal |
| 20 | * syntax. |
| 21 | * |
| 22 | * Host software MUST handle host names of up to 63 characters and |
| 23 | * SHOULD handle host names of up to 255 characters. |
| 24 | */ |
Denis Vlasenko | d686482 | 2008-02-25 23:24:32 +0000 | [diff] [blame] | 25 | #include "libbb.h" |
| 26 | #include <sys/utsname.h> |
| 27 | |
| 28 | /* |
| 29 | * On success return the current malloced and NUL terminated hostname. |
| 30 | * On error return malloced and NUL terminated string "?". |
| 31 | * This is an illegal first character for a hostname. |
| 32 | * The returned malloced string must be freed by the caller. |
| 33 | */ |
Denis Vlasenko | defc1ea | 2008-06-27 02:52:20 +0000 | [diff] [blame] | 34 | char* FAST_FUNC safe_gethostname(void) |
Denis Vlasenko | d686482 | 2008-02-25 23:24:32 +0000 | [diff] [blame] | 35 | { |
| 36 | struct utsname uts; |
| 37 | |
| 38 | /* The length of the arrays in a struct utsname is unspecified; |
| 39 | * the fields are terminated by a null byte. |
| 40 | * Note that there is no standard that says that the hostname |
| 41 | * set by sethostname(2) is the same string as the nodename field of the |
| 42 | * struct returned by uname (indeed, some systems allow a 256-byte host- |
| 43 | * name and an 8-byte nodename), but this is true on Linux. The same holds |
| 44 | * for setdomainname(2) and the domainname field. |
| 45 | */ |
Denis Vlasenko | c693840 | 2008-03-24 02:18:03 +0000 | [diff] [blame] | 46 | |
Denis Vlasenko | d686482 | 2008-02-25 23:24:32 +0000 | [diff] [blame] | 47 | /* Uname can fail only if you pass a bad pointer to it. */ |
| 48 | uname(&uts); |
Denis Vlasenko | c94d356 | 2008-06-30 13:30:21 +0000 | [diff] [blame] | 49 | return xstrndup(!uts.nodename[0] ? "?" : uts.nodename, sizeof(uts.nodename)); |
| 50 | } |