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