1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2011 Lennart Poettering
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.
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.
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/>.
22 #include <dbus/dbus.h>
30 #include "dbus-common.h"
34 #define NULL_ADJTIME_UTC "0.0 0 0\n0\nUTC\n"
35 #define NULL_ADJTIME_LOCAL "0.0 0 0\n0\nLOCAL\n"
38 " <interface name=\"org.freedesktop.timedate1\">\n" \
39 " <property name=\"Timezone\" type=\"s\" access=\"read\"/>\n" \
40 " <property name=\"LocalRTC\" type=\"b\" access=\"read\"/>\n" \
41 " <property name=\"NTP\" type=\"b\" access=\"read\"/>\n" \
42 " <method name=\"SetTime\">\n" \
43 " <arg name=\"usec_utc\" type=\"x\" direction=\"in\"/>\n" \
44 " <arg name=\"relative\" type=\"b\" direction=\"in\"/>\n" \
45 " <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
47 " <method name=\"SetTimezone\">\n" \
48 " <arg name=\"timezone\" type=\"s\" direction=\"in\"/>\n" \
49 " <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
51 " <method name=\"SetLocalRTC\">\n" \
52 " <arg name=\"local_rtc\" type=\"b\" direction=\"in\"/>\n" \
53 " <arg name=\"fix_system\" type=\"b\" direction=\"in\"/>\n" \
54 " <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
56 " <method name=\"SetNTP\">\n" \
57 " <arg name=\"use_ntp\" type=\"b\" direction=\"in\"/>\n" \
58 " <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
62 #define INTROSPECTION \
63 DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
66 BUS_PROPERTIES_INTERFACE \
67 BUS_INTROSPECTABLE_INTERFACE \
71 #define INTERFACES_LIST \
72 BUS_GENERIC_INTERFACES_LIST \
73 "org.freedesktop.timedate1\0"
75 const char timedate_interface[] _introspect_("timedate1") = INTERFACE;
87 static usec_t remain_until;
89 static void free_data(void) {
96 static bool valid_timezone(const char *name) {
105 if (*name == '/' || *name == 0)
108 for (p = name; *p; p++) {
109 if (!(*p >= '0' && *p <= '9') &&
110 !(*p >= 'a' && *p <= 'z') &&
111 !(*p >= 'A' && *p <= 'Z') &&
112 !(*p == '-' || *p == '_' || *p == '+' || *p == '/'))
128 t = strappend("/usr/share/zoneinfo/", name);
138 if (!S_ISREG(st.st_mode))
144 static void verify_timezone(void) {
145 char *p, *a = NULL, *b = NULL;
152 p = strappend("/usr/share/zoneinfo/", tz.zone);
154 log_error("Out of memory");
158 j = read_full_file("/etc/localtime", &a, &l);
159 k = read_full_file(p, &b, &q);
163 if (j < 0 || k < 0 || l != q || memcmp(a, b, l)) {
164 log_warning("/etc/localtime and /etc/timezone out of sync.");
173 static int read_data(void) {
178 r = read_one_line_file("/etc/timezone", &tz.zone);
181 log_warning("Failed to read /etc/timezone: %s", strerror(-r));
184 r = parse_env_file("/etc/sysconfig/clock", NEWLINE,
188 if (r < 0 && r != -ENOENT)
189 log_warning("Failed to read /etc/sysconfig/clock: %s", strerror(-r));
193 if (isempty(tz.zone)) {
200 tz.local_rtc = hwclock_is_localtime() > 0;
205 static int write_data_timezone(void) {
210 if (unlink("/etc/timezone") < 0 && errno != ENOENT)
213 if (unlink("/etc/localtime") < 0 && errno != ENOENT)
219 p = strappend("/usr/share/zoneinfo/", tz.zone);
221 log_error("Out of memory");
225 r = symlink_or_copy_atomic(p, "/etc/localtime");
231 r = write_one_line_file_atomic("/etc/timezone", tz.zone);
238 static int write_data_local_rtc(void) {
242 r = read_full_file("/etc/adjtime", &s, NULL);
250 w = strdup(NULL_ADJTIME_LOCAL);
263 p = strchr(p+1, '\n');
279 w = new(char, a + (tz.local_rtc ? 5 : 3) + b + 1);
285 *(char*) mempcpy(stpcpy(mempcpy(w, s, a), tz.local_rtc ? "LOCAL" : "UTC"), e, b) = 0;
287 if (streq(w, NULL_ADJTIME_UTC)) {
290 if (unlink("/etc/adjtime") < 0) {
299 r = write_one_line_file_atomic("/etc/adjtime", w);
305 static int read_ntp(DBusConnection *bus) {
306 DBusMessage *m = NULL, *reply = NULL;
307 const char *name = "ntpd.service", *s;
313 dbus_error_init(&error);
315 m = dbus_message_new_method_call(
316 "org.freedesktop.systemd1",
317 "/org/freedesktop/systemd1",
318 "org.freedesktop.systemd1.Manager",
322 log_error("Out of memory");
327 if (!dbus_message_append_args(m,
328 DBUS_TYPE_STRING, &name,
329 DBUS_TYPE_INVALID)) {
330 log_error("Could not append arguments to message.");
335 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
337 log_error("Failed to issue method call: %s", bus_error_message(&error));
342 if (!dbus_message_get_args(reply, &error,
343 DBUS_TYPE_STRING, &s,
344 DBUS_TYPE_INVALID)) {
345 log_error("Failed to parse reply: %s", bus_error_message(&error));
351 streq(s, "enabled") ||
352 streq(s, "enabled-runtime");
357 dbus_message_unref(m);
360 dbus_message_unref(reply);
362 dbus_error_free(&error);
367 static int start_ntp(DBusConnection *bus, DBusError *error) {
368 DBusMessage *m = NULL, *reply = NULL;
369 const char *name = "ntpd.service", *mode = "replace";
375 m = dbus_message_new_method_call(
376 "org.freedesktop.systemd1",
377 "/org/freedesktop/systemd1",
378 "org.freedesktop.systemd1.Manager",
379 tz.use_ntp ? "StartUnit" : "StopUnit");
381 log_error("Could not allocate message.");
386 if (!dbus_message_append_args(m,
387 DBUS_TYPE_STRING, &name,
388 DBUS_TYPE_STRING, &mode,
389 DBUS_TYPE_INVALID)) {
390 log_error("Could not append arguments to message.");
395 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error);
397 log_error("Failed to issue method call: %s", bus_error_message(error));
406 dbus_message_unref(m);
409 dbus_message_unref(reply);
414 static int enable_ntp(DBusConnection *bus, DBusError *error) {
415 DBusMessage *m = NULL, *reply = NULL;
416 const char * const names[] = { "ntpd.service", NULL };
418 DBusMessageIter iter;
419 dbus_bool_t f = FALSE, t = TRUE;
424 m = dbus_message_new_method_call(
425 "org.freedesktop.systemd1",
426 "/org/freedesktop/systemd1",
427 "org.freedesktop.systemd1.Manager",
428 tz.use_ntp ? "EnableUnitFiles" : "DisableUnitFiles");
431 log_error("Could not allocate message.");
436 dbus_message_iter_init_append(m, &iter);
438 r = bus_append_strv_iter(&iter, (char**) names);
440 log_error("Failed to append unit files.");
443 /* send runtime bool */
444 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &f)) {
445 log_error("Failed to append runtime boolean.");
451 /* send force bool */
452 if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_BOOLEAN, &t)) {
453 log_error("Failed to append force boolean.");
459 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error);
461 log_error("Failed to issue method call: %s", bus_error_message(error));
466 dbus_message_unref(m);
467 m = dbus_message_new_method_call(
468 "org.freedesktop.systemd1",
469 "/org/freedesktop/systemd1",
470 "org.freedesktop.systemd1.Manager",
473 log_error("Could not allocate message.");
478 dbus_message_unref(reply);
479 reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error);
481 log_error("Failed to issue method call: %s", bus_error_message(error));
490 dbus_message_unref(m);
493 dbus_message_unref(reply);
498 static int property_append_ntp(DBusMessageIter *i, const char *property, void *data) {
506 if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &db))
512 static const BusProperty bus_timedate_properties[] = {
513 { "Timezone", bus_property_append_string, "s", offsetof(TZ, zone), true },
514 { "LocalRTC", bus_property_append_bool, "b", offsetof(TZ, local_rtc) },
515 { "NTP", property_append_ntp, "b", offsetof(TZ, use_ntp) },
519 static const BusBoundProperties bps[] = {
520 { "org.freedesktop.timedate1", bus_timedate_properties, &tz },
524 static DBusHandlerResult timedate_message_handler(
525 DBusConnection *connection,
526 DBusMessage *message,
529 DBusMessage *reply = NULL, *changed = NULL;
536 dbus_error_init(&error);
538 if (dbus_message_is_method_call(message, "org.freedesktop.timedate1", "SetTimezone")) {
540 dbus_bool_t interactive;
542 if (!dbus_message_get_args(
545 DBUS_TYPE_STRING, &z,
546 DBUS_TYPE_BOOLEAN, &interactive,
548 return bus_send_error_reply(connection, message, &error, -EINVAL);
550 if (!valid_timezone(z))
551 return bus_send_error_reply(connection, message, NULL, -EINVAL);
553 if (!streq_ptr(z, tz.zone)) {
556 r = verify_polkit(connection, message, "org.freedesktop.timedate1.set-timezone", interactive, &error);
558 return bus_send_error_reply(connection, message, &error, r);
567 /* 1. Write new configuration file */
568 r = write_data_timezone();
570 log_error("Failed to set timezone: %s", strerror(-r));
571 return bus_send_error_reply(connection, message, NULL, r);
578 /* 2. Teach kernel new timezone */
579 hwclock_apply_localtime_delta(NULL);
581 /* 3. Sync RTC from system clock, with the new delta */
582 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
583 assert_se(tm = localtime(&ts.tv_sec));
584 hwclock_set_time(tm);
587 log_info("Changed timezone to '%s'.", tz.zone);
589 changed = bus_properties_changed_new(
590 "/org/freedesktop/timedate1",
591 "org.freedesktop.timedate1",
597 } else if (dbus_message_is_method_call(message, "org.freedesktop.timedate1", "SetLocalRTC")) {
599 dbus_bool_t fix_system;
600 dbus_bool_t interactive;
602 if (!dbus_message_get_args(
605 DBUS_TYPE_BOOLEAN, &lrtc,
606 DBUS_TYPE_BOOLEAN, &fix_system,
607 DBUS_TYPE_BOOLEAN, &interactive,
609 return bus_send_error_reply(connection, message, &error, -EINVAL);
611 if (lrtc != tz.local_rtc) {
614 r = verify_polkit(connection, message, "org.freedesktop.timedate1.set-local-rtc", interactive, &error);
616 return bus_send_error_reply(connection, message, &error, r);
620 /* 1. Write new configuration file */
621 r = write_data_local_rtc();
623 log_error("Failed to set RTC to local/UTC: %s", strerror(-r));
624 return bus_send_error_reply(connection, message, NULL, r);
627 /* 2. Teach kernel new timezone */
629 hwclock_apply_localtime_delta(NULL);
631 hwclock_reset_localtime_delta();
633 /* 3. Synchronize clocks */
634 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
639 /* Sync system clock from RTC; first,
640 * initialize the timezone fields of
643 tm = *localtime(&ts.tv_sec);
645 tm = *gmtime(&ts.tv_sec);
647 /* Override the main fields of
648 * struct tm, but not the timezone
650 if (hwclock_get_time(&tm) >= 0) {
652 /* And set the system clock
655 ts.tv_sec = mktime(&tm);
657 ts.tv_sec = timegm(&tm);
659 clock_settime(CLOCK_REALTIME, &ts);
665 /* Sync RTC from system clock */
667 tm = localtime(&ts.tv_sec);
669 tm = gmtime(&ts.tv_sec);
671 hwclock_set_time(tm);
674 log_info("RTC configured to %s time.", tz.local_rtc ? "local" : "UTC");
676 changed = bus_properties_changed_new(
677 "/org/freedesktop/timedate1",
678 "org.freedesktop.timedate1",
684 } else if (dbus_message_is_method_call(message, "org.freedesktop.timedate1", "SetTime")) {
686 dbus_bool_t relative;
687 dbus_bool_t interactive;
689 if (!dbus_message_get_args(
692 DBUS_TYPE_INT64, &utc,
693 DBUS_TYPE_BOOLEAN, &relative,
694 DBUS_TYPE_BOOLEAN, &interactive,
696 return bus_send_error_reply(connection, message, &error, -EINVAL);
698 if (!relative && utc <= 0)
699 return bus_send_error_reply(connection, message, NULL, -EINVAL);
701 if (!relative || utc != 0) {
705 r = verify_polkit(connection, message, "org.freedesktop.timedate1.set-time", interactive, &error);
707 return bus_send_error_reply(connection, message, &error, r);
710 timespec_store(&ts, now(CLOCK_REALTIME) + utc);
712 timespec_store(&ts, utc);
714 /* Set system clock */
715 if (clock_settime(CLOCK_REALTIME, &ts) < 0) {
716 log_error("Failed to set local time: %m");
717 return bus_send_error_reply(connection, message, NULL, -errno);
720 /* Sync down to RTC */
722 tm = localtime(&ts.tv_sec);
724 tm = gmtime(&ts.tv_sec);
726 hwclock_set_time(tm);
728 log_info("Changed local time to %s", ctime(&ts.tv_sec));
730 } else if (dbus_message_is_method_call(message, "org.freedesktop.timedate1", "SetNTP")) {
732 dbus_bool_t interactive;
734 if (!dbus_message_get_args(
737 DBUS_TYPE_BOOLEAN, &ntp,
738 DBUS_TYPE_BOOLEAN, &interactive,
740 return bus_send_error_reply(connection, message, &error, -EINVAL);
742 if (ntp != !!tz.use_ntp) {
744 r = verify_polkit(connection, message, "org.freedesktop.timedate1.set-ntp", interactive, &error);
746 return bus_send_error_reply(connection, message, &error, r);
750 r = enable_ntp(connection, &error);
752 return bus_send_error_reply(connection, message, &error, r);
754 r = start_ntp(connection, &error);
756 return bus_send_error_reply(connection, message, &error, r);
758 log_info("Set NTP to %s", tz.use_ntp ? "enabled" : "disabled");
760 changed = bus_properties_changed_new(
761 "/org/freedesktop/timedate1",
762 "org.freedesktop.timedate1",
769 return bus_default_message_handler(connection, message, INTROSPECTION, INTERFACES_LIST, bps);
771 if (!(reply = dbus_message_new_method_return(message)))
774 if (!dbus_connection_send(connection, reply, NULL))
777 dbus_message_unref(reply);
782 if (!dbus_connection_send(connection, changed, NULL))
785 dbus_message_unref(changed);
788 return DBUS_HANDLER_RESULT_HANDLED;
792 dbus_message_unref(reply);
795 dbus_message_unref(changed);
797 dbus_error_free(&error);
799 return DBUS_HANDLER_RESULT_NEED_MEMORY;
802 static int connect_bus(DBusConnection **_bus) {
803 static const DBusObjectPathVTable timedate_vtable = {
804 .message_function = timedate_message_handler
807 DBusConnection *bus = NULL;
812 dbus_error_init(&error);
814 bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
816 log_error("Failed to get system D-Bus connection: %s", bus_error_message(&error));
821 dbus_connection_set_exit_on_disconnect(bus, FALSE);
823 if (!dbus_connection_register_object_path(bus, "/org/freedesktop/timedate1", &timedate_vtable, NULL) ||
824 !dbus_connection_add_filter(bus, bus_exit_idle_filter, &remain_until, NULL)) {
825 log_error("Not enough memory");
830 r = dbus_bus_request_name(bus, "org.freedesktop.timedate1", DBUS_NAME_FLAG_DO_NOT_QUEUE, &error);
831 if (dbus_error_is_set(&error)) {
832 log_error("Failed to register name on bus: %s", bus_error_message(&error));
837 if (r != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
838 log_error("Failed to acquire name.");
849 dbus_connection_close(bus);
850 dbus_connection_unref(bus);
852 dbus_error_free(&error);
857 int main(int argc, char *argv[]) {
859 DBusConnection *bus = NULL;
860 bool exiting = false;
862 log_set_target(LOG_TARGET_AUTO);
863 log_parse_environment();
868 if (argc == 2 && streq(argv[1], "--introspect")) {
869 fputs(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE
871 fputs(timedate_interface, stdout);
872 fputs("</node>\n", stdout);
877 log_error("This program takes no arguments.");
884 log_error("Failed to read timezone data: %s", strerror(-r));
888 r = connect_bus(&bus);
894 log_error("Failed to determine whether NTP is enabled: %s", strerror(-r));
898 remain_until = now(CLOCK_MONOTONIC) + DEFAULT_EXIT_USEC;
901 if (!dbus_connection_read_write_dispatch(bus, exiting ? -1 : (int) (DEFAULT_EXIT_USEC/USEC_PER_MSEC)))
904 if (!exiting && remain_until < now(CLOCK_MONOTONIC)) {
906 bus_async_unregister_and_exit(bus, "org.freedesktop.hostname1");
916 dbus_connection_flush(bus);
917 dbus_connection_close(bus);
918 dbus_connection_unref(bus);
921 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;