Debian Codegraph @

src/timedate/timedated.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <stdlib.h>
4 #include <sys/stat.h>
5 #include <sys/timex.h>
6 #include <unistd.h>
7
8 #include "sd-bus.h"
9 #include "sd-event.h"
10 #include "sd-messages.h"
11
12 #include "alloc-util.h"
13 #include "bus-common-errors.h"
14 #include "bus-error.h"
15 #include "bus-get-properties.h"
16 #include "bus-locator.h"
17 #include "bus-log-control-api.h"
18 #include "bus-map-properties.h"
19 #include "bus-message-util.h"
20 #include "bus-object.h"
21 #include "bus-polkit.h"
22 #include "bus-unit-util.h"
23 #include "bus-util.h"
24 #include "clock-util.h"
25 #include "conf-files.h"
26 #include "constants.h"
27 #include "daemon-util.h"
28 #include "extract-word.h"
29 #include "fd-util.h"
30 #include "fileio.h"
31 #include "fs-util.h"
32 #include "hashmap.h"
33 #include "hwclock-util.h"
34 #include "label-util.h"
35 #include "list.h"
36 #include "log.h"
37 #include "log-context.h"
38 #include "main-func.h"
39 #include "memory-util.h"
40 #include "path-util.h"
41 #include "service-util.h"
42 #include "set.h"
43 #include "string-util.h"
44 #include "strv.h"
45 #include "time-util.h"
46 #include "unit-def.h"
47 #include "unit-name.h"
48
49 #define NULL_ADJTIME_UTC "0.0 0 0\n0\nUTC\n"
50 #define NULL_ADJTIME_LOCAL "0.0 0 0\n0\nLOCAL\n"
51
52 #define UNIT_LIST_DIRS (const char* const*) CONF_PATHS_STRV("systemd/ntp-units.d")
53 #define SET_NTP_IN_FLIGHT_MAX 16
54
55 typedef struct UnitStatusInfo {
56 char *name;
57 char *load_state;
58 char *unit_file_state;
59 char *active_state;
60 char *path;
61
62 LIST_FIELDS(struct UnitStatusInfo, units);
63 } UnitStatusInfo;
64
65 typedef struct Context {
66 char *zone;
67 bool local_rtc;
68 Hashmap *polkit_registry;
69 sd_bus_message *cache;
70 Set *set_ntp_calls;
71
72 sd_bus_slot *slot_job_removed;
73
74 LIST_HEAD(UnitStatusInfo, units);
75 } Context;
76
77 #define _LOG_CONTEXT_PUSH_UNIT(unit, u) \
78 const UnitStatusInfo *u = (unit); \
79 LOG_CONTEXT_PUSH_KEY_VALUE("UNIT=", u->name); \
80 LOG_SET_PREFIX(u->name)
81
82 #define LOG_CONTEXT_PUSH_UNIT(unit) \
83 _LOG_CONTEXT_PUSH_UNIT(unit, UNIQ_T(u, UNIQ))
84
85 static void unit_status_info_clear(UnitStatusInfo *p) {
86 assert(p);
87
88 p->load_state = mfree(p->load_state);
89 p->unit_file_state = mfree(p->unit_file_state);
90 p->active_state = mfree(p->active_state);
91 }
92
93 static UnitStatusInfo *unit_status_info_free(UnitStatusInfo *p) {
94 if (!p)
95 return NULL;
96
97 unit_status_info_clear(p);
98 free(p->name);
99 free(p->path);
100 return mfree(p);
101 }
102
103 DEFINE_TRIVIAL_CLEANUP_FUNC(UnitStatusInfo*, unit_status_info_free);
104
105 static void context_clear(Context *c) {
106 assert(c);
107
108 free(c->zone);
109 hashmap_free(c->polkit_registry);
110 sd_bus_message_unref(c->cache);
111 set_free(c->set_ntp_calls);
112
113 sd_bus_slot_unref(c->slot_job_removed);
114
115 LIST_CLEAR(units, c->units, unit_status_info_free);
116 }
117
118 static int context_add_ntp_service(Context *c, const char *s, const char *source) {
119 _cleanup_(unit_status_info_freep) UnitStatusInfo *unit = NULL;
120
121 assert(c);
122 assert(s);
123 assert(source);
124
125 if (!unit_name_is_valid(s, UNIT_NAME_PLAIN))
126 return -EINVAL;
127
128 /* Do not add this if it is already listed */
129 LIST_FOREACH(units, u, c->units)
130 if (streq(u->name, s))
131 return 0;
132
133 unit = new0(UnitStatusInfo, 1);
134 if (!unit)
135 return -ENOMEM;
136
137 unit->name = strdup(s);
138 if (!unit->name)
139 return -ENOMEM;
140
141 LOG_CONTEXT_PUSH_UNIT(unit);
142
143 LIST_APPEND(units, c->units, unit);
144 log_debug("added from %s.", source);
145 TAKE_PTR(unit);
146
147 return 0;
148 }
149
150 static int context_parse_ntp_services_from_environment(Context *c) {
151 const char *env, *p;
152 int r;
153
154 assert(c);
155
156 env = getenv("SYSTEMD_TIMEDATED_NTP_SERVICES");
157 if (!env)
158 return 0;
159
160 log_debug("Using list of ntp services from environment variable $SYSTEMD_TIMEDATED_NTP_SERVICES=%s.", env);
161
162 for (p = env;;) {
163 _cleanup_free_ char *word = NULL;
164
165 r = extract_first_word(&p, &word, ":", 0);
166 if (r == 0)
167 break;
168 if (r == -ENOMEM)
169 return log_oom();
170 if (r < 0) {
171 log_error("Invalid syntax, ignoring: %s", env);
172 break;
173 }
174
175 r = context_add_ntp_service(c, word, "$SYSTEMD_TIMEDATED_NTP_SERVICES");
176 if (r < 0)
177 log_warning_errno(r, "Failed to add NTP service \"%s\", ignoring: %m", word);
178 }
179
180 return 1;
181 }
182
183 static int context_parse_ntp_services_from_disk(Context *c) {
184 _cleanup_strv_free_ char **files = NULL;
185 int r;
186
187 r = conf_files_list_strv(&files, ".list", /* root= */ NULL,
188 CONF_FILES_FILTER_MASKED | CONF_FILES_WARN,
189 UNIT_LIST_DIRS);
190 if (r < 0)
191 return log_error_errno(r, "Failed to enumerate .list files: %m");
192
193 STRV_FOREACH(f, files) {
194 _cleanup_fclose_ FILE *file = NULL;
195
196 log_debug("Reading file '%s'", *f);
197
198 r = fopen_unlocked(*f, "re", &file);
199 if (r < 0) {
200 log_error_errno(r, "Failed to open %s, ignoring: %m", *f);
201 continue;
202 }
203
204 for (;;) {
205 _cleanup_free_ char *line = NULL;
206
207 r = read_stripped_line(file, LINE_MAX, &line);
208 if (r < 0) {
209 log_error_errno(r, "Failed to read %s, ignoring: %m", *f);
210 continue;
211 }
212 if (r == 0)
213 break;
214
215 if (isempty(line) || startswith(line, "#"))
216 continue;
217
218 r = context_add_ntp_service(c, line, *f);
219 if (r < 0)
220 log_warning_errno(r, "Failed to add NTP service \"%s\", ignoring: %m", line);
221 }
222 }
223
224 return 1;
225 }
226
227 static int context_parse_ntp_services(Context *c) {
228 int r;
229
230 r = context_parse_ntp_services_from_environment(c);
231 if (r != 0)
232 return r;
233
234 return context_parse_ntp_services_from_disk(c);
235 }
236
237 static int context_ntp_service_is_active(Context *c) {
238 int count = 0;
239
240 assert(c);
241
242 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
243
244 LIST_FOREACH(units, info, c->units)
245 count += !STRPTR_IN_SET(info->active_state, "inactive", "failed");
246
247 return count;
248 }
249
250 static int context_ntp_service_exists(Context *c) {
251 int count = 0;
252
253 assert(c);
254
255 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
256
257 LIST_FOREACH(units, info, c->units)
258 count += streq_ptr(info->load_state, "loaded");
259
260 return count;
261 }
262
263 static int context_read_data(Context *c) {
264 _cleanup_free_ char *t = NULL;
265 int r;
266
267 assert(c);
268
269 r = get_timezone(&t);
270 if (r == -EINVAL)
271 log_warning_errno(r, "/etc/localtime should be a symbolic link to a time zone data file in /usr/share/zoneinfo/.");
272 else if (r < 0)
273 log_warning_errno(r, "Failed to get target of /etc/localtime: %m");
274
275 free_and_replace(c->zone, t);
276
277 c->local_rtc = clock_is_localtime(NULL) > 0;
278
279 return 0;
280 }
281
282 static int context_write_data_timezone(Context *c) {
283 _cleanup_free_ char *p = NULL;
284 const char *source;
285
286 assert(c);
287
288 /* No timezone is very similar to UTC. Hence in either of these cases link the UTC file in. Except if
289 * it isn't installed, in which case we remove the symlink altogether. Since glibc defaults to an
290 * internal version of UTC in that case behaviour is mostly equivalent. We still prefer creating the
291 * symlink though, since things are more self explanatory then. */
292
293 if (isempty(c->zone) || streq(c->zone, "UTC")) {
294
295 if (access("/usr/share/zoneinfo/UTC", F_OK) < 0) {
296
297 if (unlink(etc_localtime()) < 0 && errno != ENOENT)
298 return -errno;
299
300 return 0;
301 }
302
303 source = "/usr/share/zoneinfo/UTC";
304 } else {
305 p = path_join("/usr/share/zoneinfo", c->zone);
306 if (!p)
307 return -ENOMEM;
308
309 source = p;
310 }
311
312 return symlinkat_atomic_full(source, AT_FDCWD, etc_localtime(),
313 !secure_getenv("SYSTEMD_ETC_LOCALTIME"));
314 }
315
316 static const char* etc_adjtime(void) {
317 static const char *cached = NULL;
318
319 if (!cached)
320 cached = secure_getenv("SYSTEMD_ETC_ADJTIME") ?: "/etc/adjtime";
321
322 return cached;
323 }
324
325 static int context_write_data_local_rtc(Context *c) {
326 _cleanup_free_ char *s = NULL, *w = NULL;
327 int r;
328
329 assert(c);
330
331 r = read_full_file(etc_adjtime(), &s, NULL);
332 if (r < 0) {
333 if (r != -ENOENT)
334 return r;
335
336 if (!c->local_rtc)
337 return 0;
338
339 w = strdup(NULL_ADJTIME_LOCAL);
340 if (!w)
341 return -ENOMEM;
342 } else {
343 char *p;
344 const char *e = "\n"; /* default if there is less than 3 lines */
345 const char *prepend = "";
346 size_t a, b;
347
348 p = strchrnul(s, '\n');
349 if (*p == '\0')
350 /* only one line, no \n terminator */
351 prepend = "\n0\n";
352 else if (p[1] == '\0') {
353 /* only one line, with \n terminator */
354 ++p;
355 prepend = "0\n";
356 } else {
357 p = strchr(p+1, '\n');
358 if (!p) {
359 /* only two lines, no \n terminator */
360 prepend = "\n";
361 p = s + strlen(s);
362 } else {
363 char *end;
364 /* third line might have a \n terminator or not */
365 p++;
366 end = strchr(p, '\n');
367 /* if we actually have a fourth line, use that as suffix "e", otherwise the default \n */
368 if (end)
369 e = end;
370 }
371 }
372
373 a = p - s;
374 b = strlen(e);
375
376 w = new(char, a + (c->local_rtc ? 5 : 3) + strlen(prepend) + b + 1);
377 if (!w)
378 return -ENOMEM;
379
380 *mempcpy_typesafe(stpcpy(stpcpy(mempcpy(w, s, a), prepend), c->local_rtc ? "LOCAL" : "UTC"), e, b) = 0;
381
382 if (streq(w, NULL_ADJTIME_UTC)) {
383 if (unlink(etc_adjtime()) < 0)
384 if (errno != ENOENT)
385 return -errno;
386
387 return 0;
388 }
389 }
390
391 r = mac_init();
392 if (r < 0)
393 return r;
394
395 return write_string_file(etc_adjtime(), w, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_LABEL);
396 }
397
398 static int context_update_ntp_status(Context *c, sd_bus *bus, sd_bus_message *m) {
399 static const struct bus_properties_map map[] = {
400 { "LoadState", "s", NULL, offsetof(UnitStatusInfo, load_state) },
401 { "ActiveState", "s", NULL, offsetof(UnitStatusInfo, active_state) },
402 { "UnitFileState", "s", NULL, offsetof(UnitStatusInfo, unit_file_state) },
403 {}
404 };
405 int r;
406
407 assert(c);
408 assert(bus);
409
410 /* Suppress calling context_update_ntp_status() multiple times within single DBus transaction. */
411 if (m) {
412 if (m == c->cache)
413 return 0;
414
415 sd_bus_message_unref(c->cache);
416 c->cache = sd_bus_message_ref(m);
417 }
418
419 LIST_FOREACH(units, u, c->units) {
420 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
421 _cleanup_free_ char *path = NULL;
422
423 LOG_CONTEXT_PUSH_UNIT(u);
424
425 unit_status_info_clear(u);
426
427 path = unit_dbus_path_from_name(u->name);
428 if (!path)
429 return -ENOMEM;
430
431 r = bus_map_all_properties(
432 bus,
433 "org.freedesktop.systemd1",
434 path,
435 map,
436 BUS_MAP_STRDUP,
437 &error,
438 NULL,
439 u);
440 if (r < 0)
441 return log_error_errno(r, "Failed to get properties: %s", bus_error_message(&error, r));
442 }
443
444 return 0;
445 }
446
447 static int match_job_removed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
448 Context *c = ASSERT_PTR(userdata);
449 const char *path;
450 unsigned n = 0;
451 int r;
452
453 assert(m);
454
455 r = sd_bus_message_read(m, "uoss", NULL, &path, NULL, NULL);
456 if (r < 0) {
457 bus_log_parse_error(r);
458 return 0;
459 }
460
461 LIST_FOREACH(units, u, c->units)
462 if (streq_ptr(path, u->path))
463 u->path = mfree(u->path);
464 else
465 n += !!u->path;
466
467 if (n == 0) {
468 sd_bus_message *cm;
469
470 c->slot_job_removed = sd_bus_slot_unref(c->slot_job_removed);
471
472 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m),
473 "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "NTP",
474 NULL);
475 while ((cm = set_steal_first(c->set_ntp_calls))) {
476 r = sd_bus_reply_method_return(cm, NULL);
477 if (r < 0)
478 log_debug_errno(r, "Failed to reply to SetNTP method call, ignoring: %m");
479 sd_bus_message_unref(cm);
480 }
481 }
482
483 return 0;
484 }
485
486 static int unit_start_or_stop(UnitStatusInfo *u, sd_bus *bus, sd_bus_error *error, bool start) {
487 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
488 const char *path;
489 int r;
490
491 assert(u);
492 assert(bus);
493 assert(error);
494
495 LOG_CONTEXT_PUSH_UNIT(u);
496
497 r = bus_call_method(
498 bus,
499 bus_systemd_mgr,
500 start ? "StartUnit" : "StopUnit",
501 error,
502 &reply,
503 "ss",
504 u->name,
505 "replace");
506 log_full_errno_zerook(r < 0 ? LOG_WARNING : LOG_DEBUG, r,
507 "%s unit: %m", start ? "Starting" : "Stopping");
508 if (r < 0)
509 return r;
510
511 r = sd_bus_message_read(reply, "o", &path);
512 if (r < 0)
513 return bus_log_parse_error(r);
514
515 r = free_and_strdup(&u->path, path);
516 if (r < 0)
517 return log_oom();
518
519 return 0;
520 }
521
522 static int unit_enable_or_disable(UnitStatusInfo *u, sd_bus *bus, sd_bus_error *error, bool enable) {
523 int r;
524
525 assert(u);
526 assert(bus);
527 assert(error);
528
529 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
530
531 LOG_CONTEXT_PUSH_UNIT(u);
532
533 if (streq(u->unit_file_state, "enabled") == enable) {
534 log_debug("already %sd.", enable_disable(enable));
535 return 0;
536 }
537
538 log_info("%s unit.", enable ? "Enabling" : "Disabling");
539
540 if (enable)
541 r = bus_call_method(
542 bus,
543 bus_systemd_mgr,
544 "EnableUnitFiles",
545 error,
546 NULL,
547 "asbb", 1,
548 u->name,
549 false, true);
550 else
551 r = bus_call_method(
552 bus,
553 bus_systemd_mgr,
554 "DisableUnitFiles",
555 error,
556 NULL,
557 "asb", 1,
558 u->name,
559 false);
560 if (r < 0)
561 return r;
562
563 r = bus_service_manager_reload(bus);
564 if (r < 0)
565 return r;
566
567 return 0;
568 }
569
570 static bool ntp_synced(void) {
571 struct timex txc = {};
572
573 if (adjtimex(&txc) < 0)
574 return false;
575
576 /* Consider the system clock synchronized if the reported maximum error is smaller than the maximum
577 * value (16 seconds). Ignore the STA_UNSYNC flag as it may have been set to prevent the kernel from
578 * touching the RTC. */
579 return txc.maxerror < 16000000;
580 }
581
582 static BUS_DEFINE_PROPERTY_GET_GLOBAL(property_get_time, "t", now(CLOCK_REALTIME));
583 static BUS_DEFINE_PROPERTY_GET_GLOBAL(property_get_ntp_sync, "b", ntp_synced());
584
585 static int property_get_rtc_time(
586 sd_bus *bus,
587 const char *path,
588 const char *interface,
589 const char *property,
590 sd_bus_message *reply,
591 void *userdata,
592 sd_bus_error *error) {
593
594 struct tm tm = {};
595 usec_t t = 0;
596 int r;
597
598 r = hwclock_get(&tm);
599 if (r == -EBUSY)
600 log_warning("/dev/rtc is busy. Is somebody keeping it open continuously? That's not a good idea... Returning a bogus RTC timestamp.");
601 else if (r == -ENOENT)
602 log_debug("/dev/rtc not found.");
603 else if (r == -ENODATA)
604 log_debug("/dev/rtc has no valid time, power loss probably occurred?");
605 else if (r < 0)
606 return sd_bus_error_set_errnof(error, r, "Failed to read RTC: %m");
607 else {
608 r = mktime_or_timegm_usec(&tm, /* utc= */ true, &t);
609 if (r < 0)
610 log_warning_errno(r, "Failed to convert RTC time to UNIX time, ignoring: %m");
611 }
612
613 return sd_bus_message_append(reply, "t", t);
614 }
615
616 static int property_get_can_ntp(
617 sd_bus *bus,
618 const char *path,
619 const char *interface,
620 const char *property,
621 sd_bus_message *reply,
622 void *userdata,
623 sd_bus_error *error) {
624
625 Context *c = ASSERT_PTR(userdata);
626 int r;
627
628 assert(bus);
629 assert(property);
630 assert(reply);
631 assert(error);
632
633 if (c->slot_job_removed)
634 /* When the previous request is not finished, then assume NTP is enabled. */
635 return sd_bus_message_append(reply, "b", true);
636
637 r = context_update_ntp_status(c, bus, reply);
638 if (r < 0)
639 return r;
640
641 return sd_bus_message_append(reply, "b", context_ntp_service_exists(c) > 0);
642 }
643
644 static int property_get_ntp(
645 sd_bus *bus,
646 const char *path,
647 const char *interface,
648 const char *property,
649 sd_bus_message *reply,
650 void *userdata,
651 sd_bus_error *error) {
652
653 Context *c = ASSERT_PTR(userdata);
654 int r;
655
656 assert(bus);
657 assert(property);
658 assert(reply);
659 assert(error);
660
661 if (c->slot_job_removed)
662 /* When the previous request is not finished, then assume NTP is active. */
663 return sd_bus_message_append(reply, "b", true);
664
665 r = context_update_ntp_status(c, bus, reply);
666 if (r < 0)
667 return r;
668
669 return sd_bus_message_append(reply, "b", context_ntp_service_is_active(c) > 0);
670 }
671
672 static int method_set_timezone(sd_bus_message *m, void *userdata, sd_bus_error *error) {
673 Context *c = ASSERT_PTR(userdata);
674 int interactive, r;
675 const char *z;
676
677 assert(m);
678
679 r = sd_bus_message_read(m, "sb", &z, &interactive);
680 if (r < 0)
681 return r;
682
683 if (!timezone_is_valid(z, LOG_DEBUG))
684 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid or not installed time zone '%s'", z);
685
686 if (streq_ptr(z, c->zone))
687 return sd_bus_reply_method_return(m, NULL);
688
689 r = bus_verify_polkit_async_full(
690 m,
691 "org.freedesktop.timedate1.set-timezone",
692 /* details= */ NULL,
693 /* good_user= */ UID_INVALID,
694 interactive ? POLKIT_ALLOW_INTERACTIVE : 0,
695 &c->polkit_registry,
696 error);
697 if (r < 0)
698 return r;
699 if (r == 0)
700 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
701
702 r = free_and_strdup(&c->zone, z);
703 if (r < 0)
704 return r;
705
706 /* 1. Write new configuration file */
707 r = context_write_data_timezone(c);
708 if (r < 0) {
709 log_error_errno(r, "Failed to set time zone: %m");
710 return sd_bus_error_set_errnof(error, r, "Failed to set time zone: %m");
711 }
712
713 /* 2. Make glibc notice the new timezone */
714 tzset();
715
716 /* 3. Tell the kernel our timezone */
717 r = clock_set_timezone(NULL);
718 if (r < 0)
719 log_debug_errno(r, "Failed to tell kernel about timezone, ignoring: %m");
720
721 if (c->local_rtc) {
722 struct tm tm;
723
724 /* 4. Sync RTC from system clock, with the new delta */
725 r = localtime_or_gmtime_usec(now(CLOCK_REALTIME), /* utc= */ false, &tm);
726 if (r < 0)
727 log_debug_errno(r, "Failed to convert system time to calendar time, ignoring: %m");
728 else {
729 r = hwclock_set(&tm);
730 if (r < 0)
731 log_debug_errno(r, "Failed to sync time to hardware clock, ignoring: %m");
732 }
733 }
734
735 log_struct(LOG_INFO,
736 LOG_MESSAGE_ID(SD_MESSAGE_TIMEZONE_CHANGE_STR),
737 LOG_ITEM("TIMEZONE=%s", c->zone),
738 LOG_ITEM("TIMEZONE_SHORTNAME=%s", get_tzname(daylight)),
739 LOG_ITEM("DAYLIGHT=%i", daylight),
740 LOG_MESSAGE("Changed time zone to '%s' (%s).", c->zone, get_tzname(daylight)));
741
742 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m),
743 "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "Timezone",
744 NULL);
745
746 return sd_bus_reply_method_return(m, NULL);
747 }
748
749 static int method_set_local_rtc(sd_bus_message *m, void *userdata, sd_bus_error *error) {
750 int lrtc, fix_system, interactive;
751 Context *c = ASSERT_PTR(userdata);
752 struct timespec ts;
753 int r;
754
755 assert(m);
756
757 r = sd_bus_message_read(m, "bbb", &lrtc, &fix_system, &interactive);
758 if (r < 0)
759 return r;
760
761 if (lrtc == c->local_rtc && !fix_system)
762 return sd_bus_reply_method_return(m, NULL);
763
764 r = bus_verify_polkit_async_full(
765 m,
766 "org.freedesktop.timedate1.set-local-rtc",
767 /* details= */ NULL,
768 /* good_user= */ UID_INVALID,
769 interactive ? POLKIT_ALLOW_INTERACTIVE : 0,
770 &c->polkit_registry,
771 error);
772 if (r < 0)
773 return r;
774 if (r == 0)
775 return 1;
776
777 if (lrtc != c->local_rtc) {
778 c->local_rtc = lrtc;
779
780 /* 1. Write new configuration file */
781 r = context_write_data_local_rtc(c);
782 if (r < 0) {
783 log_error_errno(r, "Failed to set RTC to %s: %m", lrtc ? "local" : "UTC");
784 return sd_bus_error_set_errnof(error, r, "Failed to set RTC to %s: %m", lrtc ? "local" : "UTC");
785 }
786 }
787
788 /* 2. Tell the kernel our timezone */
789 r = clock_set_timezone(NULL);
790 if (r < 0)
791 log_debug_errno(r, "Failed to tell kernel about timezone, ignoring: %m");
792
793 /* 3. Synchronize clocks */
794 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
795
796 if (fix_system) {
797 struct tm tm = {
798 .tm_isdst = -1,
799 };
800
801 /* Sync system clock from RTC; first, initialize the timezone fields of struct tm. */
802 r = localtime_or_gmtime_usec(timespec_load(&ts), !c->local_rtc, &tm);
803 if (r < 0)
804 log_debug_errno(r, "Failed to determine current timezone, ignoring: %m");
805
806 /* Override the main fields of struct tm, but not the timezone fields */
807 r = hwclock_get(&tm);
808 if (r < 0)
809 log_debug_errno(r, "Failed to get hardware clock, ignoring: %m");
810 else {
811 usec_t t;
812 /* And set the system clock with this */
813
814 r = mktime_or_timegm_usec(&tm, !c->local_rtc, &t);
815 if (r < 0)
816 log_debug_errno(r, "Failed to convert calendar time to system time, ignoring: %m");
817 else {
818 /* We leave the subsecond offset as is! */
819 ts.tv_sec = t / USEC_PER_SEC;
820
821 if (clock_settime(CLOCK_REALTIME, &ts) < 0)
822 log_debug_errno(errno, "Failed to update system clock, ignoring: %m");
823 }
824 }
825 } else {
826 struct tm tm;
827
828 /* Sync RTC from system clock */
829 r = localtime_or_gmtime_usec(timespec_load(&ts), !c->local_rtc, &tm);
830 if (r < 0)
831 log_debug_errno(r, "Failed to convert time to calendar time, ignoring: %m");
832 else {
833 r = hwclock_set(&tm);
834 if (r < 0)
835 log_debug_errno(r, "Failed to sync time to hardware clock, ignoring: %m");
836 }
837 }
838
839 log_info("RTC configured to %s time.", c->local_rtc ? "local" : "UTC");
840
841 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m),
842 "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "LocalRTC",
843 NULL);
844
845 return sd_bus_reply_method_return(m, NULL);
846 }
847
848 static int method_set_time(sd_bus_message *m, void *userdata, sd_bus_error *error) {
849 sd_bus *bus = sd_bus_message_get_bus(m);
850 int relative, interactive, r;
851 Context *c = ASSERT_PTR(userdata);
852 int64_t utc;
853 struct timespec ts;
854 usec_t start;
855 struct tm tm;
856
857 assert(m);
858
859 if (c->slot_job_removed)
860 return sd_bus_error_set(error, BUS_ERROR_AUTOMATIC_TIME_SYNC_ENABLED, "Previous request is not finished, refusing.");
861
862 r = context_update_ntp_status(c, bus, m);
863 if (r < 0)
864 return sd_bus_error_set_errnof(error, r, "Failed to update context: %m");
865
866 if (context_ntp_service_is_active(c) > 0)
867 return sd_bus_error_set(error, BUS_ERROR_AUTOMATIC_TIME_SYNC_ENABLED, "Automatic time synchronization is enabled");
868
869 /* this only gets used if dbus does not provide a timestamp */
870 start = now(CLOCK_MONOTONIC);
871
872 r = sd_bus_message_read(m, "xbb", &utc, &relative, &interactive);
873 if (r < 0)
874 return r;
875
876 if (!relative && utc <= 0)
877 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid absolute time");
878
879 if (relative && utc == 0)
880 return sd_bus_reply_method_return(m, NULL);
881
882 if (relative) {
883 usec_t n = now(CLOCK_REALTIME);
884 bool valid;
885 if (utc > 0)
886 valid = INC_SAFE(&n, (usec_t) utc);
887 else
888 valid = DEC_SAFE(&n, (usec_t) -utc);
889 if (!valid)
890 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Time value overflow");
891
892 timespec_store(&ts, n);
893 } else
894 timespec_store(&ts, (usec_t) utc);
895
896 /* refuse the request when the time is before systemd build date time */
897 if (ts.tv_sec < TIME_EPOCH)
898 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Requested to set the clock to time before build time, refusing.");
899
900 r = bus_verify_polkit_async_full(
901 m,
902 "org.freedesktop.timedate1.set-time",
903 /* details= */ NULL,
904 /* good_user= */ UID_INVALID,
905 interactive ? POLKIT_ALLOW_INTERACTIVE : 0,
906 &c->polkit_registry,
907 error);
908 if (r < 0)
909 return r;
910 if (r == 0)
911 return 1;
912
913 /* adjust ts for time spent in program */
914 r = sd_bus_message_get_monotonic_usec(m, &start);
915 /* when sd_bus_message_get_monotonic_usec() returns -ENODATA it does not modify &start */
916 if (r < 0 && r != -ENODATA)
917 return r;
918
919 timespec_store(&ts, timespec_load(&ts) + usec_sub_unsigned(now(CLOCK_MONOTONIC), start));
920
921 /* Set system clock */
922 if (clock_settime(CLOCK_REALTIME, &ts) < 0) {
923 log_error_errno(errno, "Failed to set local time: %m");
924 return sd_bus_error_set_errnof(error, errno, "Failed to set local time: %m");
925 }
926
927 /* Sync down to RTC */
928 r = localtime_or_gmtime_usec(timespec_load(&ts), !c->local_rtc, &tm);
929 if (r < 0)
930 log_debug_errno(r, "Failed to convert timestamp to calendar time, ignoring: %m");
931 else {
932 r = hwclock_set(&tm);
933 if (r < 0)
934 log_debug_errno(r, "Failed to update hardware clock, ignoring: %m");
935 }
936
937 log_struct(LOG_INFO,
938 LOG_MESSAGE_ID(SD_MESSAGE_TIME_CHANGE_STR),
939 LOG_ITEM("REALTIME="USEC_FMT, timespec_load(&ts)),
940 LOG_MESSAGE("Changed local time to %s", strnull(FORMAT_TIMESTAMP(timespec_load(&ts)))));
941
942 return sd_bus_reply_method_return(m, NULL);
943 }
944
945 static int method_set_ntp(sd_bus_message *m, void *userdata, sd_bus_error *error) {
946 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
947 sd_bus *bus = sd_bus_message_get_bus(m);
948 Context *c = ASSERT_PTR(userdata);
949 const UnitStatusInfo *selected = NULL;
950 int enable, interactive, q, r;
951
952 assert(m);
953 assert(bus);
954
955 r = sd_bus_message_read(m, "bb", &enable, &interactive);
956 if (r < 0)
957 return r;
958
959 r = context_update_ntp_status(c, bus, m);
960 if (r < 0)
961 return r;
962
963 if (context_ntp_service_exists(c) <= 0)
964 return sd_bus_error_set(error, BUS_ERROR_NO_NTP_SUPPORT, "NTP not supported");
965
966 r = bus_verify_polkit_async_full(
967 m,
968 "org.freedesktop.timedate1.set-ntp",
969 /* details= */ NULL,
970 /* good_user= */ UID_INVALID,
971 interactive ? POLKIT_ALLOW_INTERACTIVE : 0,
972 &c->polkit_registry,
973 error);
974 if (r < 0)
975 return r;
976 if (r == 0)
977 return 1;
978
979 /* This method may be called frequently. Forget the previous job if it has not completed yet. */
980 LIST_FOREACH(units, u, c->units)
981 u->path = mfree(u->path);
982
983 if (set_size(c->set_ntp_calls) >= SET_NTP_IN_FLIGHT_MAX)
984 return sd_bus_error_set_errnof(error, EAGAIN, "Too many calls in flight.");
985
986 if (!c->slot_job_removed) {
987 r = bus_match_signal_async(
988 bus,
989 &slot,
990 bus_systemd_mgr,
991 "JobRemoved",
992 match_job_removed, NULL, c);
993 if (r < 0)
994 return r;
995 }
996
997 if (enable)
998 LIST_FOREACH(units, u, c->units) {
999 bool enable_this_one = !selected;
1000
1001 if (!streq(u->load_state, "loaded"))
1002 continue;
1003
1004 LOG_CONTEXT_PUSH_UNIT(u);
1005
1006 r = unit_enable_or_disable(u, bus, error, enable_this_one);
1007 if (r < 0)
1008 /* If enablement failed, don't start this unit. */
1009 enable_this_one = false;
1010
1011 r = unit_start_or_stop(u, bus, error, enable_this_one);
1012 if (r < 0)
1013 log_warning_errno(r, "Failed to %s %sd NTP unit, ignoring: %m",
1014 enable_this_one ? "start" : "stop",
1015 enable_disable(enable_this_one));
1016 if (enable_this_one)
1017 selected = u;
1018 }
1019 else
1020 LIST_FOREACH(units, u, c->units) {
1021 if (!streq(u->load_state, "loaded"))
1022 continue;
1023
1024 q = unit_enable_or_disable(u, bus, error, false);
1025 if (q < 0)
1026 r = q;
1027
1028 q = unit_start_or_stop(u, bus, error, false);
1029 if (q < 0)
1030 r = q;
1031 }
1032
1033 if (r < 0)
1034 return r;
1035 if (enable && !selected)
1036 return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "No NTP service found to enable.");
1037
1038 if (slot)
1039 c->slot_job_removed = TAKE_PTR(slot);
1040
1041 if (selected)
1042 log_info("Set NTP to be enabled (%s).", selected->name);
1043 else
1044 log_info("Set NTP to be disabled.");
1045
1046 /* Asynchronous reply to m in match_job_removed() */
1047 return set_ensure_consume(&c->set_ntp_calls, &bus_message_hash_ops, sd_bus_message_ref(m));
1048 }
1049
1050 static int method_list_timezones(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1051 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1052 _cleanup_strv_free_ char **zones = NULL;
1053 int r;
1054
1055 assert(m);
1056
1057 r = get_timezones(&zones);
1058 if (r < 0)
1059 return sd_bus_error_set_errnof(error, r, "Failed to read list of time zones: %m");
1060
1061 r = sd_bus_message_new_method_return(m, &reply);
1062 if (r < 0)
1063 return r;
1064
1065 r = sd_bus_message_append_strv(reply, zones);
1066 if (r < 0)
1067 return r;
1068
1069 return sd_bus_message_send(reply);
1070 }
1071
1072 static const sd_bus_vtable timedate_vtable[] = {
1073 SD_BUS_VTABLE_START(0),
1074
1075 SD_BUS_PROPERTY("Timezone", "s", NULL, offsetof(Context, zone), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
1076 SD_BUS_PROPERTY("LocalRTC", "b", bus_property_get_bool, offsetof(Context, local_rtc), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
1077 SD_BUS_PROPERTY("CanNTP", "b", property_get_can_ntp, 0, 0),
1078 SD_BUS_PROPERTY("NTP", "b", property_get_ntp, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
1079 SD_BUS_PROPERTY("NTPSynchronized", "b", property_get_ntp_sync, 0, 0),
1080 SD_BUS_PROPERTY("TimeUSec", "t", property_get_time, 0, 0),
1081 SD_BUS_PROPERTY("RTCTimeUSec", "t", property_get_rtc_time, 0, 0),
1082
1083 SD_BUS_METHOD_WITH_ARGS("SetTime",
1084 SD_BUS_ARGS("x", usec_utc, "b", relative, "b", interactive),
1085 SD_BUS_NO_RESULT,
1086 method_set_time,
1087 SD_BUS_VTABLE_UNPRIVILEGED),
1088 SD_BUS_METHOD_WITH_ARGS("SetTimezone",
1089 SD_BUS_ARGS("s", timezone, "b", interactive),
1090 SD_BUS_NO_RESULT,
1091 method_set_timezone,
1092 SD_BUS_VTABLE_UNPRIVILEGED),
1093 SD_BUS_METHOD_WITH_ARGS("SetLocalRTC",
1094 SD_BUS_ARGS("b", local_rtc, "b", fix_system, "b", interactive),
1095 SD_BUS_NO_RESULT,
1096 method_set_local_rtc,
1097 SD_BUS_VTABLE_UNPRIVILEGED),
1098 SD_BUS_METHOD_WITH_ARGS("SetNTP",
1099 SD_BUS_ARGS("b", use_ntp, "b", interactive),
1100 SD_BUS_NO_RESULT,
1101 method_set_ntp,
1102 SD_BUS_VTABLE_UNPRIVILEGED),
1103 SD_BUS_METHOD_WITH_ARGS("ListTimezones",
1104 SD_BUS_NO_ARGS,
1105 SD_BUS_RESULT("as", timezones),
1106 method_list_timezones,
1107 SD_BUS_VTABLE_UNPRIVILEGED),
1108
1109 SD_BUS_VTABLE_END,
1110 };
1111
1112 static const BusObjectImplementation manager_object = {
1113 "/org/freedesktop/timedate1",
1114 "org.freedesktop.timedate1",
1115 .vtables = BUS_VTABLES(timedate_vtable),
1116 };
1117
1118 static int connect_bus(Context *c, sd_event *event, sd_bus **_bus) {
1119 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1120 int r;
1121
1122 assert(c);
1123 assert(event);
1124 assert(_bus);
1125
1126 r = sd_bus_default_system(&bus);
1127 if (r < 0)
1128 return log_error_errno(r, "Failed to get system bus connection: %m");
1129
1130 r = bus_add_implementation(bus, &manager_object, c);
1131 if (r < 0)
1132 return r;
1133
1134 r = bus_log_control_api_register(bus);
1135 if (r < 0)
1136 return r;
1137
1138 r = sd_bus_request_name_async(bus, NULL, "org.freedesktop.timedate1", 0, NULL, NULL);
1139 if (r < 0)
1140 return log_error_errno(r, "Failed to request name: %m");
1141
1142 r = sd_bus_attach_event(bus, event, 0);
1143 if (r < 0)
1144 return log_error_errno(r, "Failed to attach bus to event loop: %m");
1145
1146 *_bus = TAKE_PTR(bus);
1147
1148 return 0;
1149 }
1150
1151 static bool context_check_idle(void *userdata) {
1152 Context *c = ASSERT_PTR(userdata);
1153
1154 return hashmap_isempty(c->polkit_registry);
1155 }
1156
1157 static int run(int argc, char *argv[]) {
1158 _cleanup_(context_clear) Context context = {};
1159 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1160 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1161 int r;
1162
1163 log_setup();
1164
1165 r = service_parse_argv("systemd-timedated.service",
1166 "Manage the system clock and timezone and NTP enablement.",
1167 BUS_IMPLEMENTATIONS(&manager_object,
1168 &log_control_object),
1169 /* runtime_scope= */ NULL,
1170 argc, argv);
1171 if (r <= 0)
1172 return r;
1173
1174 umask(0022);
1175
1176 r = sd_event_default(&event);
1177 if (r < 0)
1178 return log_error_errno(r, "Failed to allocate event loop: %m");
1179
1180 (void) sd_event_set_watchdog(event, true);
1181
1182 r = sd_event_set_signal_exit(event, true);
1183 if (r < 0)
1184 return log_error_errno(r, "Failed to install SIGINT/SIGTERM handlers: %m");
1185
1186 r = connect_bus(&context, event, &bus);
1187 if (r < 0)
1188 return r;
1189
1190 (void) sd_bus_negotiate_timestamp(bus, true);
1191
1192 r = context_read_data(&context);
1193 if (r < 0)
1194 return log_error_errno(r, "Failed to read time zone data: %m");
1195
1196 r = context_parse_ntp_services(&context);
1197 if (r < 0)
1198 return r;
1199
1200 r = sd_notify(false, NOTIFY_READY_MESSAGE);
1201 if (r < 0)
1202 log_warning_errno(r, "Failed to send readiness notification, ignoring: %m");
1203
1204 r = bus_event_loop_with_idle(
1205 event,
1206 bus,
1207 "org.freedesktop.timedate1",
1208 DEFAULT_EXIT_USEC,
1209 context_check_idle,
1210 &context);
1211 if (r < 0)
1212 return log_error_errno(r, "Failed to run event loop: %m");
1213
1214 return 0;
1215 }
1216
1217 DEFINE_MAIN_FUNCTION(run);