chiark / gitweb /
hostnamed: introduce systemd-hostnamed
[elogind.git] / src / hostnamed.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <dbus/dbus.h>
23
24 #include <errno.h>
25 #include <string.h>
26 #include <unistd.h>
27
28 #include "util.h"
29 #include "strv.h"
30 #include "dbus-common.h"
31
32 #define INTROSPECTION                                                   \
33         DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE                       \
34         "<node>\n"                                                      \
35         " <interface name=\"org.freedesktop.hostname1\">\n"             \
36         "  <property name=\"Hostname\" type=\"s\" access=\"read\"/>\n"  \
37         "  <property name=\"StaticHostname\" type=\"s\" access=\"read\"/>\n" \
38         "  <property name=\"PrettyHostname\" type=\"s\" access=\"read\"/>\n" \
39         "  <property name=\"IconName\" type=\"s\" access=\"read\"/>\n"  \
40         "  <method name=\"SetHostname\">\n"                             \
41         "   <arg name=\"name\" type=\"s\" direction=\"in\"/>\n"         \
42         "   <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
43         "  </method>\n"                                                 \
44         "  <method name=\"SetStaticHostname\">\n"                       \
45         "   <arg name=\"name\" type=\"s\" direction=\"in\"/>\n"         \
46         "   <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
47         "  </method>\n"                                                 \
48         "  <method name=\"SetPrettyHostname\">\n"                       \
49         "   <arg name=\"name\" type=\"s\" direction=\"in\"/>\n"         \
50         "   <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
51         "  </method>\n"                                                 \
52         "  <method name=\"SetIconName\">\n"                             \
53         "   <arg name=\"name\" type=\"s\" direction=\"in\"/>\n"         \
54         "   <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
55         "  </method>\n"                                                 \
56         " </interface>\n"                                               \
57         BUS_PROPERTIES_INTERFACE                                        \
58         BUS_INTROSPECTABLE_INTERFACE                                    \
59         BUS_PEER_INTERFACE                                              \
60         "</node>\n"
61
62 #define INTERFACES_LIST                         \
63         BUS_GENERIC_INTERFACES_LIST             \
64         "org.freedesktop.hostname1\0"
65
66 enum {
67         PROP_HOSTNAME,
68         PROP_STATIC_HOSTNAME,
69         PROP_PRETTY_HOSTNAME,
70         PROP_ICON_NAME,
71         _PROP_MAX
72 };
73
74 static char *data[_PROP_MAX] = {
75         NULL,
76         NULL,
77         NULL,
78         NULL
79 };
80
81 static void free_data(void) {
82         int p;
83
84         for (p = 0; p < _PROP_MAX; p++) {
85                 free(data[p]);
86                 data[p] = NULL;
87         }
88 }
89
90 static int read_data(void) {
91         int r;
92
93         free_data();
94
95         data[PROP_HOSTNAME] = gethostname_malloc();
96         if (!data[PROP_HOSTNAME])
97                 return -ENOMEM;
98
99         r = read_one_line_file("/etc/hostname", &data[PROP_STATIC_HOSTNAME]);
100         if (r < 0 && r != -ENOENT)
101                 return r;
102
103         r = parse_env_file("/etc/machine-info", NEWLINE,
104                            "PRETTY_HOSTNAME", &data[PROP_PRETTY_HOSTNAME],
105                            "ICON_NAME", &data[PROP_ICON_NAME],
106                            NULL);
107         if (r < 0 && r != -ENOENT)
108                 return r;
109
110         return 0;
111 }
112
113 static const char* fallback_icon_name(void) {
114
115 #if defined(__i386__) || defined(__x86_64__)
116         int r;
117         char *type;
118         unsigned t;
119 #endif
120
121         if (detect_virtualization(NULL) > 0)
122                 return "computer-vm";
123
124 #if defined(__i386__) || defined(__x86_64__)
125         r = read_one_line_file("/sys/class/dmi/id/chassis_type", &type);
126         if (r < 0)
127                 return NULL;
128
129         r = safe_atou(type, &t);
130         free(type);
131
132         if (r < 0)
133                 return NULL;
134
135         /* We only list the really obvious cases here. The DMI data is
136            unreliable enough, so let's not do any additional guesswork
137            on top of that. */
138
139         switch (t) {
140
141         case 0x3:
142         case 0x4:
143         case 0x6:
144         case 0x7:
145                 return "computer-desktop";
146
147         case 0x9:
148         case 0xA:
149         case 0xE:
150                 return "computer-laptop";
151
152         case 0x11:
153                 return "computer-server";
154         }
155
156 #endif
157         return NULL;
158 }
159
160 static int write_data_hostname(void) {
161         const char *hn;
162
163         if (isempty(data[PROP_HOSTNAME]))
164                 hn = "localhost";
165         else
166                 hn = data[PROP_HOSTNAME];
167
168         if (sethostname(hn, strlen(hn)) < 0)
169                 return -errno;
170
171         return 0;
172 }
173
174 static int write_data_static_hostname(void) {
175
176         if (isempty(data[PROP_STATIC_HOSTNAME])) {
177
178                 if (unlink("/etc/hostname") < 0)
179                         return errno == ENOENT ? 0 : -errno;
180
181                 return 0;
182         }
183
184         return write_one_line_file("/etc/hostname", data[PROP_STATIC_HOSTNAME]);
185 }
186
187 static int write_data_other(void) {
188         static const char * const name[_PROP_MAX] = {
189                 [PROP_PRETTY_HOSTNAME] = "PRETTY_HOSTNAME",
190                 [PROP_ICON_NAME] = "ICON_NAME"
191         };
192
193         char **l = NULL;
194         int r, p;
195
196         r = load_env_file("/etc/machine-info", &l);
197         if (r < 0 && r != -ENOENT)
198                 return r;
199
200         for (p = 2; p < _PROP_MAX; p++) {
201                 char *t, **u;
202
203                 assert(name[p]);
204
205                 if (isempty(data[p]))  {
206                         l = strv_env_unset(l, name[p]);
207                         continue;
208                 }
209
210                 if (asprintf(&t, "%s=%s", name[p], strempty(data[p])) < 0) {
211                         strv_free(l);
212                         return -ENOMEM;
213                 }
214
215                 u = strv_env_set(l, t);
216                 free(t);
217                 strv_free(l);
218
219                 if (!u)
220                         return -ENOMEM;
221                 l = u;
222         }
223
224         if (strv_isempty(l)) {
225
226                 if (unlink("/etc/machine-info") < 0)
227                         return errno == ENOENT ? 0 : -errno;
228
229                 return 0;
230         }
231
232         r = write_env_file("/etc/machine-info", l);
233         strv_free(l);
234
235         return r;
236 }
237
238 /* This mimics dbus_bus_get_unix_user() */
239 static pid_t get_unix_process_id(
240                 DBusConnection *connection,
241                 const char *name,
242                 DBusError *error) {
243
244         DBusMessage *m = NULL, *reply = NULL;
245         uint32_t pid = 0;
246
247         m = dbus_message_new_method_call(
248                         DBUS_SERVICE_DBUS,
249                         DBUS_PATH_DBUS,
250                         DBUS_INTERFACE_DBUS,
251                         "GetConnectionUnixProcessID");
252         if (!m) {
253                 dbus_set_error_const(error, DBUS_ERROR_NO_MEMORY, NULL);
254                 goto finish;
255         }
256
257         if (!dbus_message_append_args(
258                             m,
259                             DBUS_TYPE_STRING, &name,
260                             DBUS_TYPE_INVALID)) {
261                 dbus_set_error_const(error, DBUS_ERROR_NO_MEMORY, NULL);
262                 goto finish;
263         }
264
265         reply = dbus_connection_send_with_reply_and_block(connection, m, -1, error);
266         if (!reply)
267                 goto finish;
268
269         if (dbus_set_error_from_message(error, reply))
270                 goto finish;
271
272         if (!dbus_message_get_args(
273                             reply, error,
274                             DBUS_TYPE_UINT32, &pid,
275                             DBUS_TYPE_INVALID))
276                 goto finish;
277
278 finish:
279         if (m)
280                 dbus_message_unref(m);
281
282         if (reply)
283                 dbus_message_unref(reply);
284
285         return (pid_t) pid;
286 }
287
288 static int verify_polkit(
289                 DBusConnection *c,
290                 DBusMessage *request,
291                 const char *action,
292                 bool interactive,
293                 DBusError *error) {
294
295         DBusMessage *m = NULL, *reply = NULL;
296         const char *unix_process = "unix-process", *pid = "pid", *starttime = "start-time", *cancel_id = "";
297         const char *sender;
298         uint32_t flags = interactive ? 1 : 0;
299         pid_t pid_raw;
300         uint32_t pid_u32;
301         unsigned long long starttime_raw;
302         uint64_t starttime_u64;
303         DBusMessageIter iter_msg, iter_struct, iter_array, iter_dict, iter_variant;
304         int r;
305         dbus_bool_t authorized = FALSE;
306
307         assert(c);
308         assert(request);
309
310         sender = dbus_message_get_sender(request);
311         if (!sender)
312                 return -EINVAL;
313
314         pid_raw = get_unix_process_id(c, sender, error);
315         if (pid_raw == 0)
316                 return -EINVAL;
317
318         r = get_starttime_of_pid(pid_raw, &starttime_raw);
319         if (r < 0)
320                 return r;
321
322         m = dbus_message_new_method_call(
323                         "org.freedesktop.PolicyKit1",
324                         "/org/freedesktop/PolicyKit1/Authority",
325                         "org.freedesktop.PolicyKit1.Authority",
326                         "CheckAuthorization");
327         if (!m)
328                 return -ENOMEM;
329
330         dbus_message_iter_init_append(m, &iter_msg);
331
332         pid_u32 = (uint32_t) pid_raw;
333         starttime_u64 = (uint64_t) starttime_raw;
334
335         if (!dbus_message_iter_open_container(&iter_msg, DBUS_TYPE_STRUCT, NULL, &iter_struct) ||
336             !dbus_message_iter_append_basic(&iter_struct, DBUS_TYPE_STRING, &unix_process) ||
337             !dbus_message_iter_open_container(&iter_struct, DBUS_TYPE_ARRAY, "{sv}", &iter_array) ||
338             !dbus_message_iter_open_container(&iter_array, DBUS_TYPE_DICT_ENTRY, NULL, &iter_dict) ||
339             !dbus_message_iter_append_basic(&iter_dict, DBUS_TYPE_STRING, &pid) ||
340             !dbus_message_iter_open_container(&iter_dict, DBUS_TYPE_VARIANT, "u", &iter_variant) ||
341             !dbus_message_iter_append_basic(&iter_variant, DBUS_TYPE_UINT32, &pid_u32) ||
342             !dbus_message_iter_close_container(&iter_dict, &iter_variant) ||
343             !dbus_message_iter_close_container(&iter_array, &iter_dict) ||
344             !dbus_message_iter_open_container(&iter_array, DBUS_TYPE_DICT_ENTRY, NULL, &iter_dict) ||
345             !dbus_message_iter_append_basic(&iter_dict, DBUS_TYPE_STRING, &starttime) ||
346             !dbus_message_iter_open_container(&iter_dict, DBUS_TYPE_VARIANT, "t", &iter_variant) ||
347             !dbus_message_iter_append_basic(&iter_variant, DBUS_TYPE_UINT64, &starttime_u64) ||
348             !dbus_message_iter_close_container(&iter_dict, &iter_variant) ||
349             !dbus_message_iter_close_container(&iter_array, &iter_dict) ||
350             !dbus_message_iter_close_container(&iter_struct, &iter_array) ||
351             !dbus_message_iter_close_container(&iter_msg, &iter_struct) ||
352             !dbus_message_iter_append_basic(&iter_msg, DBUS_TYPE_STRING, &action) ||
353             !dbus_message_iter_open_container(&iter_msg, DBUS_TYPE_ARRAY, "{ss}", &iter_array) ||
354             !dbus_message_iter_close_container(&iter_msg, &iter_array) ||
355             !dbus_message_iter_append_basic(&iter_msg, DBUS_TYPE_UINT32, &flags) ||
356             !dbus_message_iter_append_basic(&iter_msg, DBUS_TYPE_STRING, &cancel_id)) {
357                 r = -ENOMEM;
358                 goto finish;
359         }
360
361         reply = dbus_connection_send_with_reply_and_block(c, m, -1, error);
362         if (!reply) {
363                 r = -EIO;
364                 goto finish;
365         }
366
367         if (dbus_set_error_from_message(error, reply)) {
368                 r = -EIO;
369                 goto finish;
370         }
371
372         if (!dbus_message_iter_init(reply, &iter_msg) ||
373             dbus_message_iter_get_arg_type(&iter_msg) != DBUS_TYPE_STRUCT) {
374                 r = -EIO;
375                 goto finish;
376         }
377
378         dbus_message_iter_recurse(&iter_msg, &iter_struct);
379
380         if (dbus_message_iter_get_arg_type(&iter_struct) != DBUS_TYPE_BOOLEAN) {
381                 r = -EIO;
382                 goto finish;
383         }
384
385         dbus_message_iter_get_basic(&iter_struct, &authorized);
386
387         r = authorized ? 0 : -EPERM;
388
389 finish:
390
391         if (m)
392                 dbus_message_unref(m);
393
394         if (reply)
395                 dbus_message_unref(reply);
396
397         return r;
398 }
399
400 static int bus_hostname_append_icon_name(DBusMessageIter *i, const char *property, void *userdata) {
401         const char *name;
402
403         assert(i);
404         assert(property);
405
406         if (isempty(data[PROP_ICON_NAME]))
407                 name = fallback_icon_name();
408         else
409                 name = data[PROP_ICON_NAME];
410
411         return bus_property_append_string(i, property, (void*) name);
412 }
413
414 static DBusHandlerResult hostname_message_handler(
415                 DBusConnection *connection,
416                 DBusMessage *message,
417                 void *userdata) {
418
419         const BusProperty properties[] = {
420                 { "org.freedesktop.hostname1", "Hostname",       bus_property_append_string,    "s", data[PROP_HOSTNAME]},
421                 { "org.freedesktop.hostname1", "StaticHostname", bus_property_append_string,    "s", data[PROP_STATIC_HOSTNAME]},
422                 { "org.freedesktop.hostname1", "PrettyHostname", bus_property_append_string,    "s", data[PROP_PRETTY_HOSTNAME]},
423                 { "org.freedesktop.hostname1", "IconName",       bus_hostname_append_icon_name, "s", data[PROP_ICON_NAME]},
424                 { NULL, NULL, NULL, NULL, NULL }
425         };
426
427         DBusMessage *reply = NULL, *changed = NULL;
428         DBusError error;
429         int r;
430
431         assert(connection);
432         assert(message);
433
434         dbus_error_init(&error);
435
436         if (dbus_message_is_method_call(message, "org.freedesktop.hostname1", "SetHostname")) {
437                 const char *name;
438                 dbus_bool_t interactive;
439
440                 if (!dbus_message_get_args(
441                                     message,
442                                     &error,
443                                     DBUS_TYPE_STRING, &name,
444                                     DBUS_TYPE_BOOLEAN, &interactive,
445                                     DBUS_TYPE_INVALID))
446                         return bus_send_error_reply(connection, message, &error, -EINVAL);
447
448                 if (isempty(name))
449                         name = data[PROP_STATIC_HOSTNAME];
450
451                 if (isempty(name))
452                         name = "localhost";
453
454                 if (!hostname_is_valid(name))
455                         return bus_send_error_reply(connection, message, NULL, -EINVAL);
456
457                 if (!streq_ptr(name, data[PROP_HOSTNAME])) {
458                         char *h;
459
460                         r = verify_polkit(connection, message, "org.freedesktop.hostname1.set-hostname", interactive, &error);
461                         if (r < 0)
462                                 return bus_send_error_reply(connection, message, &error, r);
463
464                         h = strdup(name);
465                         if (!h)
466                                 goto oom;
467
468                         free(data[PROP_HOSTNAME]);
469                         data[PROP_HOSTNAME] = h;
470
471                         r = write_data_hostname();
472                         if (r < 0)
473                                 return bus_send_error_reply(connection, message, NULL, r);
474
475                         log_info("Changed host name to '%s'", data[PROP_HOSTNAME]);
476
477                         changed = bus_properties_changed_new(
478                                         "/org/freedesktop/hostname1",
479                                         "org.freedesktop.hostname1",
480                                         "Hostname\0");
481                         if (!changed)
482                                 goto oom;
483                 }
484
485         } else if (dbus_message_is_method_call(message, "org.freedesktop.hostname1", "SetStaticHostname")) {
486                 const char *name;
487                 dbus_bool_t interactive;
488
489                 if (!dbus_message_get_args(
490                                     message,
491                                     &error,
492                                     DBUS_TYPE_STRING, &name,
493                                     DBUS_TYPE_BOOLEAN, &interactive,
494                                     DBUS_TYPE_INVALID))
495                         return bus_send_error_reply(connection, message, &error, -EINVAL);
496
497                 if (isempty(name))
498                         name = NULL;
499
500                 if (!streq_ptr(name, data[PROP_STATIC_HOSTNAME])) {
501
502                         r = verify_polkit(connection, message, "org.freedesktop.hostname1.set-static-hostname", interactive, &error);
503                         if (r < 0)
504                                 return bus_send_error_reply(connection, message, &error, r);
505
506                         if (isempty(name)) {
507                                 free(data[PROP_STATIC_HOSTNAME]);
508                                 data[PROP_STATIC_HOSTNAME] = NULL;
509                         } else {
510                                 char *h;
511
512                                 if (!hostname_is_valid(name))
513                                         return bus_send_error_reply(connection, message, NULL, -EINVAL);
514
515                                 h = strdup(name);
516                                 if (!h)
517                                         goto oom;
518
519                                 free(data[PROP_STATIC_HOSTNAME]);
520                                 data[PROP_STATIC_HOSTNAME] = h;
521                         }
522
523                         r = write_data_static_hostname();
524                         if (r < 0)
525                                 return bus_send_error_reply(connection, message, NULL, r);
526
527                         log_info("Changed static host name to '%s'", data[PROP_HOSTNAME]);
528
529                         changed = bus_properties_changed_new(
530                                         "/org/freedesktop/hostname1",
531                                         "org.freedesktop.hostname1",
532                                         "StaticHostname\0");
533                         if (!changed)
534                                 goto oom;
535                 }
536
537         } else if (dbus_message_is_method_call(message, "org.freedesktop.hostname1", "SetPrettyHostname") ||
538                    dbus_message_is_method_call(message, "org.freedesktop.hostname1", "SetIconName")) {
539
540                 const char *name;
541                 dbus_bool_t interactive;
542                 int k;
543
544                 if (!dbus_message_get_args(
545                                     message,
546                                     &error,
547                                     DBUS_TYPE_STRING, &name,
548                                     DBUS_TYPE_BOOLEAN, &interactive,
549                                     DBUS_TYPE_INVALID))
550                         return bus_send_error_reply(connection, message, &error, -EINVAL);
551
552                 if (isempty(name))
553                         name = NULL;
554
555                 k = streq(dbus_message_get_member(message), "SetPrettyHostname") ? PROP_PRETTY_HOSTNAME : PROP_ICON_NAME;
556
557                 if (!streq_ptr(name, data[k])) {
558
559                         r = verify_polkit(connection, message, "org.freedesktop.hostname1.set-machine-info", interactive, &error);
560                         if (r < 0)
561                                 return bus_send_error_reply(connection, message, &error, r);
562
563                         if (isempty(name)) {
564                                 free(data[k]);
565                                 data[k] = NULL;
566                         } else {
567                                 char *h;
568
569                                 h = strdup(name);
570                                 if (!h)
571                                         goto oom;
572
573                                 free(data[k]);
574                                 data[k] = h;
575                         }
576
577                         r = write_data_other();
578                         if (r < 0)
579                                 return bus_send_error_reply(connection, message, NULL, r);
580
581                         log_info("Changed %s to '%s'", k == PROP_PRETTY_HOSTNAME ? "pretty host name" : "icon name", data[k]);
582
583                         changed = bus_properties_changed_new(
584                                         "/org/freedesktop/hostname1",
585                                         "org.freedesktop.hostname1",
586                                         k == PROP_PRETTY_HOSTNAME ? "PrettyHostname\0" : "IconName\0");
587                         if (!changed)
588                                 goto oom;
589                 }
590
591         } else
592                 return bus_default_message_handler(connection, message, INTROSPECTION, INTERFACES_LIST, properties);
593
594         if (!(reply = dbus_message_new_method_return(message)))
595                 goto oom;
596
597         if (!dbus_connection_send(connection, reply, NULL))
598                 goto oom;
599
600         dbus_message_unref(reply);
601         reply = NULL;
602
603         if (changed) {
604
605                 if (!dbus_connection_send(connection, changed, NULL))
606                         goto oom;
607
608                 dbus_message_unref(changed);
609         }
610
611         return DBUS_HANDLER_RESULT_HANDLED;
612
613 oom:
614         if (reply)
615                 dbus_message_unref(reply);
616
617         if (changed)
618                 dbus_message_unref(changed);
619
620         dbus_error_free(&error);
621
622         return DBUS_HANDLER_RESULT_NEED_MEMORY;
623 }
624
625 int main(int argc, char *argv[]) {
626         const DBusObjectPathVTable hostname_vtable = {
627                 .message_function = hostname_message_handler
628         };
629
630         DBusConnection *bus = NULL;
631         DBusError error;
632         int r;
633
634         dbus_error_init(&error);
635
636         log_set_target(LOG_TARGET_AUTO);
637         log_parse_environment();
638         log_open();
639
640         if (argc != 1) {
641                 log_error("This program takes no arguments.");
642                 r = -EINVAL;
643                 goto finish;
644         }
645
646         umask(0022);
647
648         r = read_data();
649         if (r < 0) {
650                 log_error("Failed to read hostname data: %s", strerror(-r));
651                 goto finish;
652         }
653
654         bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
655         if (!bus) {
656                 log_error("Failed to get system D-Bus connection: %s", error.message);
657                 r = -ECONNREFUSED;
658                 goto finish;
659         }
660
661         if (!dbus_connection_register_object_path(bus, "/org/freedesktop/hostname1", &hostname_vtable, NULL)) {
662                 log_error("Not enough memory");
663                 r = -ENOMEM;
664                 goto finish;
665         }
666
667         if (dbus_bus_request_name(bus, "org.freedesktop.hostname1", DBUS_NAME_FLAG_DO_NOT_QUEUE, &error) < 0) {
668                 log_error("Failed to register name on bus: %s", error.message);
669                 goto finish;
670         }
671
672         while (dbus_connection_read_write_dispatch(bus, -1))
673                 ;
674
675         r = 0;
676
677 finish:
678         free_data();
679
680         if (bus) {
681                 dbus_connection_flush(bus);
682                 dbus_connection_close(bus);
683                 dbus_connection_unref(bus);
684         }
685
686         dbus_error_free(&error);
687
688         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
689 }