chiark / gitweb /
util: introduce sethostname_idempotent
authorMichal Sekletar <msekleta@redhat.com>
Tue, 21 Oct 2014 16:17:54 +0000 (18:17 +0200)
committerMichal Sekletar <msekleta@redhat.com>
Mon, 27 Oct 2014 09:37:46 +0000 (10:37 +0100)
Function queries system hostname and applies changes only when necessary. Also,
migrate all client of sethostname to sethostname_idempotent while at it.

src/core/hostname-setup.c
src/hostname/hostnamed.c
src/nspawn/nspawn.c
src/shared/util.c
src/shared/util.h

index 8aa1cff1d30f23ad1a42826a487a7e8540a11beb..57baa7927504197d881a024ede7304cfad18ad3a 100644 (file)
@@ -82,7 +82,7 @@ int hostname_setup(void) {
                 hn = "localhost";
         }
 
-        if (sethostname(hn, strlen(hn)) < 0) {
+        if (sethostname_idempotent(hn) < 0) {
                 log_warning("Failed to set hostname to <%s>: %m", hn);
                 return -errno;
         }
index 0cffb5f683a742f0febcd2fdd2c6181f4e3f8dac..a449610bb86c2593c3d0408ebab2dc82990b2293 100644 (file)
@@ -287,7 +287,7 @@ static int context_update_kernel_hostname(Context *c) {
         else
                 hn = "localhost";
 
-        if (sethostname(hn, strlen(hn)) < 0)
+        if (sethostname_idempotent(hn) < 0)
                 return -errno;
 
         return 0;
index c567c8d2720fb8ae210e49f22107ccb0154fdc2a..b6d9bc631cb7adf55223806b00d4032dd6d910b4 100644 (file)
@@ -1289,7 +1289,7 @@ static int setup_hostname(void) {
         if (arg_share_system)
                 return 0;
 
-        if (sethostname(arg_machine, strlen(arg_machine)) < 0)
+        if (sethostname_idempotent(arg_machine) < 0)
                 return -errno;
 
         return 0;
index bc97c67f768900abdd06462d2eb0dc91cb37cd9e..7d94a28302f7d49d6e54d0c66a06e84cb793e2aa 100644 (file)
@@ -7175,3 +7175,23 @@ int free_and_strdup(char **p, const char *s) {
 
         return 0;
 }
+
+int sethostname_idempotent(const char *s) {
+        int r;
+        char buf[HOST_NAME_MAX + 1] = {};
+
+        assert(s);
+
+        r = gethostname(buf, sizeof(buf));
+        if (r < 0)
+                return -errno;
+
+        if (streq(buf, s))
+                return 0;
+
+        r = sethostname(buf, strlen(buf));
+        if (r < 0)
+                return -errno;
+
+        return 1;
+}
index 887cdc4a445413bbfccba6168f1f883ef91c89f3..35584467c15df5b87eac8b6ad15bd45065281979 100644 (file)
@@ -997,3 +997,5 @@ int unquote_first_word(const char **p, char **ret);
 int unquote_many_words(const char **p, ...) _sentinel_;
 
 int free_and_strdup(char **p, const char *s);
+
+int sethostname_idempotent(const char *s);