1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2011 Lennart Poettering
14 #include "sd-messages.h"
16 #include "alloc-util.h"
17 #include "bus-common-errors.h"
18 #include "bus-error.h"
20 #include "clock-util.h"
22 #include "fileio-label.h"
26 #include "path-util.h"
27 #include "selinux-util.h"
28 #include "string-util.h"
31 #include "unit-name.h"
32 #include "user-util.h"
35 #define NULL_ADJTIME_UTC "0.0 0 0\n0\nUTC\n"
36 #define NULL_ADJTIME_LOCAL "0.0 0 0\n0\nLOCAL\n"
38 typedef struct UnitStatusInfo
{
41 char *unit_file_state
;
44 LIST_FIELDS(struct UnitStatusInfo
, units
);
47 typedef struct Context
{
50 Hashmap
*polkit_registry
;
52 LIST_HEAD(UnitStatusInfo
, units
);
55 static void unit_status_info_clear(UnitStatusInfo
*p
) {
58 p
->load_state
= mfree(p
->load_state
);
59 p
->unit_file_state
= mfree(p
->unit_file_state
);
60 p
->active_state
= mfree(p
->active_state
);
63 static void unit_status_info_free(UnitStatusInfo
*p
) {
66 unit_status_info_clear(p
);
71 static void context_free(Context
*c
) {
77 bus_verify_polkit_async_registry_free(c
->polkit_registry
);
79 while ((p
= c
->units
)) {
80 LIST_REMOVE(units
, c
->units
, p
);
81 unit_status_info_free(p
);
85 static int context_add_ntp_service(Context
*c
, const char *s
) {
88 if (!unit_name_is_valid(s
, UNIT_NAME_PLAIN
))
91 /* Do not add this if it is already listed */
92 LIST_FOREACH(units
, u
, c
->units
)
93 if (streq(u
->name
, s
))
96 u
= new0(UnitStatusInfo
, 1);
106 LIST_APPEND(units
, c
->units
, u
);
111 static int context_parse_ntp_services(Context
*c
) {
117 env
= getenv("SYSTEMD_TIMEDATED_NTP_SERVICES");
119 r
= context_add_ntp_service(c
, "systemd-timesyncd.service");
121 log_warning_errno(r
, "Failed to add NTP service \"systemd-timesyncd.service\", ignoring: %m");
127 _cleanup_free_
char *word
= NULL
;
129 r
= extract_first_word(&p
, &word
, ":", 0);
135 log_error("Invalid syntax, ignoring: %s", env
);
139 r
= context_add_ntp_service(c
, word
);
141 log_warning_errno(r
, "Failed to add NTP service \"%s\", ignoring: %m", word
);
147 static int context_ntp_service_is_active(Context
*c
) {
148 UnitStatusInfo
*info
;
153 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
155 LIST_FOREACH(units
, info
, c
->units
)
156 count
+= streq_ptr(info
->active_state
, "active");
161 static int context_ntp_service_is_enabled(Context
*c
) {
162 UnitStatusInfo
*info
;
167 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
169 LIST_FOREACH(units
, info
, c
->units
)
170 count
+= STRPTR_IN_SET(info
->unit_file_state
, "enabled", "enabled-runtime");
175 static int context_ntp_service_exists(Context
*c
) {
176 UnitStatusInfo
*info
;
181 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
183 LIST_FOREACH(units
, info
, c
->units
)
184 count
+= streq_ptr(info
->load_state
, "loaded");
189 static int context_read_data(Context
*c
) {
190 _cleanup_free_
char *t
= NULL
;
195 r
= get_timezone(&t
);
197 log_warning_errno(r
, "/etc/localtime should be a symbolic link to a time zone data file in /usr/share/zoneinfo/.");
199 log_warning_errno(r
, "Failed to get target of /etc/localtime: %m");
201 free_and_replace(c
->zone
, t
);
203 c
->local_rtc
= clock_is_localtime(NULL
) > 0;
208 static int context_write_data_timezone(Context
*c
) {
209 _cleanup_free_
char *p
= NULL
;
214 if (isempty(c
->zone
)) {
215 if (unlink("/etc/localtime") < 0 && errno
!= ENOENT
)
221 p
= strappend("../usr/share/zoneinfo/", c
->zone
);
225 r
= symlink_atomic(p
, "/etc/localtime");
232 static int context_write_data_local_rtc(Context
*c
) {
234 _cleanup_free_
char *s
= NULL
, *w
= NULL
;
238 r
= read_full_file("/etc/adjtime", &s
, NULL
);
246 w
= strdup(NULL_ADJTIME_LOCAL
);
251 const char *e
= "\n"; /* default if there is less than 3 lines */
252 const char *prepend
= "";
255 p
= strchrnul(s
, '\n');
257 /* only one line, no \n terminator */
259 else if (p
[1] == '\0') {
260 /* only one line, with \n terminator */
264 p
= strchr(p
+1, '\n');
266 /* only two lines, no \n terminator */
271 /* third line might have a \n terminator or not */
273 end
= strchr(p
, '\n');
274 /* if we actually have a fourth line, use that as suffix "e", otherwise the default \n */
283 w
= new(char, a
+ (c
->local_rtc
? 5 : 3) + strlen(prepend
) + b
+ 1);
287 *(char*) mempcpy(stpcpy(stpcpy(mempcpy(w
, s
, a
), prepend
), c
->local_rtc
? "LOCAL" : "UTC"), e
, b
) = 0;
289 if (streq(w
, NULL_ADJTIME_UTC
)) {
290 if (unlink("/etc/adjtime") < 0)
299 return write_string_file_atomic_label("/etc/adjtime", w
);
302 static int context_update_ntp_status(Context
*c
, sd_bus
*bus
, sd_bus_message
*m
) {
303 static const struct bus_properties_map map
[] = {
304 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
305 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
306 { "UnitFileState", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_state
) },
309 static sd_bus_message
*_m
= NULL
;
316 /* Suppress multiple call of context_update_ntp_status() within single DBus transaction. */
322 LIST_FOREACH(units
, u
, c
->units
) {
323 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
324 _cleanup_free_
char *path
= NULL
;
326 unit_status_info_clear(u
);
328 path
= unit_dbus_path_from_name(u
->name
);
332 r
= bus_map_all_properties(
334 "org.freedesktop.systemd1",
342 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
348 static int unit_start_or_stop(UnitStatusInfo
*u
, sd_bus
*bus
, sd_bus_error
*error
, bool start
) {
355 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
357 if (streq(u
->active_state
, "active") == start
)
360 r
= sd_bus_call_method(
362 "org.freedesktop.systemd1",
363 "/org/freedesktop/systemd1",
364 "org.freedesktop.systemd1.Manager",
365 start
? "StartUnit" : "StopUnit",
377 static int unit_enable_or_disable(UnitStatusInfo
*u
, sd_bus
*bus
, sd_bus_error
*error
, bool enable
) {
384 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
386 if (streq(u
->unit_file_state
, "enabled") == enable
)
390 r
= sd_bus_call_method(
392 "org.freedesktop.systemd1",
393 "/org/freedesktop/systemd1",
394 "org.freedesktop.systemd1.Manager",
402 r
= sd_bus_call_method(
404 "org.freedesktop.systemd1",
405 "/org/freedesktop/systemd1",
406 "org.freedesktop.systemd1.Manager",
416 r
= sd_bus_call_method(
418 "org.freedesktop.systemd1",
419 "/org/freedesktop/systemd1",
420 "org.freedesktop.systemd1.Manager",
430 static BUS_DEFINE_PROPERTY_GET_GLOBAL(property_get_time
, "t", now(CLOCK_REALTIME
));
431 static BUS_DEFINE_PROPERTY_GET_GLOBAL(property_get_ntp_sync
, "b", ntp_synced());
433 static int property_get_rtc_time(
436 const char *interface
,
437 const char *property
,
438 sd_bus_message
*reply
,
440 sd_bus_error
*error
) {
447 r
= clock_get_hwclock(&tm
);
449 log_warning("/dev/rtc is busy. Is somebody keeping it open continuously? That's not a good idea... Returning a bogus RTC timestamp.");
451 } else if (r
== -ENOENT
) {
452 log_debug("/dev/rtc not found.");
453 t
= 0; /* no RTC found */
455 return sd_bus_error_set_errnof(error
, r
, "Failed to read RTC: %m");
457 t
= (usec_t
) timegm(&tm
) * USEC_PER_SEC
;
459 return sd_bus_message_append(reply
, "t", t
);
462 static int property_get_can_ntp(
465 const char *interface
,
466 const char *property
,
467 sd_bus_message
*reply
,
469 sd_bus_error
*error
) {
471 Context
*c
= userdata
;
480 r
= context_update_ntp_status(c
, bus
, reply
);
484 return sd_bus_message_append(reply
, "b", context_ntp_service_exists(c
) > 0);
487 static int property_get_ntp(
490 const char *interface
,
491 const char *property
,
492 sd_bus_message
*reply
,
494 sd_bus_error
*error
) {
496 Context
*c
= userdata
;
505 r
= context_update_ntp_status(c
, bus
, reply
);
509 return sd_bus_message_append(reply
, "b", context_ntp_service_is_active(c
) > 0);
512 static int method_set_timezone(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
513 Context
*c
= userdata
;
520 r
= sd_bus_message_read(m
, "sb", &z
, &interactive
);
524 if (!timezone_is_valid(z
, LOG_DEBUG
))
525 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Invalid time zone '%s'", z
);
527 if (streq_ptr(z
, c
->zone
))
528 return sd_bus_reply_method_return(m
, NULL
);
530 r
= bus_verify_polkit_async(
533 "org.freedesktop.timedate1.set-timezone",
542 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
544 r
= free_and_strdup(&c
->zone
, z
);
548 /* 1. Write new configuration file */
549 r
= context_write_data_timezone(c
);
551 log_error_errno(r
, "Failed to set time zone: %m");
552 return sd_bus_error_set_errnof(error
, r
, "Failed to set time zone: %m");
555 /* 2. Make glibc notice the new timezone */
558 /* 3. Tell the kernel our timezone */
559 r
= clock_set_timezone(NULL
);
561 log_debug_errno(r
, "Failed to tell kernel about timezone, ignoring: %m");
567 /* 4. Sync RTC from system clock, with the new delta */
568 assert_se(clock_gettime(CLOCK_REALTIME
, &ts
) == 0);
569 assert_se(tm
= localtime(&ts
.tv_sec
));
571 r
= clock_set_hwclock(tm
);
573 log_debug_errno(r
, "Failed to sync time to hardware clock, ignoring: %m");
577 "MESSAGE_ID=" SD_MESSAGE_TIMEZONE_CHANGE_STR
,
578 "TIMEZONE=%s", c
->zone
,
579 "TIMEZONE_SHORTNAME=%s", tzname
[daylight
],
580 "DAYLIGHT=%i", daylight
,
581 LOG_MESSAGE("Changed time zone to '%s' (%s).", c
->zone
, tzname
[daylight
]));
583 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m
), "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "Timezone", NULL
);
585 return sd_bus_reply_method_return(m
, NULL
);
588 static int method_set_local_rtc(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
589 int lrtc
, fix_system
, interactive
;
590 Context
*c
= userdata
;
597 r
= sd_bus_message_read(m
, "bbb", &lrtc
, &fix_system
, &interactive
);
601 if (lrtc
== c
->local_rtc
)
602 return sd_bus_reply_method_return(m
, NULL
);
604 r
= bus_verify_polkit_async(
607 "org.freedesktop.timedate1.set-local-rtc",
620 /* 1. Write new configuration file */
621 r
= context_write_data_local_rtc(c
);
623 log_error_errno(r
, "Failed to set RTC to local/UTC: %m");
624 return sd_bus_error_set_errnof(error
, r
, "Failed to set RTC to local/UTC: %m");
627 /* 2. Tell the kernel our timezone */
628 r
= clock_set_timezone(NULL
);
630 log_debug_errno(r
, "Failed to tell kernel about timezone, ignoring: %m");
632 /* 3. Synchronize clocks */
633 assert_se(clock_gettime(CLOCK_REALTIME
, &ts
) == 0);
638 /* Sync system clock from RTC; first, initialize the timezone fields of struct tm. */
640 tm
= *localtime(&ts
.tv_sec
);
642 tm
= *gmtime(&ts
.tv_sec
);
644 /* Override the main fields of struct tm, but not the timezone fields */
645 r
= clock_get_hwclock(&tm
);
647 log_debug_errno(r
, "Failed to get hardware clock, ignoring: %m");
649 /* And set the system clock with this */
651 ts
.tv_sec
= mktime(&tm
);
653 ts
.tv_sec
= timegm(&tm
);
655 if (clock_settime(CLOCK_REALTIME
, &ts
) < 0)
656 log_debug_errno(errno
, "Failed to update system clock, ignoring: %m");
662 /* Sync RTC from system clock */
664 tm
= localtime(&ts
.tv_sec
);
666 tm
= gmtime(&ts
.tv_sec
);
668 r
= clock_set_hwclock(tm
);
670 log_debug_errno(r
, "Failed to sync time to hardware clock, ignoring: %m");
673 log_info("RTC configured to %s time.", c
->local_rtc
? "local" : "UTC");
675 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m
), "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "LocalRTC", NULL
);
677 return sd_bus_reply_method_return(m
, NULL
);
680 static int method_set_time(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
681 sd_bus
*bus
= sd_bus_message_get_bus(m
);
682 int relative
, interactive
, r
;
683 Context
*c
= userdata
;
692 r
= context_update_ntp_status(c
, bus
, m
);
694 return sd_bus_error_set_errnof(error
, r
, "Failed to update context: %m");
696 if (context_ntp_service_is_active(c
) > 0)
697 return sd_bus_error_set(error
, BUS_ERROR_AUTOMATIC_TIME_SYNC_ENABLED
, "Automatic time synchronization is enabled");
699 /* this only gets used if dbus does not provide a timestamp */
700 start
= now(CLOCK_MONOTONIC
);
702 r
= sd_bus_message_read(m
, "xbb", &utc
, &relative
, &interactive
);
706 if (!relative
&& utc
<= 0)
707 return sd_bus_error_set(error
, SD_BUS_ERROR_INVALID_ARGS
, "Invalid absolute time");
709 if (relative
&& utc
== 0)
710 return sd_bus_reply_method_return(m
, NULL
);
715 n
= now(CLOCK_REALTIME
);
718 if ((utc
> 0 && x
< n
) ||
720 return sd_bus_error_set(error
, SD_BUS_ERROR_INVALID_ARGS
, "Time value overflow");
722 timespec_store(&ts
, x
);
724 timespec_store(&ts
, (usec_t
) utc
);
726 r
= bus_verify_polkit_async(
729 "org.freedesktop.timedate1.set-time",
740 /* adjust ts for time spent in program */
741 r
= sd_bus_message_get_monotonic_usec(m
, &start
);
742 /* when sd_bus_message_get_monotonic_usec() returns -ENODATA it does not modify &start */
743 if (r
< 0 && r
!= -ENODATA
)
746 timespec_store(&ts
, timespec_load(&ts
) + (now(CLOCK_MONOTONIC
) - start
));
748 /* Set system clock */
749 if (clock_settime(CLOCK_REALTIME
, &ts
) < 0) {
750 log_error_errno(errno
, "Failed to set local time: %m");
751 return sd_bus_error_set_errnof(error
, errno
, "Failed to set local time: %m");
754 /* Sync down to RTC */
756 tm
= localtime(&ts
.tv_sec
);
758 tm
= gmtime(&ts
.tv_sec
);
760 r
= clock_set_hwclock(tm
);
762 log_debug_errno(r
, "Failed to update hardware clock, ignoring: %m");
765 "MESSAGE_ID=" SD_MESSAGE_TIME_CHANGE_STR
,
766 "REALTIME="USEC_FMT
, timespec_load(&ts
),
767 LOG_MESSAGE("Changed local time to %s", ctime(&ts
.tv_sec
)));
769 return sd_bus_reply_method_return(m
, NULL
);
772 static int method_set_ntp(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
773 sd_bus
*bus
= sd_bus_message_get_bus(m
);
774 Context
*c
= userdata
;
776 int enable
, interactive
, q
, r
;
782 r
= sd_bus_message_read(m
, "bb", &enable
, &interactive
);
786 r
= context_update_ntp_status(c
, bus
, m
);
790 if (context_ntp_service_exists(c
) <= 0)
791 return sd_bus_error_set(error
, BUS_ERROR_NO_NTP_SUPPORT
, "NTP not supported");
793 r
= bus_verify_polkit_async(
796 "org.freedesktop.timedate1.set-ntp",
808 LIST_FOREACH(units
, u
, c
->units
) {
809 if (!streq(u
->load_state
, "loaded"))
812 q
= unit_enable_or_disable(u
, bus
, error
, enable
);
816 q
= unit_start_or_stop(u
, bus
, error
, enable
);
821 else if (context_ntp_service_is_enabled(c
) <= 0)
822 LIST_FOREACH(units
, u
, c
->units
) {
823 if (!streq(u
->load_state
, "loaded"))
826 r
= unit_enable_or_disable(u
, bus
, error
, enable
);
830 r
= unit_start_or_stop(u
, bus
, error
, enable
);
834 else if (context_ntp_service_is_active(c
) <= 0)
835 LIST_FOREACH(units
, u
, c
->units
) {
836 if (!streq(u
->load_state
, "loaded") ||
837 !streq(u
->unit_file_state
, "enabled"))
840 r
= unit_start_or_stop(u
, bus
, error
, enable
);
847 log_info("Set NTP to %sd", enable_disable(enable
));
849 (void) sd_bus_emit_properties_changed(bus
, "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "NTP", NULL
);
851 return sd_bus_reply_method_return(m
, NULL
);
854 static const sd_bus_vtable timedate_vtable
[] = {
855 SD_BUS_VTABLE_START(0),
856 SD_BUS_PROPERTY("Timezone", "s", NULL
, offsetof(Context
, zone
), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE
),
857 SD_BUS_PROPERTY("LocalRTC", "b", bus_property_get_bool
, offsetof(Context
, local_rtc
), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE
),
858 SD_BUS_PROPERTY("CanNTP", "b", property_get_can_ntp
, 0, 0),
859 SD_BUS_PROPERTY("NTP", "b", property_get_ntp
, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE
),
860 SD_BUS_PROPERTY("NTPSynchronized", "b", property_get_ntp_sync
, 0, 0),
861 SD_BUS_PROPERTY("TimeUSec", "t", property_get_time
, 0, 0),
862 SD_BUS_PROPERTY("RTCTimeUSec", "t", property_get_rtc_time
, 0, 0),
863 SD_BUS_METHOD("SetTime", "xbb", NULL
, method_set_time
, SD_BUS_VTABLE_UNPRIVILEGED
),
864 SD_BUS_METHOD("SetTimezone", "sb", NULL
, method_set_timezone
, SD_BUS_VTABLE_UNPRIVILEGED
),
865 SD_BUS_METHOD("SetLocalRTC", "bbb", NULL
, method_set_local_rtc
, SD_BUS_VTABLE_UNPRIVILEGED
),
866 SD_BUS_METHOD("SetNTP", "bb", NULL
, method_set_ntp
, SD_BUS_VTABLE_UNPRIVILEGED
),
870 static int connect_bus(Context
*c
, sd_event
*event
, sd_bus
**_bus
) {
871 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
878 r
= sd_bus_default_system(&bus
);
880 return log_error_errno(r
, "Failed to get system bus connection: %m");
882 r
= sd_bus_add_object_vtable(bus
, NULL
, "/org/freedesktop/timedate1", "org.freedesktop.timedate1", timedate_vtable
, c
);
884 return log_error_errno(r
, "Failed to register object: %m");
886 r
= sd_bus_request_name_async(bus
, NULL
, "org.freedesktop.timedate1", 0, NULL
, NULL
);
888 return log_error_errno(r
, "Failed to request name: %m");
890 r
= sd_bus_attach_event(bus
, event
, 0);
892 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
894 *_bus
= TAKE_PTR(bus
);
899 int main(int argc
, char *argv
[]) {
900 Context context
= {};
901 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
902 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
905 log_set_target(LOG_TARGET_AUTO
);
906 log_parse_environment();
912 log_error("This program takes no arguments.");
917 r
= sd_event_default(&event
);
919 log_error_errno(r
, "Failed to allocate event loop: %m");
923 sd_event_set_watchdog(event
, true);
925 r
= connect_bus(&context
, event
, &bus
);
929 (void) sd_bus_negotiate_timestamp(bus
, true);
931 r
= context_read_data(&context
);
933 log_error_errno(r
, "Failed to read time zone data: %m");
937 r
= context_parse_ntp_services(&context
);
941 r
= bus_event_loop_with_idle(event
, bus
, "org.freedesktop.timedate1", DEFAULT_EXIT_USEC
, NULL
, NULL
);
943 log_error_errno(r
, "Failed to run event loop: %m");
948 context_free(&context
);
950 return r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;