]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/timedate/timedated.c
Merge pull request #29525 from poettering/confext-sysext-multimodal
[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 const char *word;
215
216 r = read_line(file, LINE_MAX, &line);
217 if (r < 0) {
218 log_error_errno(r, "Failed to read %s, ignoring: %m", *f);
219 continue;
220 }
221 if (r == 0)
222 break;
223
224 word = strstrip(line);
225 if (isempty(word) || startswith(word, "#"))
226 continue;
227
228 r = context_add_ntp_service(c, word, *f);
229 if (r < 0)
230 log_warning_errno(r, "Failed to add NTP service \"%s\", ignoring: %m", word);
231 }
232 }
233
234 return 1;
235 }
236
237 static int context_parse_ntp_services(Context *c) {
238 int r;
239
240 r = context_parse_ntp_services_from_environment(c);
241 if (r != 0)
242 return r;
243
244 return context_parse_ntp_services_from_disk(c);
245 }
246
247 static int context_ntp_service_is_active(Context *c) {
248 int count = 0;
249
250 assert(c);
251
252 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
253
254 LIST_FOREACH(units, info, c->units)
255 count += !STRPTR_IN_SET(info->active_state, "inactive", "failed");
256
257 return count;
258 }
259
260 static int context_ntp_service_exists(Context *c) {
261 int count = 0;
262
263 assert(c);
264
265 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
266
267 LIST_FOREACH(units, info, c->units)
268 count += streq_ptr(info->load_state, "loaded");
269
270 return count;
271 }
272
273 static int context_read_data(Context *c) {
274 _cleanup_free_ char *t = NULL;
275 int r;
276
277 assert(c);
278
279 r = get_timezone(&t);
280 if (r == -EINVAL)
281 log_warning_errno(r, "/etc/localtime should be a symbolic link to a time zone data file in /usr/share/zoneinfo/.");
282 else if (r < 0)
283 log_warning_errno(r, "Failed to get target of /etc/localtime: %m");
284
285 free_and_replace(c->zone, t);
286
287 c->local_rtc = clock_is_localtime(NULL) > 0;
288
289 return 0;
290 }
291
292 static int context_write_data_timezone(Context *c) {
293 _cleanup_free_ char *p = NULL;
294 const char *source;
295
296 assert(c);
297
298 /* No timezone is very similar to UTC. Hence in either of these cases link the UTC file in. Except if
299 * it isn't installed, in which case we remove the symlink altogether. Since glibc defaults to an
300 * internal version of UTC in that case behaviour is mostly equivalent. We still prefer creating the
301 * symlink though, since things are more self explanatory then. */
302
303 if (isempty(c->zone) || streq(c->zone, "UTC")) {
304
305 if (access("/usr/share/zoneinfo/UTC", F_OK) < 0) {
306
307 if (unlink("/etc/localtime") < 0 && errno != ENOENT)
308 return -errno;
309
310 return 0;
311 }
312
313 source = "../usr/share/zoneinfo/UTC";
314 } else {
315 p = path_join("../usr/share/zoneinfo", c->zone);
316 if (!p)
317 return -ENOMEM;
318
319 source = p;
320 }
321
322 return symlink_atomic(source, "/etc/localtime");
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 *(char*) mempcpy(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_atomic_label("/etc/adjtime", w);
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 unit_status_info_clear(u);
424
425 path = unit_dbus_path_from_name(u->name);
426 if (!path)
427 return -ENOMEM;
428
429 r = bus_map_all_properties(
430 bus,
431 "org.freedesktop.systemd1",
432 path,
433 map,
434 BUS_MAP_STRDUP,
435 &error,
436 NULL,
437 u);
438 if (r < 0)
439 return log_unit_error_errno(u, r, "Failed to get properties: %s", bus_error_message(&error, r));
440 }
441
442 return 0;
443 }
444
445 static int match_job_removed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
446 Context *c = ASSERT_PTR(userdata);
447 const char *path;
448 unsigned n = 0;
449 int r;
450
451 assert(m);
452
453 r = sd_bus_message_read(m, "uoss", NULL, &path, NULL, NULL);
454 if (r < 0) {
455 bus_log_parse_error(r);
456 return 0;
457 }
458
459 LIST_FOREACH(units, u, c->units)
460 if (streq_ptr(path, u->path))
461 u->path = mfree(u->path);
462 else
463 n += !!u->path;
464
465 if (n == 0) {
466 c->slot_job_removed = sd_bus_slot_unref(c->slot_job_removed);
467
468 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m),
469 "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "NTP",
470 NULL);
471 }
472
473 return 0;
474 }
475
476 static int unit_start_or_stop(UnitStatusInfo *u, sd_bus *bus, sd_bus_error *error, bool start) {
477 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
478 const char *path;
479 int r;
480
481 assert(u);
482 assert(bus);
483 assert(error);
484
485 r = bus_call_method(
486 bus,
487 bus_systemd_mgr,
488 start ? "StartUnit" : "StopUnit",
489 error,
490 &reply,
491 "ss",
492 u->name,
493 "replace");
494 log_unit_full_errno_zerook(u, r < 0 ? LOG_WARNING : LOG_DEBUG, r,
495 "%s unit: %m", start ? "Starting" : "Stopping");
496 if (r < 0)
497 return r;
498
499 r = sd_bus_message_read(reply, "o", &path);
500 if (r < 0)
501 return bus_log_parse_error(r);
502
503 r = free_and_strdup(&u->path, path);
504 if (r < 0)
505 return log_oom();
506
507 return 0;
508 }
509
510 static int unit_enable_or_disable(UnitStatusInfo *u, sd_bus *bus, sd_bus_error *error, bool enable) {
511 int r;
512
513 assert(u);
514 assert(bus);
515 assert(error);
516
517 /* Call context_update_ntp_status() to update UnitStatusInfo before calling this. */
518
519 if (streq(u->unit_file_state, "enabled") == enable) {
520 log_unit_debug(u, "already %sd.", enable_disable(enable));
521 return 0;
522 }
523
524 log_unit_info(u, "%s unit.", enable ? "Enabling" : "Disabling");
525
526 if (enable)
527 r = bus_call_method(
528 bus,
529 bus_systemd_mgr,
530 "EnableUnitFiles",
531 error,
532 NULL,
533 "asbb", 1,
534 u->name,
535 false, true);
536 else
537 r = bus_call_method(
538 bus,
539 bus_systemd_mgr,
540 "DisableUnitFiles",
541 error,
542 NULL,
543 "asb", 1,
544 u->name,
545 false);
546 if (r < 0)
547 return r;
548
549 r = bus_service_manager_reload(bus);
550 if (r < 0)
551 return r;
552
553 return 0;
554 }
555
556 static bool ntp_synced(void) {
557 struct timex txc = {};
558
559 if (adjtimex(&txc) < 0)
560 return false;
561
562 /* Consider the system clock synchronized if the reported maximum error is smaller than the maximum
563 * value (16 seconds). Ignore the STA_UNSYNC flag as it may have been set to prevent the kernel from
564 * touching the RTC. */
565 return txc.maxerror < 16000000;
566 }
567
568 static BUS_DEFINE_PROPERTY_GET_GLOBAL(property_get_time, "t", now(CLOCK_REALTIME));
569 static BUS_DEFINE_PROPERTY_GET_GLOBAL(property_get_ntp_sync, "b", ntp_synced());
570
571 static int property_get_rtc_time(
572 sd_bus *bus,
573 const char *path,
574 const char *interface,
575 const char *property,
576 sd_bus_message *reply,
577 void *userdata,
578 sd_bus_error *error) {
579
580 struct tm tm = {};
581 usec_t t = 0;
582 int r;
583
584 r = clock_get_hwclock(&tm);
585 if (r == -EBUSY)
586 log_warning("/dev/rtc is busy. Is somebody keeping it open continuously? That's not a good idea... Returning a bogus RTC timestamp.");
587 else if (r == -ENOENT)
588 log_debug("/dev/rtc not found.");
589 else if (r < 0)
590 return sd_bus_error_set_errnof(error, r, "Failed to read RTC: %m");
591 else
592 t = (usec_t) timegm(&tm) * USEC_PER_SEC;
593
594 return sd_bus_message_append(reply, "t", t);
595 }
596
597 static int property_get_can_ntp(
598 sd_bus *bus,
599 const char *path,
600 const char *interface,
601 const char *property,
602 sd_bus_message *reply,
603 void *userdata,
604 sd_bus_error *error) {
605
606 Context *c = ASSERT_PTR(userdata);
607 int r;
608
609 assert(bus);
610 assert(property);
611 assert(reply);
612 assert(error);
613
614 if (c->slot_job_removed)
615 /* When the previous request is not finished, then assume NTP is enabled. */
616 return sd_bus_message_append(reply, "b", true);
617
618 r = context_update_ntp_status(c, bus, reply);
619 if (r < 0)
620 return r;
621
622 return sd_bus_message_append(reply, "b", context_ntp_service_exists(c) > 0);
623 }
624
625 static int property_get_ntp(
626 sd_bus *bus,
627 const char *path,
628 const char *interface,
629 const char *property,
630 sd_bus_message *reply,
631 void *userdata,
632 sd_bus_error *error) {
633
634 Context *c = ASSERT_PTR(userdata);
635 int r;
636
637 assert(bus);
638 assert(property);
639 assert(reply);
640 assert(error);
641
642 if (c->slot_job_removed)
643 /* When the previous request is not finished, then assume NTP is active. */
644 return sd_bus_message_append(reply, "b", true);
645
646 r = context_update_ntp_status(c, bus, reply);
647 if (r < 0)
648 return r;
649
650 return sd_bus_message_append(reply, "b", context_ntp_service_is_active(c) > 0);
651 }
652
653 static int method_set_timezone(sd_bus_message *m, void *userdata, sd_bus_error *error) {
654 Context *c = ASSERT_PTR(userdata);
655 int interactive, r;
656 const char *z;
657
658 assert(m);
659
660 r = sd_bus_message_read(m, "sb", &z, &interactive);
661 if (r < 0)
662 return r;
663
664 if (!timezone_is_valid(z, LOG_DEBUG))
665 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid or not installed time zone '%s'", z);
666
667 if (streq_ptr(z, c->zone))
668 return sd_bus_reply_method_return(m, NULL);
669
670 r = bus_verify_polkit_async(
671 m,
672 CAP_SYS_TIME,
673 "org.freedesktop.timedate1.set-timezone",
674 NULL,
675 interactive,
676 UID_INVALID,
677 &c->polkit_registry,
678 error);
679 if (r < 0)
680 return r;
681 if (r == 0)
682 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
683
684 r = free_and_strdup(&c->zone, z);
685 if (r < 0)
686 return r;
687
688 /* 1. Write new configuration file */
689 r = context_write_data_timezone(c);
690 if (r < 0) {
691 log_error_errno(r, "Failed to set time zone: %m");
692 return sd_bus_error_set_errnof(error, r, "Failed to set time zone: %m");
693 }
694
695 /* 2. Make glibc notice the new timezone */
696 tzset();
697
698 /* 3. Tell the kernel our timezone */
699 r = clock_set_timezone(NULL);
700 if (r < 0)
701 log_debug_errno(r, "Failed to tell kernel about timezone, ignoring: %m");
702
703 if (c->local_rtc) {
704 struct timespec ts;
705 struct tm tm;
706
707 /* 4. Sync RTC from system clock, with the new delta */
708 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
709 assert_se(localtime_r(&ts.tv_sec, &tm));
710
711 r = clock_set_hwclock(&tm);
712 if (r < 0)
713 log_debug_errno(r, "Failed to sync time to hardware clock, ignoring: %m");
714 }
715
716 log_struct(LOG_INFO,
717 "MESSAGE_ID=" SD_MESSAGE_TIMEZONE_CHANGE_STR,
718 "TIMEZONE=%s", c->zone,
719 "TIMEZONE_SHORTNAME=%s", tzname[daylight],
720 "DAYLIGHT=%i", daylight,
721 LOG_MESSAGE("Changed time zone to '%s' (%s).", c->zone, tzname[daylight]));
722
723 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m),
724 "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "Timezone",
725 NULL);
726
727 return sd_bus_reply_method_return(m, NULL);
728 }
729
730 static int method_set_local_rtc(sd_bus_message *m, void *userdata, sd_bus_error *error) {
731 int lrtc, fix_system, interactive;
732 Context *c = ASSERT_PTR(userdata);
733 struct timespec ts;
734 int r;
735
736 assert(m);
737
738 r = sd_bus_message_read(m, "bbb", &lrtc, &fix_system, &interactive);
739 if (r < 0)
740 return r;
741
742 if (lrtc == c->local_rtc && !fix_system)
743 return sd_bus_reply_method_return(m, NULL);
744
745 r = bus_verify_polkit_async(
746 m,
747 CAP_SYS_TIME,
748 "org.freedesktop.timedate1.set-local-rtc",
749 NULL,
750 interactive,
751 UID_INVALID,
752 &c->polkit_registry,
753 error);
754 if (r < 0)
755 return r;
756 if (r == 0)
757 return 1;
758
759 if (lrtc != c->local_rtc) {
760 c->local_rtc = lrtc;
761
762 /* 1. Write new configuration file */
763 r = context_write_data_local_rtc(c);
764 if (r < 0) {
765 log_error_errno(r, "Failed to set RTC to %s: %m", lrtc ? "local" : "UTC");
766 return sd_bus_error_set_errnof(error, r, "Failed to set RTC to %s: %m", lrtc ? "local" : "UTC");
767 }
768 }
769
770 /* 2. Tell the kernel our timezone */
771 r = clock_set_timezone(NULL);
772 if (r < 0)
773 log_debug_errno(r, "Failed to tell kernel about timezone, ignoring: %m");
774
775 /* 3. Synchronize clocks */
776 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
777
778 if (fix_system) {
779 struct tm tm;
780
781 /* Sync system clock from RTC; first, initialize the timezone fields of struct tm. */
782 localtime_or_gmtime_r(&ts.tv_sec, &tm, !c->local_rtc);
783
784 /* Override the main fields of struct tm, but not the timezone fields */
785 r = clock_get_hwclock(&tm);
786 if (r < 0)
787 log_debug_errno(r, "Failed to get hardware clock, ignoring: %m");
788 else {
789 /* And set the system clock with this */
790 ts.tv_sec = mktime_or_timegm(&tm, !c->local_rtc);
791
792 if (clock_settime(CLOCK_REALTIME, &ts) < 0)
793 log_debug_errno(errno, "Failed to update system clock, ignoring: %m");
794 }
795
796 } else {
797 struct tm tm;
798
799 /* Sync RTC from system clock */
800 localtime_or_gmtime_r(&ts.tv_sec, &tm, !c->local_rtc);
801
802 r = clock_set_hwclock(&tm);
803 if (r < 0)
804 log_debug_errno(r, "Failed to sync time to hardware clock, ignoring: %m");
805 }
806
807 log_info("RTC configured to %s time.", c->local_rtc ? "local" : "UTC");
808
809 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m),
810 "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "LocalRTC",
811 NULL);
812
813 return sd_bus_reply_method_return(m, NULL);
814 }
815
816 static int method_set_time(sd_bus_message *m, void *userdata, sd_bus_error *error) {
817 sd_bus *bus = sd_bus_message_get_bus(m);
818 char buf[FORMAT_TIMESTAMP_MAX];
819 int relative, interactive, r;
820 Context *c = ASSERT_PTR(userdata);
821 int64_t utc;
822 struct timespec ts;
823 usec_t start;
824 struct tm tm;
825
826 assert(m);
827
828 if (c->slot_job_removed)
829 return sd_bus_error_set(error, BUS_ERROR_AUTOMATIC_TIME_SYNC_ENABLED, "Previous request is not finished, refusing.");
830
831 r = context_update_ntp_status(c, bus, m);
832 if (r < 0)
833 return sd_bus_error_set_errnof(error, r, "Failed to update context: %m");
834
835 if (context_ntp_service_is_active(c) > 0)
836 return sd_bus_error_set(error, BUS_ERROR_AUTOMATIC_TIME_SYNC_ENABLED, "Automatic time synchronization is enabled");
837
838 /* this only gets used if dbus does not provide a timestamp */
839 start = now(CLOCK_MONOTONIC);
840
841 r = sd_bus_message_read(m, "xbb", &utc, &relative, &interactive);
842 if (r < 0)
843 return r;
844
845 if (!relative && utc <= 0)
846 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid absolute time");
847
848 if (relative && utc == 0)
849 return sd_bus_reply_method_return(m, NULL);
850
851 if (relative) {
852 usec_t n, x;
853
854 n = now(CLOCK_REALTIME);
855 x = n + utc;
856
857 if ((utc > 0 && x < n) ||
858 (utc < 0 && x > n))
859 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Time value overflow");
860
861 timespec_store(&ts, x);
862 } else
863 timespec_store(&ts, (usec_t) utc);
864
865 r = bus_verify_polkit_async(
866 m,
867 CAP_SYS_TIME,
868 "org.freedesktop.timedate1.set-time",
869 NULL,
870 interactive,
871 UID_INVALID,
872 &c->polkit_registry,
873 error);
874 if (r < 0)
875 return r;
876 if (r == 0)
877 return 1;
878
879 /* adjust ts for time spent in program */
880 r = sd_bus_message_get_monotonic_usec(m, &start);
881 /* when sd_bus_message_get_monotonic_usec() returns -ENODATA it does not modify &start */
882 if (r < 0 && r != -ENODATA)
883 return r;
884
885 timespec_store(&ts, timespec_load(&ts) + (now(CLOCK_MONOTONIC) - start));
886
887 /* Set system clock */
888 if (clock_settime(CLOCK_REALTIME, &ts) < 0) {
889 log_error_errno(errno, "Failed to set local time: %m");
890 return sd_bus_error_set_errnof(error, errno, "Failed to set local time: %m");
891 }
892
893 /* Sync down to RTC */
894 localtime_or_gmtime_r(&ts.tv_sec, &tm, !c->local_rtc);
895
896 r = clock_set_hwclock(&tm);
897 if (r < 0)
898 log_debug_errno(r, "Failed to update hardware clock, ignoring: %m");
899
900 log_struct(LOG_INFO,
901 "MESSAGE_ID=" SD_MESSAGE_TIME_CHANGE_STR,
902 "REALTIME="USEC_FMT, timespec_load(&ts),
903 LOG_MESSAGE("Changed local time to %s", strnull(format_timestamp(buf, sizeof(buf), timespec_load(&ts)))));
904
905 return sd_bus_reply_method_return(m, NULL);
906 }
907
908 static int method_set_ntp(sd_bus_message *m, void *userdata, sd_bus_error *error) {
909 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
910 sd_bus *bus = sd_bus_message_get_bus(m);
911 Context *c = ASSERT_PTR(userdata);
912 const UnitStatusInfo *selected = NULL;
913 int enable, interactive, q, r;
914
915 assert(m);
916 assert(bus);
917
918 r = sd_bus_message_read(m, "bb", &enable, &interactive);
919 if (r < 0)
920 return r;
921
922 r = context_update_ntp_status(c, bus, m);
923 if (r < 0)
924 return r;
925
926 if (context_ntp_service_exists(c) <= 0)
927 return sd_bus_error_set(error, BUS_ERROR_NO_NTP_SUPPORT, "NTP not supported");
928
929 r = bus_verify_polkit_async(
930 m,
931 CAP_SYS_TIME,
932 "org.freedesktop.timedate1.set-ntp",
933 NULL,
934 interactive,
935 UID_INVALID,
936 &c->polkit_registry,
937 error);
938 if (r < 0)
939 return r;
940 if (r == 0)
941 return 1;
942
943 /* This method may be called frequently. Forget the previous job if it has not completed yet. */
944 LIST_FOREACH(units, u, c->units)
945 u->path = mfree(u->path);
946
947 if (!c->slot_job_removed) {
948 r = bus_match_signal_async(
949 bus,
950 &slot,
951 bus_systemd_mgr,
952 "JobRemoved",
953 match_job_removed, NULL, c);
954 if (r < 0)
955 return r;
956 }
957
958 if (enable)
959 LIST_FOREACH(units, u, c->units) {
960 bool enable_this_one = !selected;
961
962 if (!streq(u->load_state, "loaded"))
963 continue;
964
965 r = unit_enable_or_disable(u, bus, error, enable_this_one);
966 if (r < 0)
967 /* If enablement failed, don't start this unit. */
968 enable_this_one = false;
969
970 r = unit_start_or_stop(u, bus, error, enable_this_one);
971 if (r < 0)
972 log_unit_warning_errno(u, r, "Failed to %s %sd NTP unit, ignoring: %m",
973 enable_this_one ? "start" : "stop",
974 enable_disable(enable_this_one));
975 if (enable_this_one)
976 selected = u;
977 }
978 else
979 LIST_FOREACH(units, u, c->units) {
980 if (!streq(u->load_state, "loaded"))
981 continue;
982
983 q = unit_enable_or_disable(u, bus, error, false);
984 if (q < 0)
985 r = q;
986
987 q = unit_start_or_stop(u, bus, error, false);
988 if (q < 0)
989 r = q;
990 }
991
992 if (r < 0)
993 return r;
994 if (enable && !selected)
995 return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "No NTP service found to enable.");
996
997 if (slot)
998 c->slot_job_removed = TAKE_PTR(slot);
999
1000 if (selected)
1001 log_info("Set NTP to enabled (%s).", selected->name);
1002 else
1003 log_info("Set NTP to disabled.");
1004
1005 return sd_bus_reply_method_return(m, NULL);
1006 }
1007
1008 static int method_list_timezones(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1009 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1010 _cleanup_strv_free_ char **zones = NULL;
1011 int r;
1012
1013 assert(m);
1014
1015 r = get_timezones(&zones);
1016 if (r < 0)
1017 return sd_bus_error_set_errnof(error, r, "Failed to read list of time zones: %m");
1018
1019 r = sd_bus_message_new_method_return(m, &reply);
1020 if (r < 0)
1021 return r;
1022
1023 r = sd_bus_message_append_strv(reply, zones);
1024 if (r < 0)
1025 return r;
1026
1027 return sd_bus_send(NULL, reply, NULL);
1028 }
1029
1030 static const sd_bus_vtable timedate_vtable[] = {
1031 SD_BUS_VTABLE_START(0),
1032
1033 SD_BUS_PROPERTY("Timezone", "s", NULL, offsetof(Context, zone), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
1034 SD_BUS_PROPERTY("LocalRTC", "b", bus_property_get_bool, offsetof(Context, local_rtc), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
1035 SD_BUS_PROPERTY("CanNTP", "b", property_get_can_ntp, 0, 0),
1036 SD_BUS_PROPERTY("NTP", "b", property_get_ntp, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
1037 SD_BUS_PROPERTY("NTPSynchronized", "b", property_get_ntp_sync, 0, 0),
1038 SD_BUS_PROPERTY("TimeUSec", "t", property_get_time, 0, 0),
1039 SD_BUS_PROPERTY("RTCTimeUSec", "t", property_get_rtc_time, 0, 0),
1040
1041 SD_BUS_METHOD_WITH_ARGS("SetTime",
1042 SD_BUS_ARGS("x", usec_utc, "b", relative, "b", interactive),
1043 SD_BUS_NO_RESULT,
1044 method_set_time,
1045 SD_BUS_VTABLE_UNPRIVILEGED),
1046 SD_BUS_METHOD_WITH_ARGS("SetTimezone",
1047 SD_BUS_ARGS("s", timezone, "b", interactive),
1048 SD_BUS_NO_RESULT,
1049 method_set_timezone,
1050 SD_BUS_VTABLE_UNPRIVILEGED),
1051 SD_BUS_METHOD_WITH_ARGS("SetLocalRTC",
1052 SD_BUS_ARGS("b", local_rtc, "b", fix_system, "b", interactive),
1053 SD_BUS_NO_RESULT,
1054 method_set_local_rtc,
1055 SD_BUS_VTABLE_UNPRIVILEGED),
1056 SD_BUS_METHOD_WITH_ARGS("SetNTP",
1057 SD_BUS_ARGS("b", use_ntp, "b", interactive),
1058 SD_BUS_NO_RESULT,
1059 method_set_ntp,
1060 SD_BUS_VTABLE_UNPRIVILEGED),
1061 SD_BUS_METHOD_WITH_ARGS("ListTimezones",
1062 SD_BUS_NO_ARGS,
1063 SD_BUS_RESULT("as", timezones),
1064 method_list_timezones,
1065 SD_BUS_VTABLE_UNPRIVILEGED),
1066
1067 SD_BUS_VTABLE_END,
1068 };
1069
1070 const BusObjectImplementation manager_object = {
1071 "/org/freedesktop/timedate1",
1072 "org.freedesktop.timedate1",
1073 .vtables = BUS_VTABLES(timedate_vtable),
1074 };
1075
1076 static int connect_bus(Context *c, sd_event *event, sd_bus **_bus) {
1077 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1078 int r;
1079
1080 assert(c);
1081 assert(event);
1082 assert(_bus);
1083
1084 r = sd_bus_default_system(&bus);
1085 if (r < 0)
1086 return log_error_errno(r, "Failed to get system bus connection: %m");
1087
1088 r = bus_add_implementation(bus, &manager_object, c);
1089 if (r < 0)
1090 return r;
1091
1092 r = bus_log_control_api_register(bus);
1093 if (r < 0)
1094 return r;
1095
1096 r = sd_bus_request_name_async(bus, NULL, "org.freedesktop.timedate1", 0, NULL, NULL);
1097 if (r < 0)
1098 return log_error_errno(r, "Failed to request name: %m");
1099
1100 r = sd_bus_attach_event(bus, event, 0);
1101 if (r < 0)
1102 return log_error_errno(r, "Failed to attach bus to event loop: %m");
1103
1104 *_bus = TAKE_PTR(bus);
1105
1106 return 0;
1107 }
1108
1109 static int run(int argc, char *argv[]) {
1110 _cleanup_(context_clear) Context context = {};
1111 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1112 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1113 int r;
1114
1115 log_setup();
1116
1117 r = service_parse_argv("systemd-timedated.service",
1118 "Manage the system clock and timezone and NTP enablement.",
1119 BUS_IMPLEMENTATIONS(&manager_object,
1120 &log_control_object),
1121 argc, argv);
1122 if (r <= 0)
1123 return r;
1124
1125 umask(0022);
1126
1127 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, -1) >= 0);
1128
1129 r = sd_event_default(&event);
1130 if (r < 0)
1131 return log_error_errno(r, "Failed to allocate event loop: %m");
1132
1133 (void) sd_event_set_watchdog(event, true);
1134
1135 r = sd_event_add_signal(event, NULL, SIGINT, NULL, NULL);
1136 if (r < 0)
1137 return log_error_errno(r, "Failed to install SIGINT handler: %m");
1138
1139 r = sd_event_add_signal(event, NULL, SIGTERM, NULL, NULL);
1140 if (r < 0)
1141 return log_error_errno(r, "Failed to install SIGTERM handler: %m");
1142
1143 r = connect_bus(&context, event, &bus);
1144 if (r < 0)
1145 return r;
1146
1147 (void) sd_bus_negotiate_timestamp(bus, true);
1148
1149 r = context_read_data(&context);
1150 if (r < 0)
1151 return log_error_errno(r, "Failed to read time zone data: %m");
1152
1153 r = context_parse_ntp_services(&context);
1154 if (r < 0)
1155 return r;
1156
1157 r = bus_event_loop_with_idle(event, bus, "org.freedesktop.timedate1", DEFAULT_EXIT_USEC, NULL, NULL);
1158 if (r < 0)
1159 return log_error_errno(r, "Failed to run event loop: %m");
1160
1161 return 0;
1162 }
1163
1164 DEFINE_MAIN_FUNCTION(run);