xref: /freebsd/libexec/nuageinit/tests/sethostname.lua (revision e508c3431d8e1ace6118e150837a0d0d67f1672a)
1#!/usr/libexec/flua
2---
3-- SPDX-License-Identifier: BSD-2-Clause
4--
5-- Copyright (c) 2026 Baptiste Daroussin <bapt@FreeBSD.org>
6
7local n = require("nuage")
8
9local root = os.getenv("NUAGE_FAKE_ROOTDIR")
10if not root then
11	root = ""
12end
13
14local hostnamepath = root .. "/etc/rc.conf.d/hostname"
15
16local function check_hostname(expected)
17	local f = io.open(hostnamepath, "r")
18	if not f then
19		n.err("hostname file not found, expected: " .. expected)
20	end
21	local content = f:read("*a")
22	f:close()
23	local expected_content = "hostname=" .. n.shell_escape(expected) .. "\n"
24	if content ~= expected_content then
25		n.err("hostname mismatch: got '" .. content ..
26		    "', expected '" .. expected_content .. "'")
27	end
28end
29
30local function check_no_hostname()
31	if io.open(hostnamepath, "r") then
32		n.err("hostname file should not exist")
33	end
34end
35
36-- nil hostname: no-op
37n.sethostname(nil)
38check_no_hostname()
39
40-- Empty hostname: invalid
41n.sethostname("")
42check_no_hostname()
43
44-- Hostname too long (>253 chars): invalid
45n.sethostname(string.rep("a", 254))
46check_no_hostname()
47
48-- Invalid characters: invalid
49n.sethostname("host;name")
50check_no_hostname()
51
52-- Starts with dot: invalid
53n.sethostname(".hostname")
54check_no_hostname()
55
56-- Ends with hyphen: invalid
57n.sethostname("hostname-")
58check_no_hostname()
59
60-- Label too long (>63 chars): invalid
61n.sethostname(string.rep("a", 64) .. ".example.com")
62check_no_hostname()
63
64-- Label starts with hyphen: invalid
65n.sethostname("myhost.-label.com")
66check_no_hostname()
67
68-- Valid simple hostname
69n.sethostname("myhostname")
70check_hostname("myhostname")
71
72-- Final: set a valid hostname for the shell test
73n.sethostname("myhostname")
74