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 int property_get_rtc_time(
433 const char *interface
,
434 const char *property
,
435 sd_bus_message
*reply
,
437 sd_bus_error
*error
) {
444 r
= clock_get_hwclock(&tm
);
446 log_warning("/dev/rtc is busy. Is somebody keeping it open continuously? That's not a good idea... Returning a bogus RTC timestamp.");
448 } else if (r
== -ENOENT
) {
449 log_debug("/dev/rtc not found.");
450 t
= 0; /* no RTC found */
452 return sd_bus_error_set_errnof(error
, r
, "Failed to read RTC: %m");
454 t
= (usec_t
) timegm(&tm
) * USEC_PER_SEC
;
456 return sd_bus_message_append(reply
, "t", t
);
459 static int property_get_time(
462 const char *interface
,
463 const char *property
,
464 sd_bus_message
*reply
,
466 sd_bus_error
*error
) {
468 return sd_bus_message_append(reply
, "t", now(CLOCK_REALTIME
));
471 static int property_get_ntp_sync(
474 const char *interface
,
475 const char *property
,
476 sd_bus_message
*reply
,
478 sd_bus_error
*error
) {
480 return sd_bus_message_append(reply
, "b", ntp_synced());
483 static int property_get_can_ntp(
486 const char *interface
,
487 const char *property
,
488 sd_bus_message
*reply
,
490 sd_bus_error
*error
) {
492 Context
*c
= userdata
;
501 r
= context_update_ntp_status(c
, bus
, reply
);
505 return sd_bus_message_append(reply
, "b", context_ntp_service_exists(c
) > 0);
508 static int property_get_ntp(
511 const char *interface
,
512 const char *property
,
513 sd_bus_message
*reply
,
515 sd_bus_error
*error
) {
517 Context
*c
= userdata
;
526 r
= context_update_ntp_status(c
, bus
, reply
);
530 return sd_bus_message_append(reply
, "b", context_ntp_service_is_active(c
) > 0);
533 static int method_set_timezone(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
534 Context
*c
= userdata
;
543 r
= sd_bus_message_read(m
, "sb", &z
, &interactive
);
547 if (!timezone_is_valid(z
))
548 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Invalid time zone '%s'", z
);
550 if (streq_ptr(z
, c
->zone
))
551 return sd_bus_reply_method_return(m
, NULL
);
553 r
= bus_verify_polkit_async(
556 "org.freedesktop.timedate1.set-timezone",
565 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
574 /* 1. Write new configuration file */
575 r
= context_write_data_timezone(c
);
577 log_error_errno(r
, "Failed to set time zone: %m");
578 return sd_bus_error_set_errnof(error
, r
, "Failed to set time zone: %m");
581 /* 2. Tell the kernel our timezone */
582 clock_set_timezone(NULL
);
588 /* 3. Sync RTC from system clock, with the new delta */
589 assert_se(clock_gettime(CLOCK_REALTIME
, &ts
) == 0);
590 assert_se(tm
= localtime(&ts
.tv_sec
));
591 clock_set_hwclock(tm
);
595 "MESSAGE_ID=" SD_MESSAGE_TIMEZONE_CHANGE_STR
,
596 "TIMEZONE=%s", c
->zone
,
597 LOG_MESSAGE("Changed time zone to '%s'.", c
->zone
),
600 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m
), "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "Timezone", NULL
);
602 return sd_bus_reply_method_return(m
, NULL
);
605 static int method_set_local_rtc(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
606 int lrtc
, fix_system
, interactive
;
607 Context
*c
= userdata
;
614 r
= sd_bus_message_read(m
, "bbb", &lrtc
, &fix_system
, &interactive
);
618 if (lrtc
== c
->local_rtc
)
619 return sd_bus_reply_method_return(m
, NULL
);
621 r
= bus_verify_polkit_async(
624 "org.freedesktop.timedate1.set-local-rtc",
637 /* 1. Write new configuration file */
638 r
= context_write_data_local_rtc(c
);
640 log_error_errno(r
, "Failed to set RTC to local/UTC: %m");
641 return sd_bus_error_set_errnof(error
, r
, "Failed to set RTC to local/UTC: %m");
644 /* 2. Tell the kernel our timezone */
645 clock_set_timezone(NULL
);
647 /* 3. Synchronize clocks */
648 assert_se(clock_gettime(CLOCK_REALTIME
, &ts
) == 0);
653 /* Sync system clock from RTC; first,
654 * initialize the timezone fields of
657 tm
= *localtime(&ts
.tv_sec
);
659 tm
= *gmtime(&ts
.tv_sec
);
661 /* Override the main fields of
662 * struct tm, but not the timezone
664 if (clock_get_hwclock(&tm
) >= 0) {
666 /* And set the system clock
669 ts
.tv_sec
= mktime(&tm
);
671 ts
.tv_sec
= timegm(&tm
);
673 clock_settime(CLOCK_REALTIME
, &ts
);
679 /* Sync RTC from system clock */
681 tm
= localtime(&ts
.tv_sec
);
683 tm
= gmtime(&ts
.tv_sec
);
685 clock_set_hwclock(tm
);
688 log_info("RTC configured to %s time.", c
->local_rtc
? "local" : "UTC");
690 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m
), "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "LocalRTC", NULL
);
692 return sd_bus_reply_method_return(m
, NULL
);
695 static int method_set_time(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
696 sd_bus
*bus
= sd_bus_message_get_bus(m
);
697 int relative
, interactive
, r
;
698 Context
*c
= userdata
;
707 r
= context_update_ntp_status(c
, bus
, m
);
709 return sd_bus_error_set_errnof(error
, r
, "Failed to update context: %m");
711 if (context_ntp_service_is_active(c
) > 0)
712 return sd_bus_error_set(error
, BUS_ERROR_AUTOMATIC_TIME_SYNC_ENABLED
, "Automatic time synchronization is enabled");
714 /* this only gets used if dbus does not provide a timestamp */
715 start
= now(CLOCK_MONOTONIC
);
717 r
= sd_bus_message_read(m
, "xbb", &utc
, &relative
, &interactive
);
721 if (!relative
&& utc
<= 0)
722 return sd_bus_error_set(error
, SD_BUS_ERROR_INVALID_ARGS
, "Invalid absolute time");
724 if (relative
&& utc
== 0)
725 return sd_bus_reply_method_return(m
, NULL
);
730 n
= now(CLOCK_REALTIME
);
733 if ((utc
> 0 && x
< n
) ||
735 return sd_bus_error_set(error
, SD_BUS_ERROR_INVALID_ARGS
, "Time value overflow");
737 timespec_store(&ts
, x
);
739 timespec_store(&ts
, (usec_t
) utc
);
741 r
= bus_verify_polkit_async(
744 "org.freedesktop.timedate1.set-time",
755 /* adjust ts for time spent in program */
756 r
= sd_bus_message_get_monotonic_usec(m
, &start
);
757 /* when sd_bus_message_get_monotonic_usec() returns -ENODATA it does not modify &start */
758 if (r
< 0 && r
!= -ENODATA
)
761 timespec_store(&ts
, timespec_load(&ts
) + (now(CLOCK_MONOTONIC
) - start
));
763 /* Set system clock */
764 if (clock_settime(CLOCK_REALTIME
, &ts
) < 0) {
765 log_error_errno(errno
, "Failed to set local time: %m");
766 return sd_bus_error_set_errnof(error
, errno
, "Failed to set local time: %m");
769 /* Sync down to RTC */
771 tm
= localtime(&ts
.tv_sec
);
773 tm
= gmtime(&ts
.tv_sec
);
774 clock_set_hwclock(tm
);
777 "MESSAGE_ID=" SD_MESSAGE_TIME_CHANGE_STR
,
778 "REALTIME="USEC_FMT
, timespec_load(&ts
),
779 LOG_MESSAGE("Changed local time to %s", ctime(&ts
.tv_sec
)),
782 return sd_bus_reply_method_return(m
, NULL
);
785 static int method_set_ntp(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
786 sd_bus
*bus
= sd_bus_message_get_bus(m
);
787 Context
*c
= userdata
;
789 int enable
, interactive
, q
, r
;
795 r
= sd_bus_message_read(m
, "bb", &enable
, &interactive
);
799 r
= context_update_ntp_status(c
, bus
, m
);
803 if (context_ntp_service_exists(c
) <= 0)
804 return sd_bus_error_set(error
, BUS_ERROR_NO_NTP_SUPPORT
, "NTP not supported");
806 r
= bus_verify_polkit_async(
809 "org.freedesktop.timedate1.set-ntp",
821 LIST_FOREACH(units
, u
, c
->units
) {
822 if (!streq(u
->load_state
, "loaded"))
825 q
= unit_enable_or_disable(u
, bus
, error
, enable
);
829 q
= unit_start_or_stop(u
, bus
, error
, enable
);
834 else if (context_ntp_service_is_enabled(c
) <= 0)
835 LIST_FOREACH(units
, u
, c
->units
) {
836 if (!streq(u
->load_state
, "loaded"))
839 r
= unit_enable_or_disable(u
, bus
, error
, enable
);
843 r
= unit_start_or_stop(u
, bus
, error
, enable
);
847 else if (context_ntp_service_is_active(c
) <= 0)
848 LIST_FOREACH(units
, u
, c
->units
) {
849 if (!streq(u
->load_state
, "loaded") ||
850 !streq(u
->unit_file_state
, "enabled"))
853 r
= unit_start_or_stop(u
, bus
, error
, enable
);
860 log_info("Set NTP to %sd", enable_disable(enable
));
862 (void) sd_bus_emit_properties_changed(bus
, "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "NTP", NULL
);
864 return sd_bus_reply_method_return(m
, NULL
);
867 static const sd_bus_vtable timedate_vtable
[] = {
868 SD_BUS_VTABLE_START(0),
869 SD_BUS_PROPERTY("Timezone", "s", NULL
, offsetof(Context
, zone
), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE
),
870 SD_BUS_PROPERTY("LocalRTC", "b", bus_property_get_bool
, offsetof(Context
, local_rtc
), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE
),
871 SD_BUS_PROPERTY("CanNTP", "b", property_get_can_ntp
, 0, 0),
872 SD_BUS_PROPERTY("NTP", "b", property_get_ntp
, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE
),
873 SD_BUS_PROPERTY("NTPSynchronized", "b", property_get_ntp_sync
, 0, 0),
874 SD_BUS_PROPERTY("TimeUSec", "t", property_get_time
, 0, 0),
875 SD_BUS_PROPERTY("RTCTimeUSec", "t", property_get_rtc_time
, 0, 0),
876 SD_BUS_METHOD("SetTime", "xbb", NULL
, method_set_time
, SD_BUS_VTABLE_UNPRIVILEGED
),
877 SD_BUS_METHOD("SetTimezone", "sb", NULL
, method_set_timezone
, SD_BUS_VTABLE_UNPRIVILEGED
),
878 SD_BUS_METHOD("SetLocalRTC", "bbb", NULL
, method_set_local_rtc
, SD_BUS_VTABLE_UNPRIVILEGED
),
879 SD_BUS_METHOD("SetNTP", "bb", NULL
, method_set_ntp
, SD_BUS_VTABLE_UNPRIVILEGED
),
883 static int connect_bus(Context
*c
, sd_event
*event
, sd_bus
**_bus
) {
884 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
891 r
= sd_bus_default_system(&bus
);
893 return log_error_errno(r
, "Failed to get system bus connection: %m");
895 r
= sd_bus_add_object_vtable(bus
, NULL
, "/org/freedesktop/timedate1", "org.freedesktop.timedate1", timedate_vtable
, c
);
897 return log_error_errno(r
, "Failed to register object: %m");
899 r
= sd_bus_request_name_async(bus
, NULL
, "org.freedesktop.timedate1", 0, NULL
, NULL
);
901 return log_error_errno(r
, "Failed to request name: %m");
903 r
= sd_bus_attach_event(bus
, event
, 0);
905 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
907 *_bus
= TAKE_PTR(bus
);
912 int main(int argc
, char *argv
[]) {
913 Context context
= {};
914 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
915 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
918 log_set_target(LOG_TARGET_AUTO
);
919 log_parse_environment();
925 log_error("This program takes no arguments.");
930 r
= sd_event_default(&event
);
932 log_error_errno(r
, "Failed to allocate event loop: %m");
936 sd_event_set_watchdog(event
, true);
938 r
= connect_bus(&context
, event
, &bus
);
942 (void) sd_bus_negotiate_timestamp(bus
, true);
944 r
= context_read_data(&context
);
946 log_error_errno(r
, "Failed to read time zone data: %m");
950 r
= context_parse_ntp_services(&context
);
954 r
= bus_event_loop_with_idle(event
, bus
, "org.freedesktop.timedate1", DEFAULT_EXIT_USEC
, NULL
, NULL
);
956 log_error_errno(r
, "Failed to run event loop: %m");
961 context_free(&context
);
963 return r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;