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