1 # $NetBSD: 30-hostname,v 1.7 2015/08/21 10:39:00 roy Exp $
3 # Set the hostname from DHCP data if required
5 # A hostname can either be a short hostname or a FQDN.
10 # A value of server means just what the server says, don't manipulate it.
11 # This could lead to an inconsistent hostname on a DHCPv4 and DHCPv6 network
12 # where the DHCPv4 hostname is short and the DHCPv6 has an FQDN.
13 # DHCPv6 has no hostname option.
14 # RFC4702 section 3.1 says FQDN should be prefered over hostname.
16 # As such, the default is hostname_fqdn=true so that a consistent hostname
18 : ${hostname_fqdn:=true}
20 # Some systems don't have hostname(1)
26 if type hostname >/dev/null 2>&1; then
28 elif [ -r /proc/sys/kernel/hostname ]; then
29 read name </proc/sys/kernel/hostname && echo "$name"
30 elif sysctl kern.hostname >/dev/null 2>&1; then
31 sysctl -n kern.hostname
32 elif sysctl kernel.hostname >/dev/null 2>&1; then
33 sysctl -n kernel.hostname
40 # Always prefer hostname(1) if we have it
41 if type hostname >/dev/null 2>&1; then
43 elif [ -w /proc/sys/kernel/hostname ]; then
44 echo "$1" >/proc/sys/kernel/hostname
45 elif sysctl kern.hostname >/dev/null 2>&1; then
46 sysctl -w "kern.hostname=$1"
47 elif sysctl kernel.hostname >/dev/null 2>&1; then
48 sysctl -w "kernel.hostname=$1"
50 # We know this will fail, but it will now fail
51 # with an error to stdout
58 local hostname hfqdn=false hshort=false
60 case "$force_hostname" in
61 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|1) return 0;;
64 hostname="$(_hostname)"
66 ""|"(none)"|localhost|localhost.localdomain) return 0;;
69 case "$hostname_fqdn" in
70 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|1) hfqdn=true;;
71 [Ss][Ee][Rr][Vv][Ee][Rr]) ;;
75 if [ -n "$old_fqdn" ]; then
76 if ${hfqdn} || ! ${hsort}; then
77 [ "$hostname" = "$old_fqdn" ]
79 [ "$hostname" = "${old_fqdn%%.*}" ]
81 elif [ -n "$old_host_name" ]; then
83 if [ -n "$old_domain_name" -a \
84 "$old_host_name" = "${old_host_name#*.}" ]
87 "$old_host_name.$old_domain_name" ]
89 [ "$hostname" = "$old_host_name" ]
92 [ "$hostname" = "${old_host_name%%.*}" ]
94 [ "$hostname" = "$old_host_name" ]
105 if valid_domainname "$1"; then
108 syslog err "Invalid hostname: $1"
114 local hfqdn=false hshort=false
116 need_hostname || return
118 case "$hostname_fqdn" in
119 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|1) hfqdn=true;;
124 if [ -n "$new_fqdn" ]; then
125 if ${hfqdn} || ! ${hshort}; then
126 try_hostname "$new_fqdn"
128 try_hostname "${new_fqdn%%.*}"
130 elif [ -n "$new_host_name" ]; then
132 if [ -n "$new_domain_name" -a \
133 "$new_host_name" = "${new_host_name#*.}" ]
135 try_hostname "$new_host_name.$new_domain_name"
137 try_hostname "$new_host_name"
140 try_hostname "${new_host_name%%.*}"
142 try_hostname "$new_host_name"
147 # For ease of use, map DHCP6 names onto our DHCP4 names
149 BOUND6|RENEW6|REBIND6|REBOOT6|INFORM6)
150 new_fqdn="$new_dhcp6_fqdn"
151 old_fqdn="$old_dhcp6_fqdn"