1 /* SPDX-License-Identifier: LGPL-2.1+ */
9 #include "sd-messages.h"
11 #include "alloc-util.h"
12 #include "bus-common-errors.h"
13 #include "bus-error.h"
15 #include "clock-util.h"
17 #include "fileio-label.h"
21 #include "path-util.h"
22 #include "selinux-util.h"
23 #include "signal-util.h"
24 #include "string-util.h"
27 #include "unit-name.h"
28 #include "user-util.h"
31 #define NULL_ADJTIME_UTC "0.0 0 0\n0\nUTC\n"
32 #define NULL_ADJTIME_LOCAL "0.0 0 0\n0\nLOCAL\n"
34 typedef struct UnitStatusInfo
{
37 char *unit_file_state
;
40 LIST_FIELDS(struct UnitStatusInfo
, units
);
43 typedef struct Context
{
46 Hashmap
*polkit_registry
;
48 LIST_HEAD(UnitStatusInfo
, units
);
51 static void unit_status_info_clear(UnitStatusInfo
*p
) {
54 p
->load_state
= mfree(p
->load_state
);
55 p
->unit_file_state
= mfree(p
->unit_file_state
);
56 p
->active_state
= mfree(p
->active_state
);
59 static void unit_status_info_free(UnitStatusInfo
*p
) {
62 unit_status_info_clear(p
);
67 static void context_free(Context
*c
) {
73 bus_verify_polkit_async_registry_free(c
->polkit_registry
);
75 while ((p
= c
->units
)) {
76 LIST_REMOVE(units
, c
->units
, p
);
77 unit_status_info_free(p
);
81 static int context_add_ntp_service(Context
*c
, const char *s
) {
84 if (!unit_name_is_valid(s
, UNIT_NAME_PLAIN
))
87 /* Do not add this if it is already listed */
88 LIST_FOREACH(units
, u
, c
->units
)
89 if (streq(u
->name
, s
))
92 u
= new0(UnitStatusInfo
, 1);
102 LIST_APPEND(units
, c
->units
, u
);
107 static int context_parse_ntp_services(Context
*c
) {
113 env
= getenv("SYSTEMD_TIMEDATED_NTP_SERVICES");
115 r
= context_add_ntp_service(c
, "systemd-timesyncd.service");
117 log_warning_errno(r
, "Failed to add NTP service \"systemd-timesyncd.service\", ignoring: %m");
123 _cleanup_free_
char *word
= NULL
;
125 r
= extract_first_word(&p
, &word
, ":", 0);
131 log_error("Invalid syntax, ignoring: %s", env
);
135 r
= context_add_ntp_service(c
, word
);
137 log_warning_errno(r
, "Failed to add NTP service \"%s\", ignoring: %m", word
);
143 static int context_ntp_service_is_active(Context
*c
) {
144 UnitStatusInfo
*info
;
149 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
151 LIST_FOREACH(units
, info
, c
->units
)
152 count
+= streq_ptr(info
->active_state
, "active");
157 static int context_ntp_service_is_enabled(Context
*c
) {
158 UnitStatusInfo
*info
;
163 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
165 LIST_FOREACH(units
, info
, c
->units
)
166 count
+= STRPTR_IN_SET(info
->unit_file_state
, "enabled", "enabled-runtime");
171 static int context_ntp_service_exists(Context
*c
) {
172 UnitStatusInfo
*info
;
177 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
179 LIST_FOREACH(units
, info
, c
->units
)
180 count
+= streq_ptr(info
->load_state
, "loaded");
185 static int context_read_data(Context
*c
) {
186 _cleanup_free_
char *t
= NULL
;
191 r
= get_timezone(&t
);
193 log_warning_errno(r
, "/etc/localtime should be a symbolic link to a time zone data file in /usr/share/zoneinfo/.");
195 log_warning_errno(r
, "Failed to get target of /etc/localtime: %m");
197 free_and_replace(c
->zone
, t
);
199 c
->local_rtc
= clock_is_localtime(NULL
) > 0;
204 static int context_write_data_timezone(Context
*c
) {
205 _cleanup_free_
char *p
= NULL
;
210 if (isempty(c
->zone
)) {
211 if (unlink("/etc/localtime") < 0 && errno
!= ENOENT
)
217 p
= strappend("../usr/share/zoneinfo/", c
->zone
);
221 r
= symlink_atomic(p
, "/etc/localtime");
228 static int context_write_data_local_rtc(Context
*c
) {
230 _cleanup_free_
char *s
= NULL
, *w
= NULL
;
234 r
= read_full_file("/etc/adjtime", &s
, NULL
);
242 w
= strdup(NULL_ADJTIME_LOCAL
);
247 const char *e
= "\n"; /* default if there is less than 3 lines */
248 const char *prepend
= "";
251 p
= strchrnul(s
, '\n');
253 /* only one line, no \n terminator */
255 else if (p
[1] == '\0') {
256 /* only one line, with \n terminator */
260 p
= strchr(p
+1, '\n');
262 /* only two lines, no \n terminator */
267 /* third line might have a \n terminator or not */
269 end
= strchr(p
, '\n');
270 /* if we actually have a fourth line, use that as suffix "e", otherwise the default \n */
279 w
= new(char, a
+ (c
->local_rtc
? 5 : 3) + strlen(prepend
) + b
+ 1);
283 *(char*) mempcpy(stpcpy(stpcpy(mempcpy(w
, s
, a
), prepend
), c
->local_rtc
? "LOCAL" : "UTC"), e
, b
) = 0;
285 if (streq(w
, NULL_ADJTIME_UTC
)) {
286 if (unlink("/etc/adjtime") < 0)
295 return write_string_file_atomic_label("/etc/adjtime", w
);
298 static int context_update_ntp_status(Context
*c
, sd_bus
*bus
, sd_bus_message
*m
) {
299 static const struct bus_properties_map map
[] = {
300 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
301 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
302 { "UnitFileState", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_state
) },
305 static sd_bus_message
*_m
= NULL
;
312 /* Suppress multiple call of context_update_ntp_status() within single DBus transaction. */
318 LIST_FOREACH(units
, u
, c
->units
) {
319 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
320 _cleanup_free_
char *path
= NULL
;
322 unit_status_info_clear(u
);
324 path
= unit_dbus_path_from_name(u
->name
);
328 r
= bus_map_all_properties(
330 "org.freedesktop.systemd1",
338 return log_error_errno(r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
344 static int unit_start_or_stop(UnitStatusInfo
*u
, sd_bus
*bus
, sd_bus_error
*error
, bool start
) {
351 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
353 if (streq(u
->active_state
, "active") == start
)
356 r
= sd_bus_call_method(
358 "org.freedesktop.systemd1",
359 "/org/freedesktop/systemd1",
360 "org.freedesktop.systemd1.Manager",
361 start
? "StartUnit" : "StopUnit",
373 static int unit_enable_or_disable(UnitStatusInfo
*u
, sd_bus
*bus
, sd_bus_error
*error
, bool enable
) {
380 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
382 if (streq(u
->unit_file_state
, "enabled") == enable
)
386 r
= sd_bus_call_method(
388 "org.freedesktop.systemd1",
389 "/org/freedesktop/systemd1",
390 "org.freedesktop.systemd1.Manager",
398 r
= sd_bus_call_method(
400 "org.freedesktop.systemd1",
401 "/org/freedesktop/systemd1",
402 "org.freedesktop.systemd1.Manager",
412 r
= sd_bus_call_method(
414 "org.freedesktop.systemd1",
415 "/org/freedesktop/systemd1",
416 "org.freedesktop.systemd1.Manager",
426 static BUS_DEFINE_PROPERTY_GET_GLOBAL(property_get_time
, "t", now(CLOCK_REALTIME
));
427 static BUS_DEFINE_PROPERTY_GET_GLOBAL(property_get_ntp_sync
, "b", ntp_synced());
429 static int property_get_rtc_time(
432 const char *interface
,
433 const char *property
,
434 sd_bus_message
*reply
,
436 sd_bus_error
*error
) {
443 r
= clock_get_hwclock(&tm
);
445 log_warning("/dev/rtc is busy. Is somebody keeping it open continuously? That's not a good idea... Returning a bogus RTC timestamp.");
447 } else if (r
== -ENOENT
) {
448 log_debug("/dev/rtc not found.");
449 t
= 0; /* no RTC found */
451 return sd_bus_error_set_errnof(error
, r
, "Failed to read RTC: %m");
453 t
= (usec_t
) timegm(&tm
) * USEC_PER_SEC
;
455 return sd_bus_message_append(reply
, "t", t
);
458 static int property_get_can_ntp(
461 const char *interface
,
462 const char *property
,
463 sd_bus_message
*reply
,
465 sd_bus_error
*error
) {
467 Context
*c
= userdata
;
476 r
= context_update_ntp_status(c
, bus
, reply
);
480 return sd_bus_message_append(reply
, "b", context_ntp_service_exists(c
) > 0);
483 static int property_get_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_is_active(c
) > 0);
508 static int method_set_timezone(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
509 Context
*c
= userdata
;
516 r
= sd_bus_message_read(m
, "sb", &z
, &interactive
);
520 if (!timezone_is_valid(z
, LOG_DEBUG
))
521 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Invalid time zone '%s'", z
);
523 if (streq_ptr(z
, c
->zone
))
524 return sd_bus_reply_method_return(m
, NULL
);
526 r
= bus_verify_polkit_async(
529 "org.freedesktop.timedate1.set-timezone",
538 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
540 r
= free_and_strdup(&c
->zone
, z
);
544 /* 1. Write new configuration file */
545 r
= context_write_data_timezone(c
);
547 log_error_errno(r
, "Failed to set time zone: %m");
548 return sd_bus_error_set_errnof(error
, r
, "Failed to set time zone: %m");
551 /* 2. Make glibc notice the new timezone */
554 /* 3. Tell the kernel our timezone */
555 r
= clock_set_timezone(NULL
);
557 log_debug_errno(r
, "Failed to tell kernel about timezone, ignoring: %m");
563 /* 4. Sync RTC from system clock, with the new delta */
564 assert_se(clock_gettime(CLOCK_REALTIME
, &ts
) == 0);
565 assert_se(localtime_r(&ts
.tv_sec
, &tm
));
567 r
= clock_set_hwclock(&tm
);
569 log_debug_errno(r
, "Failed to sync time to hardware clock, ignoring: %m");
573 "MESSAGE_ID=" SD_MESSAGE_TIMEZONE_CHANGE_STR
,
574 "TIMEZONE=%s", c
->zone
,
575 "TIMEZONE_SHORTNAME=%s", tzname
[daylight
],
576 "DAYLIGHT=%i", daylight
,
577 LOG_MESSAGE("Changed time zone to '%s' (%s).", c
->zone
, tzname
[daylight
]));
579 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m
), "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "Timezone", NULL
);
581 return sd_bus_reply_method_return(m
, NULL
);
584 static int method_set_local_rtc(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
585 int lrtc
, fix_system
, interactive
;
586 Context
*c
= userdata
;
593 r
= sd_bus_message_read(m
, "bbb", &lrtc
, &fix_system
, &interactive
);
597 if (lrtc
== c
->local_rtc
)
598 return sd_bus_reply_method_return(m
, NULL
);
600 r
= bus_verify_polkit_async(
603 "org.freedesktop.timedate1.set-local-rtc",
616 /* 1. Write new configuration file */
617 r
= context_write_data_local_rtc(c
);
619 log_error_errno(r
, "Failed to set RTC to local/UTC: %m");
620 return sd_bus_error_set_errnof(error
, r
, "Failed to set RTC to local/UTC: %m");
623 /* 2. Tell the kernel our timezone */
624 r
= clock_set_timezone(NULL
);
626 log_debug_errno(r
, "Failed to tell kernel about timezone, ignoring: %m");
628 /* 3. Synchronize clocks */
629 assert_se(clock_gettime(CLOCK_REALTIME
, &ts
) == 0);
634 /* Sync system clock from RTC; first, initialize the timezone fields of struct tm. */
636 localtime_r(&ts
.tv_sec
, &tm
);
638 gmtime_r(&ts
.tv_sec
, &tm
);
640 /* Override the main fields of struct tm, but not the timezone fields */
641 r
= clock_get_hwclock(&tm
);
643 log_debug_errno(r
, "Failed to get hardware clock, ignoring: %m");
645 /* And set the system clock with this */
647 ts
.tv_sec
= mktime(&tm
);
649 ts
.tv_sec
= timegm(&tm
);
651 if (clock_settime(CLOCK_REALTIME
, &ts
) < 0)
652 log_debug_errno(errno
, "Failed to update system clock, ignoring: %m");
658 /* Sync RTC from system clock */
660 localtime_r(&ts
.tv_sec
, &tm
);
662 gmtime_r(&ts
.tv_sec
, &tm
);
664 r
= clock_set_hwclock(&tm
);
666 log_debug_errno(r
, "Failed to sync time to hardware clock, ignoring: %m");
669 log_info("RTC configured to %s time.", c
->local_rtc
? "local" : "UTC");
671 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m
), "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "LocalRTC", NULL
);
673 return sd_bus_reply_method_return(m
, NULL
);
676 static int method_set_time(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
677 sd_bus
*bus
= sd_bus_message_get_bus(m
);
678 int relative
, interactive
, r
;
679 Context
*c
= userdata
;
688 r
= context_update_ntp_status(c
, bus
, m
);
690 return sd_bus_error_set_errnof(error
, r
, "Failed to update context: %m");
692 if (context_ntp_service_is_active(c
) > 0)
693 return sd_bus_error_set(error
, BUS_ERROR_AUTOMATIC_TIME_SYNC_ENABLED
, "Automatic time synchronization is enabled");
695 /* this only gets used if dbus does not provide a timestamp */
696 start
= now(CLOCK_MONOTONIC
);
698 r
= sd_bus_message_read(m
, "xbb", &utc
, &relative
, &interactive
);
702 if (!relative
&& utc
<= 0)
703 return sd_bus_error_set(error
, SD_BUS_ERROR_INVALID_ARGS
, "Invalid absolute time");
705 if (relative
&& utc
== 0)
706 return sd_bus_reply_method_return(m
, NULL
);
711 n
= now(CLOCK_REALTIME
);
714 if ((utc
> 0 && x
< n
) ||
716 return sd_bus_error_set(error
, SD_BUS_ERROR_INVALID_ARGS
, "Time value overflow");
718 timespec_store(&ts
, x
);
720 timespec_store(&ts
, (usec_t
) utc
);
722 r
= bus_verify_polkit_async(
725 "org.freedesktop.timedate1.set-time",
736 /* adjust ts for time spent in program */
737 r
= sd_bus_message_get_monotonic_usec(m
, &start
);
738 /* when sd_bus_message_get_monotonic_usec() returns -ENODATA it does not modify &start */
739 if (r
< 0 && r
!= -ENODATA
)
742 timespec_store(&ts
, timespec_load(&ts
) + (now(CLOCK_MONOTONIC
) - start
));
744 /* Set system clock */
745 if (clock_settime(CLOCK_REALTIME
, &ts
) < 0) {
746 log_error_errno(errno
, "Failed to set local time: %m");
747 return sd_bus_error_set_errnof(error
, errno
, "Failed to set local time: %m");
750 /* Sync down to RTC */
752 localtime_r(&ts
.tv_sec
, &tm
);
754 gmtime_r(&ts
.tv_sec
, &tm
);
756 r
= clock_set_hwclock(&tm
);
758 log_debug_errno(r
, "Failed to update hardware clock, ignoring: %m");
761 "MESSAGE_ID=" SD_MESSAGE_TIME_CHANGE_STR
,
762 "REALTIME="USEC_FMT
, timespec_load(&ts
),
763 LOG_MESSAGE("Changed local time to %s", ctime(&ts
.tv_sec
)));
765 return sd_bus_reply_method_return(m
, NULL
);
768 static int method_set_ntp(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
769 sd_bus
*bus
= sd_bus_message_get_bus(m
);
770 Context
*c
= userdata
;
772 int enable
, interactive
, q
, r
;
778 r
= sd_bus_message_read(m
, "bb", &enable
, &interactive
);
782 r
= context_update_ntp_status(c
, bus
, m
);
786 if (context_ntp_service_exists(c
) <= 0)
787 return sd_bus_error_set(error
, BUS_ERROR_NO_NTP_SUPPORT
, "NTP not supported");
789 r
= bus_verify_polkit_async(
792 "org.freedesktop.timedate1.set-ntp",
804 LIST_FOREACH(units
, u
, c
->units
) {
805 if (!streq(u
->load_state
, "loaded"))
808 q
= unit_enable_or_disable(u
, bus
, error
, enable
);
812 q
= unit_start_or_stop(u
, bus
, error
, enable
);
817 else if (context_ntp_service_is_enabled(c
) <= 0)
818 LIST_FOREACH(units
, u
, c
->units
) {
819 if (!streq(u
->load_state
, "loaded"))
822 r
= unit_enable_or_disable(u
, bus
, error
, enable
);
826 r
= unit_start_or_stop(u
, bus
, error
, enable
);
830 else if (context_ntp_service_is_active(c
) <= 0)
831 LIST_FOREACH(units
, u
, c
->units
) {
832 if (!streq(u
->load_state
, "loaded") ||
833 !streq(u
->unit_file_state
, "enabled"))
836 r
= unit_start_or_stop(u
, bus
, error
, enable
);
843 log_info("Set NTP to %sd", enable_disable(enable
));
845 (void) sd_bus_emit_properties_changed(bus
, "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "NTP", NULL
);
847 return sd_bus_reply_method_return(m
, NULL
);
850 static const sd_bus_vtable timedate_vtable
[] = {
851 SD_BUS_VTABLE_START(0),
852 SD_BUS_PROPERTY("Timezone", "s", NULL
, offsetof(Context
, zone
), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE
),
853 SD_BUS_PROPERTY("LocalRTC", "b", bus_property_get_bool
, offsetof(Context
, local_rtc
), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE
),
854 SD_BUS_PROPERTY("CanNTP", "b", property_get_can_ntp
, 0, 0),
855 SD_BUS_PROPERTY("NTP", "b", property_get_ntp
, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE
),
856 SD_BUS_PROPERTY("NTPSynchronized", "b", property_get_ntp_sync
, 0, 0),
857 SD_BUS_PROPERTY("TimeUSec", "t", property_get_time
, 0, 0),
858 SD_BUS_PROPERTY("RTCTimeUSec", "t", property_get_rtc_time
, 0, 0),
859 SD_BUS_METHOD("SetTime", "xbb", NULL
, method_set_time
, SD_BUS_VTABLE_UNPRIVILEGED
),
860 SD_BUS_METHOD("SetTimezone", "sb", NULL
, method_set_timezone
, SD_BUS_VTABLE_UNPRIVILEGED
),
861 SD_BUS_METHOD("SetLocalRTC", "bbb", NULL
, method_set_local_rtc
, SD_BUS_VTABLE_UNPRIVILEGED
),
862 SD_BUS_METHOD("SetNTP", "bb", NULL
, method_set_ntp
, SD_BUS_VTABLE_UNPRIVILEGED
),
866 static int connect_bus(Context
*c
, sd_event
*event
, sd_bus
**_bus
) {
867 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
874 r
= sd_bus_default_system(&bus
);
876 return log_error_errno(r
, "Failed to get system bus connection: %m");
878 r
= sd_bus_add_object_vtable(bus
, NULL
, "/org/freedesktop/timedate1", "org.freedesktop.timedate1", timedate_vtable
, c
);
880 return log_error_errno(r
, "Failed to register object: %m");
882 r
= sd_bus_request_name_async(bus
, NULL
, "org.freedesktop.timedate1", 0, NULL
, NULL
);
884 return log_error_errno(r
, "Failed to request name: %m");
886 r
= sd_bus_attach_event(bus
, event
, 0);
888 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
890 *_bus
= TAKE_PTR(bus
);
895 int main(int argc
, char *argv
[]) {
896 Context context
= {};
897 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
898 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
901 log_set_target(LOG_TARGET_AUTO
);
902 log_parse_environment();
908 log_error("This program takes no arguments.");
913 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGTERM
, SIGINT
, -1) >= 0);
915 r
= sd_event_default(&event
);
917 log_error_errno(r
, "Failed to allocate event loop: %m");
921 (void) sd_event_set_watchdog(event
, true);
923 r
= sd_event_add_signal(event
, NULL
, SIGINT
, NULL
, NULL
);
927 r
= sd_event_add_signal(event
, NULL
, SIGTERM
, NULL
, NULL
);
931 r
= connect_bus(&context
, event
, &bus
);
935 (void) sd_bus_negotiate_timestamp(bus
, true);
937 r
= context_read_data(&context
);
939 log_error_errno(r
, "Failed to read time zone data: %m");
943 r
= context_parse_ntp_services(&context
);
947 r
= bus_event_loop_with_idle(event
, bus
, "org.freedesktop.timedate1", DEFAULT_EXIT_USEC
, NULL
, NULL
);
949 log_error_errno(r
, "Failed to run event loop: %m");
954 context_free(&context
);
956 return r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;