1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
11 #include "sd-messages.h"
13 #include "alloc-util.h"
14 #include "bus-common-errors.h"
15 #include "bus-error.h"
16 #include "bus-get-properties.h"
17 #include "bus-locator.h"
18 #include "bus-log-control-api.h"
19 #include "bus-map-properties.h"
20 #include "bus-polkit.h"
21 #include "clock-util.h"
22 #include "conf-files.h"
25 #include "fileio-label.h"
30 #include "main-func.h"
31 #include "memory-util.h"
32 #include "missing_capability.h"
33 #include "path-util.h"
34 #include "selinux-util.h"
35 #include "service-util.h"
36 #include "signal-util.h"
37 #include "string-util.h"
40 #include "unit-name.h"
41 #include "user-util.h"
43 #define NULL_ADJTIME_UTC "0.0 0 0\n0\nUTC\n"
44 #define NULL_ADJTIME_LOCAL "0.0 0 0\n0\nLOCAL\n"
46 #define UNIT_LIST_DIRS (const char* const*) CONF_PATHS_STRV("systemd/ntp-units.d")
48 typedef struct UnitStatusInfo
{
51 char *unit_file_state
;
55 LIST_FIELDS(struct UnitStatusInfo
, units
);
58 typedef struct Context
{
61 Hashmap
*polkit_registry
;
62 sd_bus_message
*cache
;
64 sd_bus_slot
*slot_job_removed
;
66 LIST_HEAD(UnitStatusInfo
, units
);
69 #define log_unit_full_errno_zerook(unit, level, error, ...) \
71 const UnitStatusInfo *_u = (unit); \
72 _u ? log_object_internal(level, error, PROJECT_FILE, __LINE__, __func__, "UNIT=", _u->name, NULL, NULL, ##__VA_ARGS__) : \
73 log_internal(level, error, PROJECT_FILE, __LINE__, __func__, ##__VA_ARGS__); \
76 #define log_unit_full_errno(unit, level, error, ...) \
78 int _error = (error); \
79 ASSERT_NON_ZERO(_error); \
80 log_unit_full_errno_zerook(unit, level, _error, ##__VA_ARGS__); \
83 #define log_unit_full(unit, level, ...) (void) log_unit_full_errno_zerook(unit, level, 0, ##__VA_ARGS__)
85 #define log_unit_debug(unit, ...) log_unit_full(unit, LOG_DEBUG, ##__VA_ARGS__)
86 #define log_unit_info(unit, ...) log_unit_full(unit, LOG_INFO, ##__VA_ARGS__)
87 #define log_unit_notice(unit, ...) log_unit_full(unit, LOG_NOTICE, ##__VA_ARGS__)
88 #define log_unit_warning(unit, ...) log_unit_full(unit, LOG_WARNING, ##__VA_ARGS__)
89 #define log_unit_error(unit, ...) log_unit_full(unit, LOG_ERR, ##__VA_ARGS__)
91 #define log_unit_debug_errno(unit, error, ...) log_unit_full_errno(unit, LOG_DEBUG, error, ##__VA_ARGS__)
92 #define log_unit_info_errno(unit, error, ...) log_unit_full_errno(unit, LOG_INFO, error, ##__VA_ARGS__)
93 #define log_unit_notice_errno(unit, error, ...) log_unit_full_errno(unit, LOG_NOTICE, error, ##__VA_ARGS__)
94 #define log_unit_warning_errno(unit, error, ...) log_unit_full_errno(unit, LOG_WARNING, error, ##__VA_ARGS__)
95 #define log_unit_error_errno(unit, error, ...) log_unit_full_errno(unit, LOG_ERR, error, ##__VA_ARGS__)
97 static void unit_status_info_clear(UnitStatusInfo
*p
) {
100 p
->load_state
= mfree(p
->load_state
);
101 p
->unit_file_state
= mfree(p
->unit_file_state
);
102 p
->active_state
= mfree(p
->active_state
);
105 static UnitStatusInfo
*unit_status_info_free(UnitStatusInfo
*p
) {
109 unit_status_info_clear(p
);
115 DEFINE_TRIVIAL_CLEANUP_FUNC(UnitStatusInfo
*, unit_status_info_free
);
117 static void context_clear(Context
*c
) {
123 bus_verify_polkit_async_registry_free(c
->polkit_registry
);
124 sd_bus_message_unref(c
->cache
);
126 sd_bus_slot_unref(c
->slot_job_removed
);
128 while ((p
= c
->units
)) {
129 LIST_REMOVE(units
, c
->units
, p
);
130 unit_status_info_free(p
);
134 static int context_add_ntp_service(Context
*c
, const char *s
, const char *source
) {
135 _cleanup_(unit_status_info_freep
) UnitStatusInfo
*unit
= NULL
;
141 if (!unit_name_is_valid(s
, UNIT_NAME_PLAIN
))
144 /* Do not add this if it is already listed */
145 LIST_FOREACH(units
, u
, c
->units
)
146 if (streq(u
->name
, s
))
149 unit
= new0(UnitStatusInfo
, 1);
153 unit
->name
= strdup(s
);
157 LIST_APPEND(units
, c
->units
, unit
);
158 log_unit_debug(unit
, "added from %s.", source
);
164 static int context_parse_ntp_services_from_environment(Context
*c
) {
170 env
= getenv("SYSTEMD_TIMEDATED_NTP_SERVICES");
174 log_debug("Using list of ntp services from environment variable $SYSTEMD_TIMEDATED_NTP_SERVICES=%s.", env
);
177 _cleanup_free_
char *word
= NULL
;
179 r
= extract_first_word(&p
, &word
, ":", 0);
185 log_error("Invalid syntax, ignoring: %s", env
);
189 r
= context_add_ntp_service(c
, word
, "$SYSTEMD_TIMEDATED_NTP_SERVICES");
191 log_warning_errno(r
, "Failed to add NTP service \"%s\", ignoring: %m", word
);
197 static int context_parse_ntp_services_from_disk(Context
*c
) {
198 _cleanup_strv_free_
char **files
= NULL
;
201 r
= conf_files_list_strv(&files
, ".list", NULL
, CONF_FILES_FILTER_MASKED
, UNIT_LIST_DIRS
);
203 return log_error_errno(r
, "Failed to enumerate .list files: %m");
205 STRV_FOREACH(f
, files
) {
206 _cleanup_fclose_
FILE *file
= NULL
;
208 log_debug("Reading file '%s'", *f
);
210 r
= fopen_unlocked(*f
, "re", &file
);
212 log_error_errno(r
, "Failed to open %s, ignoring: %m", *f
);
217 _cleanup_free_
char *line
= NULL
;
220 r
= read_line(file
, LINE_MAX
, &line
);
222 log_error_errno(r
, "Failed to read %s, ignoring: %m", *f
);
228 word
= strstrip(line
);
229 if (isempty(word
) || startswith(word
, "#"))
232 r
= context_add_ntp_service(c
, word
, *f
);
234 log_warning_errno(r
, "Failed to add NTP service \"%s\", ignoring: %m", word
);
241 static int context_parse_ntp_services(Context
*c
) {
244 r
= context_parse_ntp_services_from_environment(c
);
248 return context_parse_ntp_services_from_disk(c
);
251 static int context_ntp_service_is_active(Context
*c
) {
256 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
258 LIST_FOREACH(units
, info
, c
->units
)
259 count
+= !STRPTR_IN_SET(info
->active_state
, "inactive", "failed");
264 static int context_ntp_service_exists(Context
*c
) {
269 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
271 LIST_FOREACH(units
, info
, c
->units
)
272 count
+= streq_ptr(info
->load_state
, "loaded");
277 static int context_read_data(Context
*c
) {
278 _cleanup_free_
char *t
= NULL
;
283 r
= get_timezone(&t
);
285 log_warning_errno(r
, "/etc/localtime should be a symbolic link to a time zone data file in /usr/share/zoneinfo/.");
287 log_warning_errno(r
, "Failed to get target of /etc/localtime: %m");
289 free_and_replace(c
->zone
, t
);
291 c
->local_rtc
= clock_is_localtime(NULL
) > 0;
296 static int context_write_data_timezone(Context
*c
) {
297 _cleanup_free_
char *p
= NULL
;
302 /* No timezone is very similar to UTC. Hence in either of these cases link the UTC file in. Except if
303 * it isn't installed, in which case we remove the symlink altogether. Since glibc defaults to an
304 * internal version of UTC in that case behaviour is mostly equivalent. We still prefer creating the
305 * symlink though, since things are more self explanatory then. */
307 if (isempty(c
->zone
) || streq(c
->zone
, "UTC")) {
309 if (access("/usr/share/zoneinfo/UTC", F_OK
) < 0) {
311 if (unlink("/etc/localtime") < 0 && errno
!= ENOENT
)
317 source
= "../usr/share/zoneinfo/UTC";
319 p
= path_join("../usr/share/zoneinfo", c
->zone
);
326 return symlink_atomic(source
, "/etc/localtime");
329 static int context_write_data_local_rtc(Context
*c
) {
330 _cleanup_free_
char *s
= NULL
, *w
= NULL
;
335 r
= read_full_file("/etc/adjtime", &s
, NULL
);
343 w
= strdup(NULL_ADJTIME_LOCAL
);
348 const char *e
= "\n"; /* default if there is less than 3 lines */
349 const char *prepend
= "";
352 p
= strchrnul(s
, '\n');
354 /* only one line, no \n terminator */
356 else if (p
[1] == '\0') {
357 /* only one line, with \n terminator */
361 p
= strchr(p
+1, '\n');
363 /* only two lines, no \n terminator */
368 /* third line might have a \n terminator or not */
370 end
= strchr(p
, '\n');
371 /* if we actually have a fourth line, use that as suffix "e", otherwise the default \n */
380 w
= new(char, a
+ (c
->local_rtc
? 5 : 3) + strlen(prepend
) + b
+ 1);
384 *(char*) mempcpy(stpcpy(stpcpy(mempcpy(w
, s
, a
), prepend
), c
->local_rtc
? "LOCAL" : "UTC"), e
, b
) = 0;
386 if (streq(w
, NULL_ADJTIME_UTC
)) {
387 if (unlink("/etc/adjtime") < 0)
395 r
= mac_selinux_init();
399 return write_string_file_atomic_label("/etc/adjtime", w
);
402 static int context_update_ntp_status(Context
*c
, sd_bus
*bus
, sd_bus_message
*m
) {
403 static const struct bus_properties_map map
[] = {
404 { "LoadState", "s", NULL
, offsetof(UnitStatusInfo
, load_state
) },
405 { "ActiveState", "s", NULL
, offsetof(UnitStatusInfo
, active_state
) },
406 { "UnitFileState", "s", NULL
, offsetof(UnitStatusInfo
, unit_file_state
) },
414 /* Suppress calling context_update_ntp_status() multiple times within single DBus transaction. */
419 sd_bus_message_unref(c
->cache
);
420 c
->cache
= sd_bus_message_ref(m
);
423 LIST_FOREACH(units
, u
, c
->units
) {
424 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
425 _cleanup_free_
char *path
= NULL
;
427 unit_status_info_clear(u
);
429 path
= unit_dbus_path_from_name(u
->name
);
433 r
= bus_map_all_properties(
435 "org.freedesktop.systemd1",
443 return log_unit_error_errno(u
, r
, "Failed to get properties: %s", bus_error_message(&error
, r
));
449 static int match_job_removed(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
450 Context
*c
= userdata
;
458 r
= sd_bus_message_read(m
, "uoss", NULL
, &path
, NULL
, NULL
);
460 bus_log_parse_error(r
);
464 LIST_FOREACH(units
, u
, c
->units
)
465 if (streq_ptr(path
, u
->path
))
466 u
->path
= mfree(u
->path
);
471 c
->slot_job_removed
= sd_bus_slot_unref(c
->slot_job_removed
);
473 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m
),
474 "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "NTP",
481 static int unit_start_or_stop(UnitStatusInfo
*u
, sd_bus
*bus
, sd_bus_error
*error
, bool start
) {
482 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
493 start
? "StartUnit" : "StopUnit",
499 log_unit_full_errno_zerook(u
, r
< 0 ? LOG_WARNING
: LOG_DEBUG
, r
,
500 "%s unit: %m", start
? "Starting" : "Stopping");
504 r
= sd_bus_message_read(reply
, "o", &path
);
506 return bus_log_parse_error(r
);
508 r
= free_and_strdup(&u
->path
, path
);
515 static int unit_enable_or_disable(UnitStatusInfo
*u
, sd_bus
*bus
, sd_bus_error
*error
, bool enable
) {
522 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
524 if (streq(u
->unit_file_state
, "enabled") == enable
) {
525 log_unit_debug(u
, "already %sd.", enable_disable(enable
));
529 log_unit_info(u
, "%s unit.", enable
? "Enabling" : "Disabling");
554 r
= bus_call_method(bus
, bus_systemd_mgr
, "Reload", error
, NULL
, NULL
);
561 static bool ntp_synced(void) {
562 struct timex txc
= {};
564 if (adjtimex(&txc
) < 0)
567 /* Consider the system clock synchronized if the reported maximum error is smaller than the maximum
568 * value (16 seconds). Ignore the STA_UNSYNC flag as it may have been set to prevent the kernel from
569 * touching the RTC. */
570 return txc
.maxerror
< 16000000;
573 static BUS_DEFINE_PROPERTY_GET_GLOBAL(property_get_time
, "t", now(CLOCK_REALTIME
));
574 static BUS_DEFINE_PROPERTY_GET_GLOBAL(property_get_ntp_sync
, "b", ntp_synced());
576 static int property_get_rtc_time(
579 const char *interface
,
580 const char *property
,
581 sd_bus_message
*reply
,
583 sd_bus_error
*error
) {
589 r
= clock_get_hwclock(&tm
);
591 log_warning("/dev/rtc is busy. Is somebody keeping it open continuously? That's not a good idea... Returning a bogus RTC timestamp.");
592 else if (r
== -ENOENT
)
593 log_debug("/dev/rtc not found.");
595 return sd_bus_error_set_errnof(error
, r
, "Failed to read RTC: %m");
597 t
= (usec_t
) timegm(&tm
) * USEC_PER_SEC
;
599 return sd_bus_message_append(reply
, "t", t
);
602 static int property_get_can_ntp(
605 const char *interface
,
606 const char *property
,
607 sd_bus_message
*reply
,
609 sd_bus_error
*error
) {
611 Context
*c
= userdata
;
620 if (c
->slot_job_removed
)
621 /* When the previous request is not finished, then assume NTP is enabled. */
622 return sd_bus_message_append(reply
, "b", true);
624 r
= context_update_ntp_status(c
, bus
, reply
);
628 return sd_bus_message_append(reply
, "b", context_ntp_service_exists(c
) > 0);
631 static int property_get_ntp(
634 const char *interface
,
635 const char *property
,
636 sd_bus_message
*reply
,
638 sd_bus_error
*error
) {
640 Context
*c
= userdata
;
649 if (c
->slot_job_removed
)
650 /* When the previous request is not finished, then assume NTP is active. */
651 return sd_bus_message_append(reply
, "b", true);
653 r
= context_update_ntp_status(c
, bus
, reply
);
657 return sd_bus_message_append(reply
, "b", context_ntp_service_is_active(c
) > 0);
660 static int method_set_timezone(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
661 Context
*c
= userdata
;
668 r
= sd_bus_message_read(m
, "sb", &z
, &interactive
);
672 if (!timezone_is_valid(z
, LOG_DEBUG
))
673 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Invalid or not installed time zone '%s'", z
);
675 if (streq_ptr(z
, c
->zone
))
676 return sd_bus_reply_method_return(m
, NULL
);
678 r
= bus_verify_polkit_async(
681 "org.freedesktop.timedate1.set-timezone",
690 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
692 r
= free_and_strdup(&c
->zone
, z
);
696 /* 1. Write new configuration file */
697 r
= context_write_data_timezone(c
);
699 log_error_errno(r
, "Failed to set time zone: %m");
700 return sd_bus_error_set_errnof(error
, r
, "Failed to set time zone: %m");
703 /* 2. Make glibc notice the new timezone */
706 /* 3. Tell the kernel our timezone */
707 r
= clock_set_timezone(NULL
);
709 log_debug_errno(r
, "Failed to tell kernel about timezone, ignoring: %m");
715 /* 4. Sync RTC from system clock, with the new delta */
716 assert_se(clock_gettime(CLOCK_REALTIME
, &ts
) == 0);
717 assert_se(localtime_r(&ts
.tv_sec
, &tm
));
719 r
= clock_set_hwclock(&tm
);
721 log_debug_errno(r
, "Failed to sync time to hardware clock, ignoring: %m");
725 "MESSAGE_ID=" SD_MESSAGE_TIMEZONE_CHANGE_STR
,
726 "TIMEZONE=%s", c
->zone
,
727 "TIMEZONE_SHORTNAME=%s", tzname
[daylight
],
728 "DAYLIGHT=%i", daylight
,
729 LOG_MESSAGE("Changed time zone to '%s' (%s).", c
->zone
, tzname
[daylight
]));
731 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m
),
732 "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "Timezone",
735 return sd_bus_reply_method_return(m
, NULL
);
738 static int method_set_local_rtc(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
739 int lrtc
, fix_system
, interactive
;
740 Context
*c
= userdata
;
747 r
= sd_bus_message_read(m
, "bbb", &lrtc
, &fix_system
, &interactive
);
751 if (lrtc
== c
->local_rtc
&& !fix_system
)
752 return sd_bus_reply_method_return(m
, NULL
);
754 r
= bus_verify_polkit_async(
757 "org.freedesktop.timedate1.set-local-rtc",
768 if (lrtc
!= c
->local_rtc
) {
771 /* 1. Write new configuration file */
772 r
= context_write_data_local_rtc(c
);
774 log_error_errno(r
, "Failed to set RTC to %s: %m", lrtc
? "local" : "UTC");
775 return sd_bus_error_set_errnof(error
, r
, "Failed to set RTC to %s: %m", lrtc
? "local" : "UTC");
779 /* 2. Tell the kernel our timezone */
780 r
= clock_set_timezone(NULL
);
782 log_debug_errno(r
, "Failed to tell kernel about timezone, ignoring: %m");
784 /* 3. Synchronize clocks */
785 assert_se(clock_gettime(CLOCK_REALTIME
, &ts
) == 0);
790 /* Sync system clock from RTC; first, initialize the timezone fields of struct tm. */
791 localtime_or_gmtime_r(&ts
.tv_sec
, &tm
, !c
->local_rtc
);
793 /* Override the main fields of struct tm, but not the timezone fields */
794 r
= clock_get_hwclock(&tm
);
796 log_debug_errno(r
, "Failed to get hardware clock, ignoring: %m");
798 /* And set the system clock with this */
799 ts
.tv_sec
= mktime_or_timegm(&tm
, !c
->local_rtc
);
801 if (clock_settime(CLOCK_REALTIME
, &ts
) < 0)
802 log_debug_errno(errno
, "Failed to update system clock, ignoring: %m");
808 /* Sync RTC from system clock */
809 localtime_or_gmtime_r(&ts
.tv_sec
, &tm
, !c
->local_rtc
);
811 r
= clock_set_hwclock(&tm
);
813 log_debug_errno(r
, "Failed to sync time to hardware clock, ignoring: %m");
816 log_info("RTC configured to %s time.", c
->local_rtc
? "local" : "UTC");
818 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m
),
819 "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "LocalRTC",
822 return sd_bus_reply_method_return(m
, NULL
);
825 static int method_set_time(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
826 sd_bus
*bus
= sd_bus_message_get_bus(m
);
827 char buf
[FORMAT_TIMESTAMP_MAX
];
828 int relative
, interactive
, r
;
829 Context
*c
= userdata
;
838 if (c
->slot_job_removed
)
839 return sd_bus_error_set(error
, BUS_ERROR_AUTOMATIC_TIME_SYNC_ENABLED
, "Previous request is not finished, refusing.");
841 r
= context_update_ntp_status(c
, bus
, m
);
843 return sd_bus_error_set_errnof(error
, r
, "Failed to update context: %m");
845 if (context_ntp_service_is_active(c
) > 0)
846 return sd_bus_error_set(error
, BUS_ERROR_AUTOMATIC_TIME_SYNC_ENABLED
, "Automatic time synchronization is enabled");
848 /* this only gets used if dbus does not provide a timestamp */
849 start
= now(CLOCK_MONOTONIC
);
851 r
= sd_bus_message_read(m
, "xbb", &utc
, &relative
, &interactive
);
855 if (!relative
&& utc
<= 0)
856 return sd_bus_error_set(error
, SD_BUS_ERROR_INVALID_ARGS
, "Invalid absolute time");
858 if (relative
&& utc
== 0)
859 return sd_bus_reply_method_return(m
, NULL
);
864 n
= now(CLOCK_REALTIME
);
867 if ((utc
> 0 && x
< n
) ||
869 return sd_bus_error_set(error
, SD_BUS_ERROR_INVALID_ARGS
, "Time value overflow");
871 timespec_store(&ts
, x
);
873 timespec_store(&ts
, (usec_t
) utc
);
875 r
= bus_verify_polkit_async(
878 "org.freedesktop.timedate1.set-time",
889 /* adjust ts for time spent in program */
890 r
= sd_bus_message_get_monotonic_usec(m
, &start
);
891 /* when sd_bus_message_get_monotonic_usec() returns -ENODATA it does not modify &start */
892 if (r
< 0 && r
!= -ENODATA
)
895 timespec_store(&ts
, timespec_load(&ts
) + (now(CLOCK_MONOTONIC
) - start
));
897 /* Set system clock */
898 if (clock_settime(CLOCK_REALTIME
, &ts
) < 0) {
899 log_error_errno(errno
, "Failed to set local time: %m");
900 return sd_bus_error_set_errnof(error
, errno
, "Failed to set local time: %m");
903 /* Sync down to RTC */
904 localtime_or_gmtime_r(&ts
.tv_sec
, &tm
, !c
->local_rtc
);
906 r
= clock_set_hwclock(&tm
);
908 log_debug_errno(r
, "Failed to update hardware clock, ignoring: %m");
911 "MESSAGE_ID=" SD_MESSAGE_TIME_CHANGE_STR
,
912 "REALTIME="USEC_FMT
, timespec_load(&ts
),
913 LOG_MESSAGE("Changed local time to %s", strnull(format_timestamp(buf
, sizeof(buf
), timespec_load(&ts
)))));
915 return sd_bus_reply_method_return(m
, NULL
);
918 static int method_set_ntp(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
919 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*slot
= NULL
;
920 sd_bus
*bus
= sd_bus_message_get_bus(m
);
921 Context
*c
= userdata
;
922 const UnitStatusInfo
*selected
= NULL
;
923 int enable
, interactive
, q
, r
;
929 r
= sd_bus_message_read(m
, "bb", &enable
, &interactive
);
933 r
= context_update_ntp_status(c
, bus
, m
);
937 if (context_ntp_service_exists(c
) <= 0)
938 return sd_bus_error_set(error
, BUS_ERROR_NO_NTP_SUPPORT
, "NTP not supported");
940 r
= bus_verify_polkit_async(
943 "org.freedesktop.timedate1.set-ntp",
954 /* This method may be called frequently. Forget the previous job if it has not completed yet. */
955 LIST_FOREACH(units
, u
, c
->units
)
956 u
->path
= mfree(u
->path
);
958 if (!c
->slot_job_removed
) {
959 r
= bus_match_signal_async(
964 match_job_removed
, NULL
, c
);
970 LIST_FOREACH(units
, u
, c
->units
) {
971 bool enable_this_one
= !selected
;
973 if (!streq(u
->load_state
, "loaded"))
976 r
= unit_enable_or_disable(u
, bus
, error
, enable_this_one
);
978 /* If enablement failed, don't start this unit. */
979 enable_this_one
= false;
981 r
= unit_start_or_stop(u
, bus
, error
, enable_this_one
);
983 log_unit_warning_errno(u
, r
, "Failed to %s %sd NTP unit, ignoring: %m",
984 enable_this_one
? "start" : "stop",
985 enable_disable(enable_this_one
));
990 LIST_FOREACH(units
, u
, c
->units
) {
991 if (!streq(u
->load_state
, "loaded"))
994 q
= unit_enable_or_disable(u
, bus
, error
, false);
998 q
= unit_start_or_stop(u
, bus
, error
, false);
1005 if (enable
&& !selected
)
1006 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
), "No NTP service found to enable.");
1009 c
->slot_job_removed
= TAKE_PTR(slot
);
1012 log_info("Set NTP to enabled (%s).", selected
->name
);
1014 log_info("Set NTP to disabled.");
1016 return sd_bus_reply_method_return(m
, NULL
);
1019 static int method_list_timezones(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
1020 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1021 _cleanup_strv_free_
char **zones
= NULL
;
1026 r
= get_timezones(&zones
);
1028 return sd_bus_error_set_errnof(error
, r
, "Failed to read list of time zones: %m");
1030 r
= sd_bus_message_new_method_return(m
, &reply
);
1034 r
= sd_bus_message_append_strv(reply
, zones
);
1038 return sd_bus_send(NULL
, reply
, NULL
);
1041 static const sd_bus_vtable timedate_vtable
[] = {
1042 SD_BUS_VTABLE_START(0),
1044 SD_BUS_PROPERTY("Timezone", "s", NULL
, offsetof(Context
, zone
), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE
),
1045 SD_BUS_PROPERTY("LocalRTC", "b", bus_property_get_bool
, offsetof(Context
, local_rtc
), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE
),
1046 SD_BUS_PROPERTY("CanNTP", "b", property_get_can_ntp
, 0, 0),
1047 SD_BUS_PROPERTY("NTP", "b", property_get_ntp
, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE
),
1048 SD_BUS_PROPERTY("NTPSynchronized", "b", property_get_ntp_sync
, 0, 0),
1049 SD_BUS_PROPERTY("TimeUSec", "t", property_get_time
, 0, 0),
1050 SD_BUS_PROPERTY("RTCTimeUSec", "t", property_get_rtc_time
, 0, 0),
1052 SD_BUS_METHOD_WITH_ARGS("SetTime",
1053 SD_BUS_ARGS("x", usec_utc
, "b", relative
, "b", interactive
),
1056 SD_BUS_VTABLE_UNPRIVILEGED
),
1057 SD_BUS_METHOD_WITH_ARGS("SetTimezone",
1058 SD_BUS_ARGS("s", timezone
, "b", interactive
),
1060 method_set_timezone
,
1061 SD_BUS_VTABLE_UNPRIVILEGED
),
1062 SD_BUS_METHOD_WITH_ARGS("SetLocalRTC",
1063 SD_BUS_ARGS("b", local_rtc
, "b", fix_system
, "b", interactive
),
1065 method_set_local_rtc
,
1066 SD_BUS_VTABLE_UNPRIVILEGED
),
1067 SD_BUS_METHOD_WITH_ARGS("SetNTP",
1068 SD_BUS_ARGS("b", use_ntp
, "b", interactive
),
1071 SD_BUS_VTABLE_UNPRIVILEGED
),
1072 SD_BUS_METHOD_WITH_ARGS("ListTimezones",
1074 SD_BUS_RESULT("as", timezones
),
1075 method_list_timezones
,
1076 SD_BUS_VTABLE_UNPRIVILEGED
),
1081 const BusObjectImplementation manager_object
= {
1082 "/org/freedesktop/timedate1",
1083 "org.freedesktop.timedate1",
1084 .vtables
= BUS_VTABLES(timedate_vtable
),
1087 static int connect_bus(Context
*c
, sd_event
*event
, sd_bus
**_bus
) {
1088 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
1095 r
= sd_bus_default_system(&bus
);
1097 return log_error_errno(r
, "Failed to get system bus connection: %m");
1099 r
= bus_add_implementation(bus
, &manager_object
, c
);
1103 r
= bus_log_control_api_register(bus
);
1107 r
= sd_bus_request_name_async(bus
, NULL
, "org.freedesktop.timedate1", 0, NULL
, NULL
);
1109 return log_error_errno(r
, "Failed to request name: %m");
1111 r
= sd_bus_attach_event(bus
, event
, 0);
1113 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
1115 *_bus
= TAKE_PTR(bus
);
1120 static int run(int argc
, char *argv
[]) {
1121 _cleanup_(context_clear
) Context context
= {};
1122 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
1123 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
1128 r
= service_parse_argv("systemd-timedated.service",
1129 "Manage the system clock and timezone and NTP enablement.",
1130 BUS_IMPLEMENTATIONS(&manager_object
,
1131 &log_control_object
),
1138 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGTERM
, SIGINT
, -1) >= 0);
1140 r
= sd_event_default(&event
);
1142 return log_error_errno(r
, "Failed to allocate event loop: %m");
1144 (void) sd_event_set_watchdog(event
, true);
1146 r
= sd_event_add_signal(event
, NULL
, SIGINT
, NULL
, NULL
);
1148 return log_error_errno(r
, "Failed to install SIGINT handler: %m");
1150 r
= sd_event_add_signal(event
, NULL
, SIGTERM
, NULL
, NULL
);
1152 return log_error_errno(r
, "Failed to install SIGTERM handler: %m");
1154 r
= connect_bus(&context
, event
, &bus
);
1158 (void) sd_bus_negotiate_timestamp(bus
, true);
1160 r
= context_read_data(&context
);
1162 return log_error_errno(r
, "Failed to read time zone data: %m");
1164 r
= context_parse_ntp_services(&context
);
1168 r
= bus_event_loop_with_idle(event
, bus
, "org.freedesktop.timedate1", DEFAULT_EXIT_USEC
, NULL
, NULL
);
1170 return log_error_errno(r
, "Failed to run event loop: %m");
1175 DEFINE_MAIN_FUNCTION(run
);