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