From 851c706e74acf0f76ee39e0c9ffa75f1e2ed1e23 Mon Sep 17 00:00:00 2001 From: Yu Watanabe Date: Wed, 12 Mar 2025 06:44:21 +0900 Subject: [PATCH 1/2] test: add test cases for hostname_substitute_wildcards() The function is indirectly tested through read_etc_hostname(), but let's also test it directly. --- src/test/test-hostname-setup.c | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/test/test-hostname-setup.c b/src/test/test-hostname-setup.c index da6e379699..8243d600e1 100644 --- a/src/test/test-hostname-setup.c +++ b/src/test/test-hostname-setup.c @@ -76,6 +76,32 @@ TEST(read_etc_hostname) { assert(hostname == (char*) 0x1234); /* does not touch argument on error */ } +TEST(hostname_substitute_wildcards) { + int r; + + r = sd_id128_get_machine(NULL); + if (ERRNO_IS_NEG_MACHINE_ID_UNSET(r)) + return (void) log_tests_skipped_errno(r, "skipping wildcard hostname tests, no machine ID defined"); + + _cleanup_free_ char *buf = NULL; + ASSERT_NOT_NULL((buf = strdup(""))); + ASSERT_OK(hostname_substitute_wildcards(buf)); + ASSERT_STREQ(buf, ""); + ASSERT_NULL((buf = mfree(buf))); + + ASSERT_NOT_NULL((buf = strdup("hogehoge"))); + ASSERT_OK(hostname_substitute_wildcards(buf)); + ASSERT_STREQ(buf, "hogehoge"); + ASSERT_NULL((buf = mfree(buf))); + + ASSERT_NOT_NULL((buf = strdup("hoge??hoge??foo?"))); + ASSERT_OK(hostname_substitute_wildcards(buf)); + log_debug("hostname_substitute_wildcards(\"hoge??hoge??foo?\"): → \"%s\"", buf); + ASSERT_EQ(fnmatch("hoge??hoge??foo?", buf, /* flags= */ 0), 0); + ASSERT_TRUE(hostname_is_valid(buf, /* flags= */ 0)); + ASSERT_NULL((buf = mfree(buf))); +} + TEST(hostname_setup) { hostname_setup(false); } From 35d5defc4e78fa97730370762953a58a27f9f560 Mon Sep 17 00:00:00 2001 From: Yu Watanabe Date: Wed, 12 Mar 2025 06:46:36 +0900 Subject: [PATCH 2/2] hostname-setup: use strchr() to find wildcard character Addresses https://github.com/systemd/systemd/pull/36647#discussion_r1990048751. --- src/shared/hostname-setup.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/shared/hostname-setup.c b/src/shared/hostname-setup.c index af89f92bdc..33b6a05ad8 100644 --- a/src/shared/hostname-setup.c +++ b/src/shared/hostname-setup.c @@ -268,9 +268,10 @@ int hostname_substitute_wildcards(char *name) { * Note that this does not directly use the machine ID, because that's not necessarily supposed to be * public information to be broadcast on the network, while the hostname certainly is. */ - for (char *n = name; *n; n++) { - if (*n != '?') - continue; + for (char *n = name; ; n++) { + n = strchr(n, '?'); + if (!n) + return 0; if (left_bits <= 0) { if (sd_id128_is_null(mid)) { @@ -293,8 +294,6 @@ int hostname_substitute_wildcards(char *name) { h >>= 4; left_bits -= 4; } - - return 0; } char* get_default_hostname(void) {