udev: String substitutions can be done in ENV, too
[systemd_ALT.git] / src / timedate / timedated.c
blob2f52d5bdd6a14194570bc97f68cc81fd4f34f640
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include <errno.h>
4 #include <sys/stat.h>
5 #include <sys/timex.h>
6 #include <sys/types.h>
7 #include <unistd.h>
9 #include "sd-bus.h"
10 #include "sd-event.h"
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 "bus-unit-util.h"
22 #include "clock-util.h"
23 #include "conf-files.h"
24 #include "constants.h"
25 #include "fd-util.h"
26 #include "fileio-label.h"
27 #include "fileio.h"
28 #include "fs-util.h"
29 #include "hashmap.h"
30 #include "list.h"
31 #include "main-func.h"
32 #include "memory-util.h"
33 #include "missing_capability.h"
34 #include "path-util.h"
35 #include "selinux-util.h"
36 #include "service-util.h"
37 #include "signal-util.h"
38 #include "string-util.h"
39 #include "strv.h"
40 #include "unit-def.h"
41 #include "unit-name.h"
42 #include "user-util.h"
44 #define NULL_ADJTIME_UTC "0.0 0 0\n0\nUTC\n"
45 #define NULL_ADJTIME_LOCAL "0.0 0 0\n0\nLOCAL\n"
47 #define UNIT_LIST_DIRS (const char* const*) CONF_PATHS_STRV("systemd/ntp-units.d")
49 typedef struct UnitStatusInfo {
50 char *name;
51 char *load_state;
52 char *unit_file_state;
53 char *active_state;
54 char *path;
56 LIST_FIELDS(struct UnitStatusInfo, units);
57 } UnitStatusInfo;
59 typedef struct Context {
60 char *zone;
61 bool local_rtc;
62 Hashmap *polkit_registry;
63 sd_bus_message *cache;
65 sd_bus_slot *slot_job_removed;
67 LIST_HEAD(UnitStatusInfo, units);
68 } Context;
70 #define log_unit_full_errno_zerook(unit, level, error, ...) \
71 ({ \
72 const UnitStatusInfo *_u = (unit); \
73 _u ? log_object_internal(level, error, PROJECT_FILE, __LINE__, __func__, "UNIT=", _u->name, NULL, NULL, ##__VA_ARGS__) : \
74 log_internal(level, error, PROJECT_FILE, __LINE__, __func__, ##__VA_ARGS__); \
77 #define log_unit_full_errno(unit, level, error, ...) \
78 ({ \
79 int _error = (error); \
80 ASSERT_NON_ZERO(_error); \
81 log_unit_full_errno_zerook(unit, level, _error, ##__VA_ARGS__); \
84 #define log_unit_full(unit, level, ...) (void) log_unit_full_errno_zerook(unit, level, 0, ##__VA_ARGS__)
86 #define log_unit_debug(unit, ...) log_unit_full(unit, LOG_DEBUG, ##__VA_ARGS__)
87 #define log_unit_info(unit, ...) log_unit_full(unit, LOG_INFO, ##__VA_ARGS__)
88 #define log_unit_notice(unit, ...) log_unit_full(unit, LOG_NOTICE, ##__VA_ARGS__)
89 #define log_unit_warning(unit, ...) log_unit_full(unit, LOG_WARNING, ##__VA_ARGS__)
90 #define log_unit_error(unit, ...) log_unit_full(unit, LOG_ERR, ##__VA_ARGS__)
92 #define log_unit_debug_errno(unit, error, ...) log_unit_full_errno(unit, LOG_DEBUG, error, ##__VA_ARGS__)
93 #define log_unit_info_errno(unit, error, ...) log_unit_full_errno(unit, LOG_INFO, error, ##__VA_ARGS__)
94 #define log_unit_notice_errno(unit, error, ...) log_unit_full_errno(unit, LOG_NOTICE, error, ##__VA_ARGS__)
95 #define log_unit_warning_errno(unit, error, ...) log_unit_full_errno(unit, LOG_WARNING, error, ##__VA_ARGS__)
96 #define log_unit_error_errno(unit, error, ...) log_unit_full_errno(unit, LOG_ERR, error, ##__VA_ARGS__)
98 static void unit_status_info_clear(UnitStatusInfo *p) {
99 assert(p);
101 p->load_state = mfree(p->load_state);
102 p->unit_file_state = mfree(p->unit_file_state);
103 p->active_state = mfree(p->active_state);
106 static UnitStatusInfo *unit_status_info_free(UnitStatusInfo *p) {
107 if (!p)
108 return NULL;
110 unit_status_info_clear(p);
111 free(p->name);
112 free(p->path);
113 return mfree(p);
116 DEFINE_TRIVIAL_CLEANUP_FUNC(UnitStatusInfo*, unit_status_info_free);
118 static void context_clear(Context *c) {
119 UnitStatusInfo *p;
121 assert(c);
123 free(c->zone);
124 bus_verify_polkit_async_registry_free(c->polkit_registry);
125 sd_bus_message_unref(c->cache);
127 sd_bus_slot_unref(c->slot_job_removed);
129 while ((p = c->units)) {
130 LIST_REMOVE(units, c->units, p);
131 unit_status_info_free(p);
135 static int context_add_ntp_service(Context *c, const char *s, const char *source) {
136 _cleanup_(unit_status_info_freep) UnitStatusInfo *unit = NULL;
138 assert(c);
139 assert(s);
140 assert(source);
142 if (!unit_name_is_valid(s, UNIT_NAME_PLAIN))
143 return -EINVAL;
145 /* Do not add this if it is already listed */
146 LIST_FOREACH(units, u, c->units)
147 if (streq(u->name, s))
148 return 0;
150 unit = new0(UnitStatusInfo, 1);
151 if (!unit)
152 return -ENOMEM;
154 unit->name = strdup(s);
155 if (!unit->name)
156 return -ENOMEM;
158 LIST_APPEND(units, c->units, unit);
159 log_unit_debug(unit, "added from %s.", source);
160 TAKE_PTR(unit);
162 return 0;
165 static int context_parse_ntp_services_from_environment(Context *c) {
166 const char *env, *p;
167 int r;
169 assert(c);
171 env = getenv("SYSTEMD_TIMEDATED_NTP_SERVICES");
172 if (!env)
173 return 0;
175 log_debug("Using list of ntp services from environment variable $SYSTEMD_TIMEDATED_NTP_SERVICES=%s.", env);
177 for (p = env;;) {
178 _cleanup_free_ char *word = NULL;
180 r = extract_first_word(&p, &word, ":", 0);
181 if (r == 0)
182 break;
183 if (r == -ENOMEM)
184 return log_oom();
185 if (r < 0) {
186 log_error("Invalid syntax, ignoring: %s", env);
187 break;
190 r = context_add_ntp_service(c, word, "$SYSTEMD_TIMEDATED_NTP_SERVICES");
191 if (r < 0)
192 log_warning_errno(r, "Failed to add NTP service \"%s\", ignoring: %m", word);
195 return 1;
198 static int context_parse_ntp_services_from_disk(Context *c) {
199 _cleanup_strv_free_ char **files = NULL;
200 int r;
202 r = conf_files_list_strv(&files, ".list", NULL, CONF_FILES_FILTER_MASKED, UNIT_LIST_DIRS);
203 if (r < 0)
204 return log_error_errno(r, "Failed to enumerate .list files: %m");
206 STRV_FOREACH(f, files) {
207 _cleanup_fclose_ FILE *file = NULL;
209 log_debug("Reading file '%s'", *f);
211 r = fopen_unlocked(*f, "re", &file);
212 if (r < 0) {
213 log_error_errno(r, "Failed to open %s, ignoring: %m", *f);
214 continue;
217 for (;;) {
218 _cleanup_free_ char *line = NULL;
219 const char *word;
221 r = read_line(file, LINE_MAX, &line);
222 if (r < 0) {
223 log_error_errno(r, "Failed to read %s, ignoring: %m", *f);
224 continue;
226 if (r == 0)
227 break;
229 word = strstrip(line);
230 if (isempty(word) || startswith(word, "#"))
231 continue;
233 r = context_add_ntp_service(c, word, *f);
234 if (r < 0)
235 log_warning_errno(r, "Failed to add NTP service \"%s\", ignoring: %m", word);
239 return 1;
242 static int context_parse_ntp_services(Context *c) {
243 int r;
245 r = context_parse_ntp_services_from_environment(c);
246 if (r != 0)
247 return r;
249 return context_parse_ntp_services_from_disk(c);
252 static int context_ntp_service_is_active(Context *c) {
253 int count = 0;
255 assert(c);
257 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
259 LIST_FOREACH(units, info, c->units)
260 count += !STRPTR_IN_SET(info->active_state, "inactive", "failed");
262 return count;
265 static int context_ntp_service_exists(Context *c) {
266 int count = 0;
268 assert(c);
270 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
272 LIST_FOREACH(units, info, c->units)
273 count += streq_ptr(info->load_state, "loaded");
275 return count;
278 static int context_read_data(Context *c) {
279 _cleanup_free_ char *t = NULL;
280 int r;
282 assert(c);
284 r = get_timezone(&t);
285 if (r == -EINVAL)
286 log_warning_errno(r, "/etc/localtime should be a symbolic link to a time zone data file in /usr/share/zoneinfo/.");
287 else if (r < 0)
288 log_warning_errno(r, "Failed to get target of /etc/localtime: %m");
290 free_and_replace(c->zone, t);
292 c->local_rtc = clock_is_localtime(NULL) > 0;
294 return 0;
297 static int context_write_data_timezone(Context *c) {
298 _cleanup_free_ char *p = NULL;
299 const char *source;
301 assert(c);
303 /* No timezone is very similar to UTC. Hence in either of these cases link the UTC file in. Except if
304 * it isn't installed, in which case we remove the symlink altogether. Since glibc defaults to an
305 * internal version of UTC in that case behaviour is mostly equivalent. We still prefer creating the
306 * symlink though, since things are more self explanatory then. */
308 if (isempty(c->zone) || streq(c->zone, "UTC")) {
310 if (access("/usr/share/zoneinfo/UTC", F_OK) < 0) {
312 if (unlink("/etc/localtime") < 0 && errno != ENOENT)
313 return -errno;
315 return 0;
318 source = "../usr/share/zoneinfo/UTC";
319 } else {
320 p = path_join("../usr/share/zoneinfo", c->zone);
321 if (!p)
322 return -ENOMEM;
324 source = p;
327 return symlink_atomic(source, "/etc/localtime");
330 static int context_write_data_local_rtc(Context *c) {
331 _cleanup_free_ char *s = NULL, *w = NULL;
332 int r;
334 assert(c);
336 r = read_full_file("/etc/adjtime", &s, NULL);
337 if (r < 0) {
338 if (r != -ENOENT)
339 return r;
341 if (!c->local_rtc)
342 return 0;
344 w = strdup(NULL_ADJTIME_LOCAL);
345 if (!w)
346 return -ENOMEM;
347 } else {
348 char *p;
349 const char *e = "\n"; /* default if there is less than 3 lines */
350 const char *prepend = "";
351 size_t a, b;
353 p = strchrnul(s, '\n');
354 if (*p == '\0')
355 /* only one line, no \n terminator */
356 prepend = "\n0\n";
357 else if (p[1] == '\0') {
358 /* only one line, with \n terminator */
359 ++p;
360 prepend = "0\n";
361 } else {
362 p = strchr(p+1, '\n');
363 if (!p) {
364 /* only two lines, no \n terminator */
365 prepend = "\n";
366 p = s + strlen(s);
367 } else {
368 char *end;
369 /* third line might have a \n terminator or not */
370 p++;
371 end = strchr(p, '\n');
372 /* if we actually have a fourth line, use that as suffix "e", otherwise the default \n */
373 if (end)
374 e = end;
378 a = p - s;
379 b = strlen(e);
381 w = new(char, a + (c->local_rtc ? 5 : 3) + strlen(prepend) + b + 1);
382 if (!w)
383 return -ENOMEM;
385 *(char*) mempcpy(stpcpy(stpcpy(mempcpy(w, s, a), prepend), c->local_rtc ? "LOCAL" : "UTC"), e, b) = 0;
387 if (streq(w, NULL_ADJTIME_UTC)) {
388 if (unlink("/etc/adjtime") < 0)
389 if (errno != ENOENT)
390 return -errno;
392 return 0;
396 r = mac_init();
397 if (r < 0)
398 return r;
400 return write_string_file_atomic_label("/etc/adjtime", w);
403 static int context_update_ntp_status(Context *c, sd_bus *bus, sd_bus_message *m) {
404 static const struct bus_properties_map map[] = {
405 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
406 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state) },
407 { "UnitFileState", "s", NULL, offsetof(UnitStatusInfo, unit_file_state) },
410 int r;
412 assert(c);
413 assert(bus);
415 /* Suppress calling context_update_ntp_status() multiple times within single DBus transaction. */
416 if (m) {
417 if (m == c->cache)
418 return 0;
420 sd_bus_message_unref(c->cache);
421 c->cache = sd_bus_message_ref(m);
424 LIST_FOREACH(units, u, c->units) {
425 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
426 _cleanup_free_ char *path = NULL;
428 unit_status_info_clear(u);
430 path = unit_dbus_path_from_name(u->name);
431 if (!path)
432 return -ENOMEM;
434 r = bus_map_all_properties(
435 bus,
436 "org.freedesktop.systemd1",
437 path,
438 map,
439 BUS_MAP_STRDUP,
440 &error,
441 NULL,
443 if (r < 0)
444 return log_unit_error_errno(u, r, "Failed to get properties: %s", bus_error_message(&error, r));
447 return 0;
450 static int match_job_removed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
451 Context *c = ASSERT_PTR(userdata);
452 const char *path;
453 unsigned n = 0;
454 int r;
456 assert(m);
458 r = sd_bus_message_read(m, "uoss", NULL, &path, NULL, NULL);
459 if (r < 0) {
460 bus_log_parse_error(r);
461 return 0;
464 LIST_FOREACH(units, u, c->units)
465 if (streq_ptr(path, u->path))
466 u->path = mfree(u->path);
467 else
468 n += !!u->path;
470 if (n == 0) {
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",
475 NULL);
478 return 0;
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;
483 const char *path;
484 int r;
486 assert(u);
487 assert(bus);
488 assert(error);
490 r = bus_call_method(
491 bus,
492 bus_systemd_mgr,
493 start ? "StartUnit" : "StopUnit",
494 error,
495 &reply,
496 "ss",
497 u->name,
498 "replace");
499 log_unit_full_errno_zerook(u, r < 0 ? LOG_WARNING : LOG_DEBUG, r,
500 "%s unit: %m", start ? "Starting" : "Stopping");
501 if (r < 0)
502 return r;
504 r = sd_bus_message_read(reply, "o", &path);
505 if (r < 0)
506 return bus_log_parse_error(r);
508 r = free_and_strdup(&u->path, path);
509 if (r < 0)
510 return log_oom();
512 return 0;
515 static int unit_enable_or_disable(UnitStatusInfo *u, sd_bus *bus, sd_bus_error *error, bool enable) {
516 int r;
518 assert(u);
519 assert(bus);
520 assert(error);
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));
526 return 0;
529 log_unit_info(u, "%s unit.", enable ? "Enabling" : "Disabling");
531 if (enable)
532 r = bus_call_method(
533 bus,
534 bus_systemd_mgr,
535 "EnableUnitFiles",
536 error,
537 NULL,
538 "asbb", 1,
539 u->name,
540 false, true);
541 else
542 r = bus_call_method(
543 bus,
544 bus_systemd_mgr,
545 "DisableUnitFiles",
546 error,
547 NULL,
548 "asb", 1,
549 u->name,
550 false);
551 if (r < 0)
552 return r;
554 r = bus_service_manager_reload(bus);
555 if (r < 0)
556 return r;
558 return 0;
561 static bool ntp_synced(void) {
562 struct timex txc = {};
564 if (adjtimex(&txc) < 0)
565 return false;
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(
577 sd_bus *bus,
578 const char *path,
579 const char *interface,
580 const char *property,
581 sd_bus_message *reply,
582 void *userdata,
583 sd_bus_error *error) {
585 struct tm tm = {};
586 usec_t t = 0;
587 int r;
589 r = clock_get_hwclock(&tm);
590 if (r == -EBUSY)
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.");
594 else if (r < 0)
595 return sd_bus_error_set_errnof(error, r, "Failed to read RTC: %m");
596 else
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(
603 sd_bus *bus,
604 const char *path,
605 const char *interface,
606 const char *property,
607 sd_bus_message *reply,
608 void *userdata,
609 sd_bus_error *error) {
611 Context *c = ASSERT_PTR(userdata);
612 int r;
614 assert(bus);
615 assert(property);
616 assert(reply);
617 assert(error);
619 if (c->slot_job_removed)
620 /* When the previous request is not finished, then assume NTP is enabled. */
621 return sd_bus_message_append(reply, "b", true);
623 r = context_update_ntp_status(c, bus, reply);
624 if (r < 0)
625 return r;
627 return sd_bus_message_append(reply, "b", context_ntp_service_exists(c) > 0);
630 static int property_get_ntp(
631 sd_bus *bus,
632 const char *path,
633 const char *interface,
634 const char *property,
635 sd_bus_message *reply,
636 void *userdata,
637 sd_bus_error *error) {
639 Context *c = ASSERT_PTR(userdata);
640 int r;
642 assert(bus);
643 assert(property);
644 assert(reply);
645 assert(error);
647 if (c->slot_job_removed)
648 /* When the previous request is not finished, then assume NTP is active. */
649 return sd_bus_message_append(reply, "b", true);
651 r = context_update_ntp_status(c, bus, reply);
652 if (r < 0)
653 return r;
655 return sd_bus_message_append(reply, "b", context_ntp_service_is_active(c) > 0);
658 static int method_set_timezone(sd_bus_message *m, void *userdata, sd_bus_error *error) {
659 Context *c = ASSERT_PTR(userdata);
660 int interactive, r;
661 const char *z;
663 assert(m);
665 r = sd_bus_message_read(m, "sb", &z, &interactive);
666 if (r < 0)
667 return r;
669 if (!timezone_is_valid(z, LOG_DEBUG))
670 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid or not installed time zone '%s'", z);
672 if (streq_ptr(z, c->zone))
673 return sd_bus_reply_method_return(m, NULL);
675 r = bus_verify_polkit_async(
677 CAP_SYS_TIME,
678 "org.freedesktop.timedate1.set-timezone",
679 NULL,
680 interactive,
681 UID_INVALID,
682 &c->polkit_registry,
683 error);
684 if (r < 0)
685 return r;
686 if (r == 0)
687 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
689 r = free_and_strdup(&c->zone, z);
690 if (r < 0)
691 return r;
693 /* 1. Write new configuration file */
694 r = context_write_data_timezone(c);
695 if (r < 0) {
696 log_error_errno(r, "Failed to set time zone: %m");
697 return sd_bus_error_set_errnof(error, r, "Failed to set time zone: %m");
700 /* 2. Make glibc notice the new timezone */
701 tzset();
703 /* 3. Tell the kernel our timezone */
704 r = clock_set_timezone(NULL);
705 if (r < 0)
706 log_debug_errno(r, "Failed to tell kernel about timezone, ignoring: %m");
708 if (c->local_rtc) {
709 struct timespec ts;
710 struct tm tm;
712 /* 4. Sync RTC from system clock, with the new delta */
713 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
714 assert_se(localtime_r(&ts.tv_sec, &tm));
716 r = clock_set_hwclock(&tm);
717 if (r < 0)
718 log_debug_errno(r, "Failed to sync time to hardware clock, ignoring: %m");
721 log_struct(LOG_INFO,
722 "MESSAGE_ID=" SD_MESSAGE_TIMEZONE_CHANGE_STR,
723 "TIMEZONE=%s", c->zone,
724 "TIMEZONE_SHORTNAME=%s", tzname[daylight],
725 "DAYLIGHT=%i", daylight,
726 LOG_MESSAGE("Changed time zone to '%s' (%s).", c->zone, tzname[daylight]));
728 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m),
729 "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "Timezone",
730 NULL);
732 return sd_bus_reply_method_return(m, NULL);
735 static int method_set_local_rtc(sd_bus_message *m, void *userdata, sd_bus_error *error) {
736 int lrtc, fix_system, interactive;
737 Context *c = ASSERT_PTR(userdata);
738 struct timespec ts;
739 int r;
741 assert(m);
743 r = sd_bus_message_read(m, "bbb", &lrtc, &fix_system, &interactive);
744 if (r < 0)
745 return r;
747 if (lrtc == c->local_rtc && !fix_system)
748 return sd_bus_reply_method_return(m, NULL);
750 r = bus_verify_polkit_async(
752 CAP_SYS_TIME,
753 "org.freedesktop.timedate1.set-local-rtc",
754 NULL,
755 interactive,
756 UID_INVALID,
757 &c->polkit_registry,
758 error);
759 if (r < 0)
760 return r;
761 if (r == 0)
762 return 1;
764 if (lrtc != c->local_rtc) {
765 c->local_rtc = lrtc;
767 /* 1. Write new configuration file */
768 r = context_write_data_local_rtc(c);
769 if (r < 0) {
770 log_error_errno(r, "Failed to set RTC to %s: %m", lrtc ? "local" : "UTC");
771 return sd_bus_error_set_errnof(error, r, "Failed to set RTC to %s: %m", lrtc ? "local" : "UTC");
775 /* 2. Tell the kernel our timezone */
776 r = clock_set_timezone(NULL);
777 if (r < 0)
778 log_debug_errno(r, "Failed to tell kernel about timezone, ignoring: %m");
780 /* 3. Synchronize clocks */
781 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
783 if (fix_system) {
784 struct tm tm;
786 /* Sync system clock from RTC; first, initialize the timezone fields of struct tm. */
787 localtime_or_gmtime_r(&ts.tv_sec, &tm, !c->local_rtc);
789 /* Override the main fields of struct tm, but not the timezone fields */
790 r = clock_get_hwclock(&tm);
791 if (r < 0)
792 log_debug_errno(r, "Failed to get hardware clock, ignoring: %m");
793 else {
794 /* And set the system clock with this */
795 ts.tv_sec = mktime_or_timegm(&tm, !c->local_rtc);
797 if (clock_settime(CLOCK_REALTIME, &ts) < 0)
798 log_debug_errno(errno, "Failed to update system clock, ignoring: %m");
801 } else {
802 struct tm tm;
804 /* Sync RTC from system clock */
805 localtime_or_gmtime_r(&ts.tv_sec, &tm, !c->local_rtc);
807 r = clock_set_hwclock(&tm);
808 if (r < 0)
809 log_debug_errno(r, "Failed to sync time to hardware clock, ignoring: %m");
812 log_info("RTC configured to %s time.", c->local_rtc ? "local" : "UTC");
814 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m),
815 "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "LocalRTC",
816 NULL);
818 return sd_bus_reply_method_return(m, NULL);
821 static int method_set_time(sd_bus_message *m, void *userdata, sd_bus_error *error) {
822 sd_bus *bus = sd_bus_message_get_bus(m);
823 char buf[FORMAT_TIMESTAMP_MAX];
824 int relative, interactive, r;
825 Context *c = ASSERT_PTR(userdata);
826 int64_t utc;
827 struct timespec ts;
828 usec_t start;
829 struct tm tm;
831 assert(m);
833 if (c->slot_job_removed)
834 return sd_bus_error_set(error, BUS_ERROR_AUTOMATIC_TIME_SYNC_ENABLED, "Previous request is not finished, refusing.");
836 r = context_update_ntp_status(c, bus, m);
837 if (r < 0)
838 return sd_bus_error_set_errnof(error, r, "Failed to update context: %m");
840 if (context_ntp_service_is_active(c) > 0)
841 return sd_bus_error_set(error, BUS_ERROR_AUTOMATIC_TIME_SYNC_ENABLED, "Automatic time synchronization is enabled");
843 /* this only gets used if dbus does not provide a timestamp */
844 start = now(CLOCK_MONOTONIC);
846 r = sd_bus_message_read(m, "xbb", &utc, &relative, &interactive);
847 if (r < 0)
848 return r;
850 if (!relative && utc <= 0)
851 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid absolute time");
853 if (relative && utc == 0)
854 return sd_bus_reply_method_return(m, NULL);
856 if (relative) {
857 usec_t n, x;
859 n = now(CLOCK_REALTIME);
860 x = n + utc;
862 if ((utc > 0 && x < n) ||
863 (utc < 0 && x > n))
864 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Time value overflow");
866 timespec_store(&ts, x);
867 } else
868 timespec_store(&ts, (usec_t) utc);
870 r = bus_verify_polkit_async(
872 CAP_SYS_TIME,
873 "org.freedesktop.timedate1.set-time",
874 NULL,
875 interactive,
876 UID_INVALID,
877 &c->polkit_registry,
878 error);
879 if (r < 0)
880 return r;
881 if (r == 0)
882 return 1;
884 /* adjust ts for time spent in program */
885 r = sd_bus_message_get_monotonic_usec(m, &start);
886 /* when sd_bus_message_get_monotonic_usec() returns -ENODATA it does not modify &start */
887 if (r < 0 && r != -ENODATA)
888 return r;
890 timespec_store(&ts, timespec_load(&ts) + (now(CLOCK_MONOTONIC) - start));
892 /* Set system clock */
893 if (clock_settime(CLOCK_REALTIME, &ts) < 0) {
894 log_error_errno(errno, "Failed to set local time: %m");
895 return sd_bus_error_set_errnof(error, errno, "Failed to set local time: %m");
898 /* Sync down to RTC */
899 localtime_or_gmtime_r(&ts.tv_sec, &tm, !c->local_rtc);
901 r = clock_set_hwclock(&tm);
902 if (r < 0)
903 log_debug_errno(r, "Failed to update hardware clock, ignoring: %m");
905 log_struct(LOG_INFO,
906 "MESSAGE_ID=" SD_MESSAGE_TIME_CHANGE_STR,
907 "REALTIME="USEC_FMT, timespec_load(&ts),
908 LOG_MESSAGE("Changed local time to %s", strnull(format_timestamp(buf, sizeof(buf), timespec_load(&ts)))));
910 return sd_bus_reply_method_return(m, NULL);
913 static int method_set_ntp(sd_bus_message *m, void *userdata, sd_bus_error *error) {
914 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
915 sd_bus *bus = sd_bus_message_get_bus(m);
916 Context *c = ASSERT_PTR(userdata);
917 const UnitStatusInfo *selected = NULL;
918 int enable, interactive, q, r;
920 assert(m);
921 assert(bus);
923 r = sd_bus_message_read(m, "bb", &enable, &interactive);
924 if (r < 0)
925 return r;
927 r = context_update_ntp_status(c, bus, m);
928 if (r < 0)
929 return r;
931 if (context_ntp_service_exists(c) <= 0)
932 return sd_bus_error_set(error, BUS_ERROR_NO_NTP_SUPPORT, "NTP not supported");
934 r = bus_verify_polkit_async(
936 CAP_SYS_TIME,
937 "org.freedesktop.timedate1.set-ntp",
938 NULL,
939 interactive,
940 UID_INVALID,
941 &c->polkit_registry,
942 error);
943 if (r < 0)
944 return r;
945 if (r == 0)
946 return 1;
948 /* This method may be called frequently. Forget the previous job if it has not completed yet. */
949 LIST_FOREACH(units, u, c->units)
950 u->path = mfree(u->path);
952 if (!c->slot_job_removed) {
953 r = bus_match_signal_async(
954 bus,
955 &slot,
956 bus_systemd_mgr,
957 "JobRemoved",
958 match_job_removed, NULL, c);
959 if (r < 0)
960 return r;
963 if (enable)
964 LIST_FOREACH(units, u, c->units) {
965 bool enable_this_one = !selected;
967 if (!streq(u->load_state, "loaded"))
968 continue;
970 r = unit_enable_or_disable(u, bus, error, enable_this_one);
971 if (r < 0)
972 /* If enablement failed, don't start this unit. */
973 enable_this_one = false;
975 r = unit_start_or_stop(u, bus, error, enable_this_one);
976 if (r < 0)
977 log_unit_warning_errno(u, r, "Failed to %s %sd NTP unit, ignoring: %m",
978 enable_this_one ? "start" : "stop",
979 enable_disable(enable_this_one));
980 if (enable_this_one)
981 selected = u;
983 else
984 LIST_FOREACH(units, u, c->units) {
985 if (!streq(u->load_state, "loaded"))
986 continue;
988 q = unit_enable_or_disable(u, bus, error, false);
989 if (q < 0)
990 r = q;
992 q = unit_start_or_stop(u, bus, error, false);
993 if (q < 0)
994 r = q;
997 if (r < 0)
998 return r;
999 if (enable && !selected)
1000 return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "No NTP service found to enable.");
1002 if (slot)
1003 c->slot_job_removed = TAKE_PTR(slot);
1005 if (selected)
1006 log_info("Set NTP to enabled (%s).", selected->name);
1007 else
1008 log_info("Set NTP to disabled.");
1010 return sd_bus_reply_method_return(m, NULL);
1013 static int method_list_timezones(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1014 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1015 _cleanup_strv_free_ char **zones = NULL;
1016 int r;
1018 assert(m);
1020 r = get_timezones(&zones);
1021 if (r < 0)
1022 return sd_bus_error_set_errnof(error, r, "Failed to read list of time zones: %m");
1024 r = sd_bus_message_new_method_return(m, &reply);
1025 if (r < 0)
1026 return r;
1028 r = sd_bus_message_append_strv(reply, zones);
1029 if (r < 0)
1030 return r;
1032 return sd_bus_send(NULL, reply, NULL);
1035 static const sd_bus_vtable timedate_vtable[] = {
1036 SD_BUS_VTABLE_START(0),
1038 SD_BUS_PROPERTY("Timezone", "s", NULL, offsetof(Context, zone), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
1039 SD_BUS_PROPERTY("LocalRTC", "b", bus_property_get_bool, offsetof(Context, local_rtc), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
1040 SD_BUS_PROPERTY("CanNTP", "b", property_get_can_ntp, 0, 0),
1041 SD_BUS_PROPERTY("NTP", "b", property_get_ntp, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
1042 SD_BUS_PROPERTY("NTPSynchronized", "b", property_get_ntp_sync, 0, 0),
1043 SD_BUS_PROPERTY("TimeUSec", "t", property_get_time, 0, 0),
1044 SD_BUS_PROPERTY("RTCTimeUSec", "t", property_get_rtc_time, 0, 0),
1046 SD_BUS_METHOD_WITH_ARGS("SetTime",
1047 SD_BUS_ARGS("x", usec_utc, "b", relative, "b", interactive),
1048 SD_BUS_NO_RESULT,
1049 method_set_time,
1050 SD_BUS_VTABLE_UNPRIVILEGED),
1051 SD_BUS_METHOD_WITH_ARGS("SetTimezone",
1052 SD_BUS_ARGS("s", timezone, "b", interactive),
1053 SD_BUS_NO_RESULT,
1054 method_set_timezone,
1055 SD_BUS_VTABLE_UNPRIVILEGED),
1056 SD_BUS_METHOD_WITH_ARGS("SetLocalRTC",
1057 SD_BUS_ARGS("b", local_rtc, "b", fix_system, "b", interactive),
1058 SD_BUS_NO_RESULT,
1059 method_set_local_rtc,
1060 SD_BUS_VTABLE_UNPRIVILEGED),
1061 SD_BUS_METHOD_WITH_ARGS("SetNTP",
1062 SD_BUS_ARGS("b", use_ntp, "b", interactive),
1063 SD_BUS_NO_RESULT,
1064 method_set_ntp,
1065 SD_BUS_VTABLE_UNPRIVILEGED),
1066 SD_BUS_METHOD_WITH_ARGS("ListTimezones",
1067 SD_BUS_NO_ARGS,
1068 SD_BUS_RESULT("as", timezones),
1069 method_list_timezones,
1070 SD_BUS_VTABLE_UNPRIVILEGED),
1072 SD_BUS_VTABLE_END,
1075 const BusObjectImplementation manager_object = {
1076 "/org/freedesktop/timedate1",
1077 "org.freedesktop.timedate1",
1078 .vtables = BUS_VTABLES(timedate_vtable),
1081 static int connect_bus(Context *c, sd_event *event, sd_bus **_bus) {
1082 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1083 int r;
1085 assert(c);
1086 assert(event);
1087 assert(_bus);
1089 r = sd_bus_default_system(&bus);
1090 if (r < 0)
1091 return log_error_errno(r, "Failed to get system bus connection: %m");
1093 r = bus_add_implementation(bus, &manager_object, c);
1094 if (r < 0)
1095 return r;
1097 r = bus_log_control_api_register(bus);
1098 if (r < 0)
1099 return r;
1101 r = sd_bus_request_name_async(bus, NULL, "org.freedesktop.timedate1", 0, NULL, NULL);
1102 if (r < 0)
1103 return log_error_errno(r, "Failed to request name: %m");
1105 r = sd_bus_attach_event(bus, event, 0);
1106 if (r < 0)
1107 return log_error_errno(r, "Failed to attach bus to event loop: %m");
1109 *_bus = TAKE_PTR(bus);
1111 return 0;
1114 static int run(int argc, char *argv[]) {
1115 _cleanup_(context_clear) Context context = {};
1116 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1117 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1118 int r;
1120 log_setup();
1122 r = service_parse_argv("systemd-timedated.service",
1123 "Manage the system clock and timezone and NTP enablement.",
1124 BUS_IMPLEMENTATIONS(&manager_object,
1125 &log_control_object),
1126 argc, argv);
1127 if (r <= 0)
1128 return r;
1130 umask(0022);
1132 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, -1) >= 0);
1134 r = sd_event_default(&event);
1135 if (r < 0)
1136 return log_error_errno(r, "Failed to allocate event loop: %m");
1138 (void) sd_event_set_watchdog(event, true);
1140 r = sd_event_add_signal(event, NULL, SIGINT, NULL, NULL);
1141 if (r < 0)
1142 return log_error_errno(r, "Failed to install SIGINT handler: %m");
1144 r = sd_event_add_signal(event, NULL, SIGTERM, NULL, NULL);
1145 if (r < 0)
1146 return log_error_errno(r, "Failed to install SIGTERM handler: %m");
1148 r = connect_bus(&context, event, &bus);
1149 if (r < 0)
1150 return r;
1152 (void) sd_bus_negotiate_timestamp(bus, true);
1154 r = context_read_data(&context);
1155 if (r < 0)
1156 return log_error_errno(r, "Failed to read time zone data: %m");
1158 r = context_parse_ntp_services(&context);
1159 if (r < 0)
1160 return r;
1162 r = bus_event_loop_with_idle(event, bus, "org.freedesktop.timedate1", DEFAULT_EXIT_USEC, NULL, NULL);
1163 if (r < 0)
1164 return log_error_errno(r, "Failed to run event loop: %m");
1166 return 0;
1169 DEFINE_MAIN_FUNCTION(run);