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