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
) {
86 _cleanup_free_
char *name
= NULL
;
89 if (!unit_name_is_valid(s
, UNIT_NAME_PLAIN
))
92 /* Do not add this if it is already listed */
93 LIST_FOREACH(units
, u
, c
->units
)
94 if (streq(u
->name
, s
))
97 u
= new0(UnitStatusInfo
, 1);
107 LIST_APPEND(units
, c
->units
, u
);
112 static int context_parse_ntp_services(Context
*c
) {
118 env
= getenv("SYSTEMD_TIMEDATED_NTP_SERVICES");
120 r
= context_add_ntp_service(c
, "systemd-timesyncd.service");
122 log_warning_errno(r
, "Failed to add NTP service \"systemd-timesyncd.service\", ignoring: %m");
128 _cleanup_free_
char *word
= NULL
;
130 r
= extract_first_word(&p
, &word
, ":", 0);
136 log_error("Invalid syntax, ignoring: %s", env
);
140 r
= context_add_ntp_service(c
, word
);
142 log_warning_errno(r
, "Failed to add NTP service \"%s\", ignoring: %m", word
);
148 static int context_ntp_service_is_active(Context
*c
) {
149 UnitStatusInfo
*info
;
154 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
156 LIST_FOREACH(units
, info
, c
->units
)
157 count
+= streq_ptr(info
->active_state
, "active");
162 static int context_ntp_service_is_enabled(Context
*c
) {
163 UnitStatusInfo
*info
;
168 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
170 LIST_FOREACH(units
, info
, c
->units
)
171 count
+= STRPTR_IN_SET(info
->unit_file_state
, "enabled", "enabled-runtime");
176 static int context_ntp_service_exists(Context
*c
) {
177 UnitStatusInfo
*info
;
182 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
184 LIST_FOREACH(units
, info
, c
->units
)
185 count
+= streq_ptr(info
->load_state
, "loaded");
190 static int context_read_data(Context
*c
) {
191 _cleanup_free_
char *t
= NULL
;
196 r
= get_timezone(&t
);
198 log_warning_errno(r
, "/etc/localtime should be a symbolic link to a time zone data file in /usr/share/zoneinfo/.");
200 log_warning_errno(r
, "Failed to get target of /etc/localtime: %m");
202 free_and_replace(c
->zone
, t
);
204 c
->local_rtc
= clock_is_localtime(NULL
) > 0;
209 static int context_write_data_timezone(Context
*c
) {
210 _cleanup_free_
char *p
= NULL
;
215 if (isempty(c
->zone
)) {
216 if (unlink("/etc/localtime") < 0 && errno
!= ENOENT
)
222 p
= strappend("../usr/share/zoneinfo/", c
->zone
);
226 r
= symlink_atomic(p
, "/etc/localtime");
233 static int context_write_data_local_rtc(Context
*c
) {
235 _cleanup_free_
char *s
= NULL
, *w
= NULL
;
239 r
= read_full_file("/etc/adjtime", &s
, NULL
);
247 w
= strdup(NULL_ADJTIME_LOCAL
);
252 const char *e
= "\n"; /* default if there is less than 3 lines */
253 const char *prepend
= "";
256 p
= strchrnul(s
, '\n');
258 /* only one line, no \n terminator */
260 else if (p
[1] == '\0') {
261 /* only one line, with \n terminator */
265 p
= strchr(p
+1, '\n');
267 /* only two lines, no \n terminator */
272 /* third line might have a \n terminator or not */
274 end
= strchr(p
, '\n');
275 /* if we actually have a fourth line, use that as suffix "e", otherwise the default \n */
284 w
= new(char, a
+ (c
->local_rtc
? 5 : 3) + strlen(prepend
) + b
+ 1);
288 *(char*) mempcpy(stpcpy(stpcpy(mempcpy(w
, s
, a
), prepend
), c
->local_rtc
? "LOCAL" : "UTC"), e
, b
) = 0;
290 if (streq(w
, NULL_ADJTIME_UTC
)) {
291 if (unlink("/etc/adjtime") < 0)
300 return write_string_file_atomic_label("/etc/adjtime", w
);
303 static int context_update_ntp_status(Context
*c
, sd_bus
*bus
, sd_bus_message
*m
) {
304 static const struct bus_properties_map map
[] = {
305 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
306 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
307 { "UnitFileState", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_state
) },
310 static sd_bus_message
*_m
= NULL
;
317 /* Suppress multiple call of context_update_ntp_status() within single DBus transaction. */
323 LIST_FOREACH(units
, u
, c
->units
) {
324 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
325 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
326 _cleanup_free_
char *path
= NULL
;
328 unit_status_info_clear(u
);
330 path
= unit_dbus_path_from_name(u
->name
);
334 r
= bus_map_all_properties(
336 "org.freedesktop.systemd1",
344 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
350 static int unit_start_or_stop(UnitStatusInfo
*u
, sd_bus
*bus
, sd_bus_error
*error
, bool start
) {
357 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
359 if (streq(u
->active_state
, "active") == start
)
362 r
= sd_bus_call_method(
364 "org.freedesktop.systemd1",
365 "/org/freedesktop/systemd1",
366 "org.freedesktop.systemd1.Manager",
367 start
? "StartUnit" : "StopUnit",
379 static int unit_enable_or_disable(UnitStatusInfo
*u
, sd_bus
*bus
, sd_bus_error
*error
, bool enable
) {
386 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
388 if (streq(u
->unit_file_state
, "enabled") == enable
)
392 r
= sd_bus_call_method(
394 "org.freedesktop.systemd1",
395 "/org/freedesktop/systemd1",
396 "org.freedesktop.systemd1.Manager",
404 r
= sd_bus_call_method(
406 "org.freedesktop.systemd1",
407 "/org/freedesktop/systemd1",
408 "org.freedesktop.systemd1.Manager",
418 r
= sd_bus_call_method(
420 "org.freedesktop.systemd1",
421 "/org/freedesktop/systemd1",
422 "org.freedesktop.systemd1.Manager",
432 static int property_get_rtc_time(
435 const char *interface
,
436 const char *property
,
437 sd_bus_message
*reply
,
439 sd_bus_error
*error
) {
446 r
= clock_get_hwclock(&tm
);
448 log_warning("/dev/rtc is busy. Is somebody keeping it open continuously? That's not a good idea... Returning a bogus RTC timestamp.");
450 } else if (r
== -ENOENT
) {
451 log_debug("/dev/rtc not found.");
452 t
= 0; /* no RTC found */
454 return sd_bus_error_set_errnof(error
, r
, "Failed to read RTC: %m");
456 t
= (usec_t
) timegm(&tm
) * USEC_PER_SEC
;
458 return sd_bus_message_append(reply
, "t", t
);
461 static int property_get_time(
464 const char *interface
,
465 const char *property
,
466 sd_bus_message
*reply
,
468 sd_bus_error
*error
) {
470 return sd_bus_message_append(reply
, "t", now(CLOCK_REALTIME
));
473 static int property_get_ntp_sync(
476 const char *interface
,
477 const char *property
,
478 sd_bus_message
*reply
,
480 sd_bus_error
*error
) {
482 return sd_bus_message_append(reply
, "b", ntp_synced());
485 static int property_get_can_ntp(
488 const char *interface
,
489 const char *property
,
490 sd_bus_message
*reply
,
492 sd_bus_error
*error
) {
494 Context
*c
= userdata
;
503 r
= context_update_ntp_status(c
, bus
, reply
);
507 return sd_bus_message_append(reply
, "b", context_ntp_service_exists(c
) > 0);
510 static int property_get_ntp(
513 const char *interface
,
514 const char *property
,
515 sd_bus_message
*reply
,
517 sd_bus_error
*error
) {
519 Context
*c
= userdata
;
528 r
= context_update_ntp_status(c
, bus
, reply
);
532 return sd_bus_message_append(reply
, "b", context_ntp_service_is_active(c
) > 0);
535 static int method_set_timezone(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
536 Context
*c
= userdata
;
545 r
= sd_bus_message_read(m
, "sb", &z
, &interactive
);
549 if (!timezone_is_valid(z
))
550 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Invalid time zone '%s'", z
);
552 if (streq_ptr(z
, c
->zone
))
553 return sd_bus_reply_method_return(m
, NULL
);
555 r
= bus_verify_polkit_async(
558 "org.freedesktop.timedate1.set-timezone",
567 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
576 /* 1. Write new configuration file */
577 r
= context_write_data_timezone(c
);
579 log_error_errno(r
, "Failed to set time zone: %m");
580 return sd_bus_error_set_errnof(error
, r
, "Failed to set time zone: %m");
583 /* 2. Tell the kernel our timezone */
584 clock_set_timezone(NULL
);
590 /* 3. Sync RTC from system clock, with the new delta */
591 assert_se(clock_gettime(CLOCK_REALTIME
, &ts
) == 0);
592 assert_se(tm
= localtime(&ts
.tv_sec
));
593 clock_set_hwclock(tm
);
597 "MESSAGE_ID=" SD_MESSAGE_TIMEZONE_CHANGE_STR
,
598 "TIMEZONE=%s", c
->zone
,
599 LOG_MESSAGE("Changed time zone to '%s'.", c
->zone
),
602 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m
), "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "Timezone", NULL
);
604 return sd_bus_reply_method_return(m
, NULL
);
607 static int method_set_local_rtc(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
608 int lrtc
, fix_system
, interactive
;
609 Context
*c
= userdata
;
616 r
= sd_bus_message_read(m
, "bbb", &lrtc
, &fix_system
, &interactive
);
620 if (lrtc
== c
->local_rtc
)
621 return sd_bus_reply_method_return(m
, NULL
);
623 r
= bus_verify_polkit_async(
626 "org.freedesktop.timedate1.set-local-rtc",
639 /* 1. Write new configuration file */
640 r
= context_write_data_local_rtc(c
);
642 log_error_errno(r
, "Failed to set RTC to local/UTC: %m");
643 return sd_bus_error_set_errnof(error
, r
, "Failed to set RTC to local/UTC: %m");
646 /* 2. Tell the kernel our timezone */
647 clock_set_timezone(NULL
);
649 /* 3. Synchronize clocks */
650 assert_se(clock_gettime(CLOCK_REALTIME
, &ts
) == 0);
655 /* Sync system clock from RTC; first,
656 * initialize the timezone fields of
659 tm
= *localtime(&ts
.tv_sec
);
661 tm
= *gmtime(&ts
.tv_sec
);
663 /* Override the main fields of
664 * struct tm, but not the timezone
666 if (clock_get_hwclock(&tm
) >= 0) {
668 /* And set the system clock
671 ts
.tv_sec
= mktime(&tm
);
673 ts
.tv_sec
= timegm(&tm
);
675 clock_settime(CLOCK_REALTIME
, &ts
);
681 /* Sync RTC from system clock */
683 tm
= localtime(&ts
.tv_sec
);
685 tm
= gmtime(&ts
.tv_sec
);
687 clock_set_hwclock(tm
);
690 log_info("RTC configured to %s time.", c
->local_rtc
? "local" : "UTC");
692 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m
), "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "LocalRTC", NULL
);
694 return sd_bus_reply_method_return(m
, NULL
);
697 static int method_set_time(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
698 sd_bus
*bus
= sd_bus_message_get_bus(m
);
699 int relative
, interactive
, r
;
700 Context
*c
= userdata
;
709 r
= context_update_ntp_status(c
, bus
, m
);
711 return sd_bus_error_set_errnof(error
, r
, "Failed to update context: %m");
713 if (context_ntp_service_is_active(c
) > 0)
714 return sd_bus_error_set(error
, BUS_ERROR_AUTOMATIC_TIME_SYNC_ENABLED
, "Automatic time synchronization is enabled");
716 /* this only gets used if dbus does not provide a timestamp */
717 start
= now(CLOCK_MONOTONIC
);
719 r
= sd_bus_message_read(m
, "xbb", &utc
, &relative
, &interactive
);
723 if (!relative
&& utc
<= 0)
724 return sd_bus_error_set(error
, SD_BUS_ERROR_INVALID_ARGS
, "Invalid absolute time");
726 if (relative
&& utc
== 0)
727 return sd_bus_reply_method_return(m
, NULL
);
732 n
= now(CLOCK_REALTIME
);
735 if ((utc
> 0 && x
< n
) ||
737 return sd_bus_error_set(error
, SD_BUS_ERROR_INVALID_ARGS
, "Time value overflow");
739 timespec_store(&ts
, x
);
741 timespec_store(&ts
, (usec_t
) utc
);
743 r
= bus_verify_polkit_async(
746 "org.freedesktop.timedate1.set-time",
757 /* adjust ts for time spent in program */
758 r
= sd_bus_message_get_monotonic_usec(m
, &start
);
759 /* when sd_bus_message_get_monotonic_usec() returns -ENODATA it does not modify &start */
760 if (r
< 0 && r
!= -ENODATA
)
763 timespec_store(&ts
, timespec_load(&ts
) + (now(CLOCK_MONOTONIC
) - start
));
765 /* Set system clock */
766 if (clock_settime(CLOCK_REALTIME
, &ts
) < 0) {
767 log_error_errno(errno
, "Failed to set local time: %m");
768 return sd_bus_error_set_errnof(error
, errno
, "Failed to set local time: %m");
771 /* Sync down to RTC */
773 tm
= localtime(&ts
.tv_sec
);
775 tm
= gmtime(&ts
.tv_sec
);
776 clock_set_hwclock(tm
);
779 "MESSAGE_ID=" SD_MESSAGE_TIME_CHANGE_STR
,
780 "REALTIME="USEC_FMT
, timespec_load(&ts
),
781 LOG_MESSAGE("Changed local time to %s", ctime(&ts
.tv_sec
)),
784 return sd_bus_reply_method_return(m
, NULL
);
787 static int method_set_ntp(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
788 sd_bus
*bus
= sd_bus_message_get_bus(m
);
789 Context
*c
= userdata
;
791 int enable
, interactive
, q
, r
;
797 r
= sd_bus_message_read(m
, "bb", &enable
, &interactive
);
801 r
= context_update_ntp_status(c
, bus
, m
);
805 if (context_ntp_service_exists(c
) <= 0)
806 return sd_bus_error_set(error
, BUS_ERROR_NO_NTP_SUPPORT
, "NTP not supported");
808 r
= bus_verify_polkit_async(
811 "org.freedesktop.timedate1.set-ntp",
823 LIST_FOREACH(units
, u
, c
->units
) {
824 if (!streq(u
->load_state
, "loaded"))
827 q
= unit_enable_or_disable(u
, bus
, error
, enable
);
831 q
= unit_start_or_stop(u
, bus
, error
, enable
);
836 else if (context_ntp_service_is_enabled(c
) <= 0)
837 LIST_FOREACH(units
, u
, c
->units
) {
838 if (!streq(u
->load_state
, "loaded"))
841 r
= unit_enable_or_disable(u
, bus
, error
, enable
);
845 r
= unit_start_or_stop(u
, bus
, error
, enable
);
849 else if (context_ntp_service_is_active(c
) <= 0)
850 LIST_FOREACH(units
, u
, c
->units
) {
851 if (!streq(u
->load_state
, "loaded") ||
852 !streq(u
->unit_file_state
, "enabled"))
855 r
= unit_start_or_stop(u
, bus
, error
, enable
);
862 log_info("Set NTP to %sd", enable_disable(enable
));
864 (void) sd_bus_emit_properties_changed(bus
, "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "NTP", NULL
);
866 return sd_bus_reply_method_return(m
, NULL
);
869 static const sd_bus_vtable timedate_vtable
[] = {
870 SD_BUS_VTABLE_START(0),
871 SD_BUS_PROPERTY("Timezone", "s", NULL
, offsetof(Context
, zone
), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE
),
872 SD_BUS_PROPERTY("LocalRTC", "b", bus_property_get_bool
, offsetof(Context
, local_rtc
), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE
),
873 SD_BUS_PROPERTY("CanNTP", "b", property_get_can_ntp
, 0, 0),
874 SD_BUS_PROPERTY("NTP", "b", property_get_ntp
, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE
),
875 SD_BUS_PROPERTY("NTPSynchronized", "b", property_get_ntp_sync
, 0, 0),
876 SD_BUS_PROPERTY("TimeUSec", "t", property_get_time
, 0, 0),
877 SD_BUS_PROPERTY("RTCTimeUSec", "t", property_get_rtc_time
, 0, 0),
878 SD_BUS_METHOD("SetTime", "xbb", NULL
, method_set_time
, SD_BUS_VTABLE_UNPRIVILEGED
),
879 SD_BUS_METHOD("SetTimezone", "sb", NULL
, method_set_timezone
, SD_BUS_VTABLE_UNPRIVILEGED
),
880 SD_BUS_METHOD("SetLocalRTC", "bbb", NULL
, method_set_local_rtc
, SD_BUS_VTABLE_UNPRIVILEGED
),
881 SD_BUS_METHOD("SetNTP", "bb", NULL
, method_set_ntp
, SD_BUS_VTABLE_UNPRIVILEGED
),
885 static int connect_bus(Context
*c
, sd_event
*event
, sd_bus
**_bus
) {
886 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
893 r
= sd_bus_default_system(&bus
);
895 return log_error_errno(r
, "Failed to get system bus connection: %m");
897 r
= sd_bus_add_object_vtable(bus
, NULL
, "/org/freedesktop/timedate1", "org.freedesktop.timedate1", timedate_vtable
, c
);
899 return log_error_errno(r
, "Failed to register object: %m");
901 r
= sd_bus_request_name_async(bus
, NULL
, "org.freedesktop.timedate1", 0, NULL
, NULL
);
903 return log_error_errno(r
, "Failed to request name: %m");
905 r
= sd_bus_attach_event(bus
, event
, 0);
907 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
909 *_bus
= TAKE_PTR(bus
);
914 int main(int argc
, char *argv
[]) {
915 Context context
= {};
916 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
917 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
920 log_set_target(LOG_TARGET_AUTO
);
921 log_parse_environment();
927 log_error("This program takes no arguments.");
932 r
= sd_event_default(&event
);
934 log_error_errno(r
, "Failed to allocate event loop: %m");
938 sd_event_set_watchdog(event
, true);
940 r
= connect_bus(&context
, event
, &bus
);
944 (void) sd_bus_negotiate_timestamp(bus
, true);
946 r
= context_read_data(&context
);
948 log_error_errno(r
, "Failed to read time zone data: %m");
952 r
= context_parse_ntp_services(&context
);
956 r
= bus_event_loop_with_idle(event
, bus
, "org.freedesktop.timedate1", DEFAULT_EXIT_USEC
, NULL
, NULL
);
958 log_error_errno(r
, "Failed to run event loop: %m");
963 context_free(&context
);
965 return r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;