]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/timedate/timedated.c
timedate: treat 'activating' or 'inactivating' NTP client status as 'active'
[thirdparty/systemd.git] / src / timedate / timedated.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
f401e48c 2
f401e48c
LP
3#include <errno.h>
4#include <string.h>
5#include <unistd.h>
6
40ca29a1 7#include "sd-bus.h"
f4f15635
LP
8#include "sd-event.h"
9#include "sd-messages.h"
40ca29a1 10
b5efdb8a 11#include "alloc-util.h"
96aad8d1 12#include "bus-common-errors.h"
f4f15635
LP
13#include "bus-error.h"
14#include "bus-util.h"
15#include "clock-util.h"
16#include "def.h"
f4f15635 17#include "fileio-label.h"
e4de7287 18#include "fileio.h"
f4f15635 19#include "fs-util.h"
5d280742
YW
20#include "hashmap.h"
21#include "list.h"
1f47bc33 22#include "main-func.h"
36dd5ffd 23#include "missing_capability.h"
f4f15635 24#include "path-util.h"
d7b8eec7 25#include "selinux-util.h"
754f0269 26#include "signal-util.h"
5d280742 27#include "string-util.h"
f4f15635 28#include "strv.h"
5d280742
YW
29#include "unit-def.h"
30#include "unit-name.h"
ee104e11 31#include "user-util.h"
f4f15635 32#include "util.h"
f401e48c
LP
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
5d280742
YW
37typedef struct UnitStatusInfo {
38 char *name;
39 char *load_state;
40 char *unit_file_state;
41 char *active_state;
cf3872bd 42 char *path;
5d280742
YW
43
44 LIST_FIELDS(struct UnitStatusInfo, units);
45} UnitStatusInfo;
46
40ca29a1 47typedef struct Context {
d200735e
MS
48 char *zone;
49 bool local_rtc;
40ca29a1 50 Hashmap *polkit_registry;
2770af85 51 sd_bus_message *cache;
5d280742 52
3af0a96c 53 sd_bus_slot *slot_job_removed;
3af0a96c 54
5d280742 55 LIST_HEAD(UnitStatusInfo, units);
40ca29a1 56} Context;
f401e48c 57
5d280742
YW
58static 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
66static void unit_status_info_free(UnitStatusInfo *p) {
67 assert(p);
68
69 unit_status_info_clear(p);
70 free(p->name);
cf3872bd 71 free(p->path);
5d280742
YW
72 free(p);
73}
74
1f47bc33 75static void context_clear(Context *c) {
5d280742
YW
76 UnitStatusInfo *p;
77
40ca29a1 78 assert(c);
f401e48c 79
82d115d9 80 free(c->zone);
36e34057 81 bus_verify_polkit_async_registry_free(c->polkit_registry);
2770af85 82 sd_bus_message_unref(c->cache);
5d280742 83
3af0a96c 84 sd_bus_slot_unref(c->slot_job_removed);
3af0a96c 85
5d280742
YW
86 while ((p = c->units)) {
87 LIST_REMOVE(units, c->units, p);
88 unit_status_info_free(p);
89 }
90}
91
92static int context_add_ntp_service(Context *c, const char *s) {
5d280742
YW
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
118static 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
154static 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)
84a87726 163 count += !STRPTR_IN_SET(info->active_state, "inactive", "failed");
5d280742
YW
164
165 return count;
166}
167
168static 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)
84a87726 177 count += !STRPTR_IN_SET(info->unit_file_state, "masked", "masked-runtime", "disabled", "bad");
5d280742
YW
178
179 return count;
180}
181
182static 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;
f401e48c
LP
194}
195
40ca29a1 196static int context_read_data(Context *c) {
424a19f8 197 _cleanup_free_ char *t = NULL;
40ca29a1
LP
198 int r;
199
200 assert(c);
f401e48c 201
5c904ba5
LP
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");
92c4ef2d 207
f9ecfd3b 208 free_and_replace(c->zone, t);
f401e48c 209
6369641d 210 c->local_rtc = clock_is_localtime(NULL) > 0;
f401e48c
LP
211
212 return 0;
213}
214
40ca29a1 215static int context_write_data_timezone(Context *c) {
424a19f8 216 _cleanup_free_ char *p = NULL;
40ca29a1
LP
217 int r = 0;
218
219 assert(c);
e19a21a8 220
40ca29a1 221 if (isempty(c->zone)) {
424a19f8 222 if (unlink("/etc/localtime") < 0 && errno != ENOENT)
f401e48c
LP
223 r = -errno;
224
f401e48c
LP
225 return r;
226 }
227
40ca29a1 228 p = strappend("../usr/share/zoneinfo/", c->zone);
0d0f0c50
SL
229 if (!p)
230 return log_oom();
f401e48c 231
424a19f8 232 r = symlink_atomic(p, "/etc/localtime");
f401e48c 233 if (r < 0)
424a19f8 234 return r;
f401e48c 235
f401e48c
LP
236 return 0;
237}
238
40ca29a1 239static int context_write_data_local_rtc(Context *c) {
f401e48c 240 int r;
7fd1b19b 241 _cleanup_free_ char *s = NULL, *w = NULL;
f401e48c 242
40ca29a1
LP
243 assert(c);
244
f401e48c
LP
245 r = read_full_file("/etc/adjtime", &s, NULL);
246 if (r < 0) {
247 if (r != -ENOENT)
248 return r;
249
40ca29a1 250 if (!c->local_rtc)
f401e48c
LP
251 return 0;
252
253 w = strdup(NULL_ADJTIME_LOCAL);
254 if (!w)
255 return -ENOMEM;
256 } else {
c9410dd4 257 char *p;
8f462d87 258 const char *e = "\n"; /* default if there is less than 3 lines */
c9410dd4 259 const char *prepend = "";
f401e48c
LP
260 size_t a, b;
261
c9410dd4 262 p = strchrnul(s, '\n');
cb971cc0 263 if (*p == '\0')
c9410dd4
MP
264 /* only one line, no \n terminator */
265 prepend = "\n0\n";
cb971cc0 266 else if (p[1] == '\0') {
c9410dd4
MP
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 }
f401e48c
LP
286
287 a = p - s;
288 b = strlen(e);
289
c9410dd4 290 w = new(char, a + (c->local_rtc ? 5 : 3) + strlen(prepend) + b + 1);
d257f05a 291 if (!w)
f401e48c 292 return -ENOMEM;
f401e48c 293
c9410dd4 294 *(char*) mempcpy(stpcpy(stpcpy(mempcpy(w, s, a), prepend), c->local_rtc ? "LOCAL" : "UTC"), e, b) = 0;
f401e48c
LP
295
296 if (streq(w, NULL_ADJTIME_UTC)) {
d257f05a 297 if (unlink("/etc/adjtime") < 0)
f401e48c
LP
298 if (errno != ENOENT)
299 return -errno;
f401e48c
LP
300
301 return 0;
302 }
303 }
40ca29a1 304
c3dacc8b 305 mac_selinux_init();
d257f05a 306 return write_string_file_atomic_label("/etc/adjtime", w);
f401e48c
LP
307}
308
5d280742
YW
309static 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 };
5d280742 316 UnitStatusInfo *u;
c5f0532f
LP
317 int r;
318
40ca29a1 319 assert(c);
c5f0532f
LP
320 assert(bus);
321
2770af85
YW
322 /* Suppress calling context_update_ntp_status() multiple times within single DBus transaction. */
323 if (m) {
324 if (m == c->cache)
325 return 0;
2aa4c315 326
2770af85
YW
327 sd_bus_message_unref(c->cache);
328 c->cache = sd_bus_message_ref(m);
329 }
2aa4c315 330
5d280742
YW
331 LIST_FOREACH(units, u, c->units) {
332 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5d280742 333 _cleanup_free_ char *path = NULL;
c5f0532f 334
5d280742 335 unit_status_info_clear(u);
40ca29a1 336
5d280742
YW
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 }
c5f0532f 353
40ca29a1 354 return 0;
c5f0532f
LP
355}
356
3af0a96c 357static int match_job_removed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
3af0a96c 358 Context *c = userdata;
cf3872bd
YW
359 UnitStatusInfo *u;
360 const char *path;
361 unsigned n = 0;
3af0a96c
YW
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
cf3872bd
YW
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;
3af0a96c 378
cf3872bd
YW
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);
3af0a96c 381
cf3872bd
YW
382 c->slot_job_removed = sd_bus_slot_unref(c->slot_job_removed);
383 }
3af0a96c
YW
384
385 return 0;
386}
387
cf3872bd 388static int unit_start_or_stop(UnitStatusInfo *u, sd_bus *bus, sd_bus_error *error, bool start) {
3af0a96c 389 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
3af0a96c 390 const char *path;
c5f0532f
LP
391 int r;
392
5d280742 393 assert(u);
c5f0532f
LP
394 assert(bus);
395 assert(error);
396
81b84399
ZJS
397 r = sd_bus_call_method(
398 bus,
399 "org.freedesktop.systemd1",
400 "/org/freedesktop/systemd1",
401 "org.freedesktop.systemd1.Manager",
5d280742 402 start ? "StartUnit" : "StopUnit",
81b84399 403 error,
3af0a96c 404 &reply,
81b84399 405 "ss",
5d280742 406 u->name,
81b84399 407 "replace");
5d280742 408 if (r < 0)
b72ddf0f 409 return r;
c5f0532f 410
3af0a96c
YW
411 r = sd_bus_message_read(reply, "o", &path);
412 if (r < 0)
413 return bus_log_parse_error(r);
414
cf3872bd 415 r = free_and_strdup(&u->path, path);
3af0a96c
YW
416 if (r < 0)
417 return log_oom();
418
b72ddf0f 419 return 0;
c5f0532f
LP
420}
421
5d280742 422static int unit_enable_or_disable(UnitStatusInfo *u, sd_bus *bus, sd_bus_error *error, bool enable) {
c5f0532f 423 int r;
c5f0532f 424
5d280742 425 assert(u);
c5f0532f
LP
426 assert(bus);
427 assert(error);
428
5d280742
YW
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)
40ca29a1
LP
435 r = sd_bus_call_method(
436 bus,
ac7019f3
LP
437 "org.freedesktop.systemd1",
438 "/org/freedesktop/systemd1",
439 "org.freedesktop.systemd1.Manager",
b72ddf0f 440 "EnableUnitFiles",
40ca29a1
LP
441 error,
442 NULL,
b72ddf0f 443 "asbb", 1,
5d280742 444 u->name,
b72ddf0f
KS
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,
5d280742 456 u->name,
b72ddf0f 457 false);
5d280742 458 if (r < 0)
b72ddf0f 459 return r;
c5f0532f 460
b72ddf0f
KS
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);
3af0a96c
YW
470 if (r < 0)
471 return r;
472
b72ddf0f 473 return 0;
40ca29a1 474}
c5f0532f 475
6cc379b5
YW
476static BUS_DEFINE_PROPERTY_GET_GLOBAL(property_get_time, "t", now(CLOCK_REALTIME));
477static BUS_DEFINE_PROPERTY_GET_GLOBAL(property_get_ntp_sync, "b", ntp_synced());
478
6fc60278
LP
479static 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,
ebcf1f97
LP
485 void *userdata,
486 sd_bus_error *error) {
6fc60278
LP
487
488 struct tm tm;
489 usec_t t;
490 int r;
491
492 zero(tm);
60989612 493 r = clock_get_hwclock(&tm);
88e262b6 494 if (r == -EBUSY) {
07a062a7 495 log_warning("/dev/rtc is busy. Is somebody keeping it open continuously? That's not a good idea... Returning a bogus RTC timestamp.");
88e262b6 496 t = 0;
fe2b58a4 497 } else if (r == -ENOENT) {
07a062a7 498 log_debug("/dev/rtc not found.");
fe2b58a4 499 t = 0; /* no RTC found */
ebcf1f97 500 } else if (r < 0)
10a87006 501 return sd_bus_error_set_errnof(error, r, "Failed to read RTC: %m");
ebcf1f97 502 else
2f6a5907 503 t = (usec_t) timegm(&tm) * USEC_PER_SEC;
6fc60278 504
ebcf1f97 505 return sd_bus_message_append(reply, "t", t);
6fc60278
LP
506}
507
5d280742
YW
508static 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 r = context_update_ntp_status(c, bus, reply);
527 if (r < 0)
528 return r;
529
530 return sd_bus_message_append(reply, "b", context_ntp_service_exists(c) > 0);
531}
532
533static int property_get_ntp(
534 sd_bus *bus,
535 const char *path,
536 const char *interface,
537 const char *property,
538 sd_bus_message *reply,
539 void *userdata,
540 sd_bus_error *error) {
541
542 Context *c = userdata;
543 int r;
544
545 assert(c);
546 assert(bus);
547 assert(property);
548 assert(reply);
549 assert(error);
550
551 r = context_update_ntp_status(c, bus, reply);
552 if (r < 0)
553 return r;
554
555 return sd_bus_message_append(reply, "b", context_ntp_service_is_active(c) > 0);
556}
557
19070062 558static int method_set_timezone(sd_bus_message *m, void *userdata, sd_bus_error *error) {
40ca29a1 559 Context *c = userdata;
2c3def62 560 int interactive, r;
40ca29a1 561 const char *z;
c5f0532f 562
7e9cf16c
LP
563 assert(m);
564 assert(c);
565
40ca29a1
LP
566 r = sd_bus_message_read(m, "sb", &z, &interactive);
567 if (r < 0)
ebcf1f97 568 return r;
c5f0532f 569
089fb865 570 if (!timezone_is_valid(z, LOG_DEBUG))
ebcf1f97 571 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid time zone '%s'", z);
ac7019f3 572
539a68e0 573 if (streq_ptr(z, c->zone))
df2d202e 574 return sd_bus_reply_method_return(m, NULL);
c5f0532f 575
c529695e
LP
576 r = bus_verify_polkit_async(
577 m,
578 CAP_SYS_TIME,
579 "org.freedesktop.timedate1.set-timezone",
403ed0e5 580 NULL,
c529695e
LP
581 interactive,
582 UID_INVALID,
583 &c->polkit_registry,
584 error);
40ca29a1 585 if (r < 0)
ebcf1f97 586 return r;
40ca29a1 587 if (r == 0)
6fc60278 588 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
6ffe5e37 589
539a68e0
YW
590 r = free_and_strdup(&c->zone, z);
591 if (r < 0)
592 return r;
593
40ca29a1
LP
594 /* 1. Write new configuration file */
595 r = context_write_data_timezone(c);
596 if (r < 0) {
da927ba9 597 log_error_errno(r, "Failed to set time zone: %m");
10a87006 598 return sd_bus_error_set_errnof(error, r, "Failed to set time zone: %m");
40ca29a1 599 }
6ffe5e37 600
8a50b96f
LP
601 /* 2. Make glibc notice the new timezone */
602 tzset();
603
604 /* 3. Tell the kernel our timezone */
2a7ff45f
LP
605 r = clock_set_timezone(NULL);
606 if (r < 0)
607 log_debug_errno(r, "Failed to tell kernel about timezone, ignoring: %m");
6ffe5e37 608
40ca29a1
LP
609 if (c->local_rtc) {
610 struct timespec ts;
e0f691e1 611 struct tm tm;
c5f0532f 612
8a50b96f 613 /* 4. Sync RTC from system clock, with the new delta */
40ca29a1 614 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
e0f691e1 615 assert_se(localtime_r(&ts.tv_sec, &tm));
2a7ff45f 616
e0f691e1 617 r = clock_set_hwclock(&tm);
2a7ff45f
LP
618 if (r < 0)
619 log_debug_errno(r, "Failed to sync time to hardware clock, ignoring: %m");
40ca29a1 620 }
c5f0532f 621
40ca29a1 622 log_struct(LOG_INFO,
2b044526 623 "MESSAGE_ID=" SD_MESSAGE_TIMEZONE_CHANGE_STR,
40ca29a1 624 "TIMEZONE=%s", c->zone,
8a50b96f
LP
625 "TIMEZONE_SHORTNAME=%s", tzname[daylight],
626 "DAYLIGHT=%i", daylight,
a1230ff9 627 LOG_MESSAGE("Changed time zone to '%s' (%s).", c->zone, tzname[daylight]));
c5f0532f 628
19070062 629 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m), "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "Timezone", NULL);
c5f0532f 630
df2d202e 631 return sd_bus_reply_method_return(m, NULL);
c5f0532f
LP
632}
633
19070062 634static int method_set_local_rtc(sd_bus_message *m, void *userdata, sd_bus_error *error) {
102d8f81 635 int lrtc, fix_system, interactive;
40ca29a1
LP
636 Context *c = userdata;
637 struct timespec ts;
f401e48c
LP
638 int r;
639
40ca29a1
LP
640 assert(m);
641 assert(c);
f401e48c 642
40ca29a1
LP
643 r = sd_bus_message_read(m, "bbb", &lrtc, &fix_system, &interactive);
644 if (r < 0)
ebcf1f97 645 return r;
f401e48c 646
40ca29a1 647 if (lrtc == c->local_rtc)
df2d202e 648 return sd_bus_reply_method_return(m, NULL);
f401e48c 649
c529695e
LP
650 r = bus_verify_polkit_async(
651 m,
652 CAP_SYS_TIME,
653 "org.freedesktop.timedate1.set-local-rtc",
403ed0e5 654 NULL,
c529695e
LP
655 interactive,
656 UID_INVALID,
657 &c->polkit_registry,
658 error);
40ca29a1 659 if (r < 0)
ebcf1f97 660 return r;
40ca29a1
LP
661 if (r == 0)
662 return 1;
f401e48c 663
40ca29a1 664 c->local_rtc = lrtc;
f401e48c 665
40ca29a1
LP
666 /* 1. Write new configuration file */
667 r = context_write_data_local_rtc(c);
668 if (r < 0) {
da927ba9 669 log_error_errno(r, "Failed to set RTC to local/UTC: %m");
10a87006 670 return sd_bus_error_set_errnof(error, r, "Failed to set RTC to local/UTC: %m");
40ca29a1 671 }
f401e48c 672
40ca29a1 673 /* 2. Tell the kernel our timezone */
2a7ff45f
LP
674 r = clock_set_timezone(NULL);
675 if (r < 0)
676 log_debug_errno(r, "Failed to tell kernel about timezone, ignoring: %m");
f401e48c 677
40ca29a1
LP
678 /* 3. Synchronize clocks */
679 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
f401e48c 680
40ca29a1
LP
681 if (fix_system) {
682 struct tm tm;
f401e48c 683
2a7ff45f 684 /* Sync system clock from RTC; first, initialize the timezone fields of struct tm. */
40ca29a1 685 if (c->local_rtc)
e46acb79 686 localtime_r(&ts.tv_sec, &tm);
40ca29a1 687 else
e46acb79 688 gmtime_r(&ts.tv_sec, &tm);
72edcff5 689
2a7ff45f
LP
690 /* Override the main fields of struct tm, but not the timezone fields */
691 r = clock_get_hwclock(&tm);
692 if (r < 0)
693 log_debug_errno(r, "Failed to get hardware clock, ignoring: %m");
694 else {
695 /* And set the system clock with this */
40ca29a1
LP
696 if (c->local_rtc)
697 ts.tv_sec = mktime(&tm);
698 else
699 ts.tv_sec = timegm(&tm);
2076cf88 700
2a7ff45f
LP
701 if (clock_settime(CLOCK_REALTIME, &ts) < 0)
702 log_debug_errno(errno, "Failed to update system clock, ignoring: %m");
f401e48c
LP
703 }
704
40ca29a1 705 } else {
e46acb79 706 struct tm tm;
f401e48c 707
40ca29a1
LP
708 /* Sync RTC from system clock */
709 if (c->local_rtc)
e46acb79 710 localtime_r(&ts.tv_sec, &tm);
40ca29a1 711 else
e46acb79 712 gmtime_r(&ts.tv_sec, &tm);
2076cf88 713
e46acb79 714 r = clock_set_hwclock(&tm);
2a7ff45f
LP
715 if (r < 0)
716 log_debug_errno(r, "Failed to sync time to hardware clock, ignoring: %m");
40ca29a1 717 }
2076cf88 718
40ca29a1 719 log_info("RTC configured to %s time.", c->local_rtc ? "local" : "UTC");
2076cf88 720
19070062 721 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m), "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "LocalRTC", NULL);
2076cf88 722
df2d202e 723 return sd_bus_reply_method_return(m, NULL);
40ca29a1 724}
2076cf88 725
19070062 726static int method_set_time(sd_bus_message *m, void *userdata, sd_bus_error *error) {
5d280742
YW
727 sd_bus *bus = sd_bus_message_get_bus(m);
728 int relative, interactive, r;
40ca29a1
LP
729 Context *c = userdata;
730 int64_t utc;
731 struct timespec ts;
2479df30 732 usec_t start;
e46acb79 733 struct tm tm;
2076cf88 734
40ca29a1
LP
735 assert(m);
736 assert(c);
2076cf88 737
5d280742
YW
738 r = context_update_ntp_status(c, bus, m);
739 if (r < 0)
740 return sd_bus_error_set_errnof(error, r, "Failed to update context: %m");
741
742 if (context_ntp_service_is_active(c) > 0)
e9e5ea88 743 return sd_bus_error_set(error, BUS_ERROR_AUTOMATIC_TIME_SYNC_ENABLED, "Automatic time synchronization is enabled");
82d115d9 744
6829cec4
SL
745 /* this only gets used if dbus does not provide a timestamp */
746 start = now(CLOCK_MONOTONIC);
747
40ca29a1
LP
748 r = sd_bus_message_read(m, "xbb", &utc, &relative, &interactive);
749 if (r < 0)
ebcf1f97 750 return r;
2076cf88 751
40ca29a1 752 if (!relative && utc <= 0)
e9e5ea88 753 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid absolute time");
2076cf88 754
40ca29a1 755 if (relative && utc == 0)
df2d202e 756 return sd_bus_reply_method_return(m, NULL);
2076cf88 757
40ca29a1
LP
758 if (relative) {
759 usec_t n, x;
f401e48c 760
40ca29a1
LP
761 n = now(CLOCK_REALTIME);
762 x = n + utc;
f401e48c 763
40ca29a1
LP
764 if ((utc > 0 && x < n) ||
765 (utc < 0 && x > n))
e9e5ea88 766 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Time value overflow");
f401e48c 767
40ca29a1
LP
768 timespec_store(&ts, x);
769 } else
770 timespec_store(&ts, (usec_t) utc);
2076cf88 771
c529695e
LP
772 r = bus_verify_polkit_async(
773 m,
774 CAP_SYS_TIME,
775 "org.freedesktop.timedate1.set-time",
403ed0e5 776 NULL,
c529695e
LP
777 interactive,
778 UID_INVALID,
779 &c->polkit_registry,
780 error);
40ca29a1 781 if (r < 0)
ebcf1f97 782 return r;
40ca29a1
LP
783 if (r == 0)
784 return 1;
785
2479df30
SL
786 /* adjust ts for time spent in program */
787 r = sd_bus_message_get_monotonic_usec(m, &start);
6829cec4 788 /* when sd_bus_message_get_monotonic_usec() returns -ENODATA it does not modify &start */
2479df30
SL
789 if (r < 0 && r != -ENODATA)
790 return r;
6829cec4
SL
791
792 timespec_store(&ts, timespec_load(&ts) + (now(CLOCK_MONOTONIC) - start));
2479df30 793
40ca29a1
LP
794 /* Set system clock */
795 if (clock_settime(CLOCK_REALTIME, &ts) < 0) {
56f64d95 796 log_error_errno(errno, "Failed to set local time: %m");
ebcf1f97 797 return sd_bus_error_set_errnof(error, errno, "Failed to set local time: %m");
40ca29a1 798 }
2076cf88 799
40ca29a1
LP
800 /* Sync down to RTC */
801 if (c->local_rtc)
e46acb79 802 localtime_r(&ts.tv_sec, &tm);
40ca29a1 803 else
e46acb79 804 gmtime_r(&ts.tv_sec, &tm);
2a7ff45f 805
e46acb79 806 r = clock_set_hwclock(&tm);
2a7ff45f
LP
807 if (r < 0)
808 log_debug_errno(r, "Failed to update hardware clock, ignoring: %m");
f401e48c 809
40ca29a1 810 log_struct(LOG_INFO,
2b044526 811 "MESSAGE_ID=" SD_MESSAGE_TIME_CHANGE_STR,
de0671ee 812 "REALTIME="USEC_FMT, timespec_load(&ts),
a1230ff9 813 LOG_MESSAGE("Changed local time to %s", ctime(&ts.tv_sec)));
f401e48c 814
df2d202e 815 return sd_bus_reply_method_return(m, NULL);
40ca29a1 816}
f401e48c 817
19070062 818static int method_set_ntp(sd_bus_message *m, void *userdata, sd_bus_error *error) {
cf3872bd 819 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
5d280742 820 sd_bus *bus = sd_bus_message_get_bus(m);
40ca29a1 821 Context *c = userdata;
5d280742
YW
822 UnitStatusInfo *u;
823 int enable, interactive, q, r;
f401e48c 824
19070062 825 assert(m);
5d280742 826 assert(bus);
19070062
LP
827 assert(c);
828
5d280742 829 r = sd_bus_message_read(m, "bb", &enable, &interactive);
40ca29a1 830 if (r < 0)
ebcf1f97 831 return r;
f401e48c 832
5d280742
YW
833 r = context_update_ntp_status(c, bus, m);
834 if (r < 0)
835 return r;
836
837 if (context_ntp_service_exists(c) <= 0)
838 return sd_bus_error_set(error, BUS_ERROR_NO_NTP_SUPPORT, "NTP not supported");
f401e48c 839
c529695e
LP
840 r = bus_verify_polkit_async(
841 m,
842 CAP_SYS_TIME,
843 "org.freedesktop.timedate1.set-ntp",
403ed0e5 844 NULL,
c529695e
LP
845 interactive,
846 UID_INVALID,
847 &c->polkit_registry,
848 error);
40ca29a1 849 if (r < 0)
ebcf1f97 850 return r;
40ca29a1
LP
851 if (r == 0)
852 return 1;
f401e48c 853
cf3872bd
YW
854 /* This method may be called frequently. Forget the previous job if it has not completed yet. */
855 LIST_FOREACH(units, u, c->units)
856 u->path = mfree(u->path);
857
858 if (!c->slot_job_removed) {
859 r = sd_bus_match_signal_async(
860 bus,
861 &slot,
862 "org.freedesktop.systemd1",
863 "/org/freedesktop/systemd1",
864 "org.freedesktop.systemd1.Manager",
865 "JobRemoved",
866 match_job_removed, NULL, c);
867 if (r < 0)
868 return r;
869 }
870
5d280742
YW
871 if (!enable)
872 LIST_FOREACH(units, u, c->units) {
873 if (!streq(u->load_state, "loaded"))
874 continue;
875
876 q = unit_enable_or_disable(u, bus, error, enable);
877 if (q < 0)
878 r = q;
879
cf3872bd 880 q = unit_start_or_stop(u, bus, error, enable);
5d280742
YW
881 if (q < 0)
882 r = q;
883 }
884
885 else if (context_ntp_service_is_enabled(c) <= 0)
886 LIST_FOREACH(units, u, c->units) {
887 if (!streq(u->load_state, "loaded"))
888 continue;
889
890 r = unit_enable_or_disable(u, bus, error, enable);
891 if (r < 0)
892 continue;
893
cf3872bd 894 r = unit_start_or_stop(u, bus, error, enable);
5d280742
YW
895 break;
896 }
897
3af0a96c 898 else
5d280742
YW
899 LIST_FOREACH(units, u, c->units) {
900 if (!streq(u->load_state, "loaded") ||
901 !streq(u->unit_file_state, "enabled"))
902 continue;
903
cf3872bd 904 r = unit_start_or_stop(u, bus, error, enable);
5d280742
YW
905 break;
906 }
40ca29a1 907
40ca29a1 908 if (r < 0)
ebcf1f97 909 return r;
f401e48c 910
cf3872bd
YW
911 if (slot)
912 c->slot_job_removed = TAKE_PTR(slot);
913
5d280742 914 log_info("Set NTP to %sd", enable_disable(enable));
f401e48c 915
df2d202e 916 return sd_bus_reply_method_return(m, NULL);
f401e48c
LP
917}
918
2cf0b2fe
NT
919static int method_list_timezones(sd_bus_message *m, void *userdata, sd_bus_error *error) {
920 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
921 _cleanup_strv_free_ char **zones = NULL;
922 int r;
923
924 assert(m);
925
926 r = get_timezones(&zones);
927 if (r < 0)
928 return sd_bus_error_set_errnof(error, r, "Failed to read list of time zones: %m");
929
930 r = sd_bus_message_new_method_return(m, &reply);
931 if (r < 0)
932 return r;
933
934 r = sd_bus_message_append_strv(reply, zones);
935 if (r < 0)
936 return r;
937
938 return sd_bus_send(NULL, reply, NULL);
939}
940
40ca29a1
LP
941static const sd_bus_vtable timedate_vtable[] = {
942 SD_BUS_VTABLE_START(0),
943 SD_BUS_PROPERTY("Timezone", "s", NULL, offsetof(Context, zone), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
82d115d9 944 SD_BUS_PROPERTY("LocalRTC", "b", bus_property_get_bool, offsetof(Context, local_rtc), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
5d280742
YW
945 SD_BUS_PROPERTY("CanNTP", "b", property_get_can_ntp, 0, 0),
946 SD_BUS_PROPERTY("NTP", "b", property_get_ntp, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
03cc26dd
LP
947 SD_BUS_PROPERTY("NTPSynchronized", "b", property_get_ntp_sync, 0, 0),
948 SD_BUS_PROPERTY("TimeUSec", "t", property_get_time, 0, 0),
6fc60278 949 SD_BUS_PROPERTY("RTCTimeUSec", "t", property_get_rtc_time, 0, 0),
adacb957
LP
950 SD_BUS_METHOD("SetTime", "xbb", NULL, method_set_time, SD_BUS_VTABLE_UNPRIVILEGED),
951 SD_BUS_METHOD("SetTimezone", "sb", NULL, method_set_timezone, SD_BUS_VTABLE_UNPRIVILEGED),
952 SD_BUS_METHOD("SetLocalRTC", "bbb", NULL, method_set_local_rtc, SD_BUS_VTABLE_UNPRIVILEGED),
953 SD_BUS_METHOD("SetNTP", "bb", NULL, method_set_ntp, SD_BUS_VTABLE_UNPRIVILEGED),
2cf0b2fe 954 SD_BUS_METHOD("ListTimezones", NULL, "as", method_list_timezones, SD_BUS_VTABLE_UNPRIVILEGED),
40ca29a1
LP
955 SD_BUS_VTABLE_END,
956};
957
958static int connect_bus(Context *c, sd_event *event, sd_bus **_bus) {
4afd3348 959 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
f401e48c
LP
960 int r;
961
40ca29a1
LP
962 assert(c);
963 assert(event);
f401e48c
LP
964 assert(_bus);
965
76b54375 966 r = sd_bus_default_system(&bus);
f647962d
MS
967 if (r < 0)
968 return log_error_errno(r, "Failed to get system bus connection: %m");
f401e48c 969
19befb2d 970 r = sd_bus_add_object_vtable(bus, NULL, "/org/freedesktop/timedate1", "org.freedesktop.timedate1", timedate_vtable, c);
f647962d
MS
971 if (r < 0)
972 return log_error_errno(r, "Failed to register object: %m");
f401e48c 973
0c0b9306 974 r = sd_bus_request_name_async(bus, NULL, "org.freedesktop.timedate1", 0, NULL, NULL);
f647962d 975 if (r < 0)
0c0b9306 976 return log_error_errno(r, "Failed to request name: %m");
add10b5a 977
40ca29a1 978 r = sd_bus_attach_event(bus, event, 0);
f647962d
MS
979 if (r < 0)
980 return log_error_errno(r, "Failed to attach bus to event loop: %m");
f401e48c 981
1cc6c93a 982 *_bus = TAKE_PTR(bus);
f401e48c 983
40ca29a1 984 return 0;
f401e48c
LP
985}
986
1f47bc33
YW
987static int run(int argc, char *argv[]) {
988 _cleanup_(context_clear) Context context = {};
4afd3348
LP
989 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
990 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
f401e48c 991 int r;
f401e48c 992
6bf3c61c 993 log_setup_service();
f401e48c 994
4c12626c
LP
995 umask(0022);
996
1f47bc33
YW
997 if (argc != 1)
998 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program takes no arguments.");
f401e48c 999
754f0269
YW
1000 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, -1) >= 0);
1001
afc6adb5 1002 r = sd_event_default(&event);
1f47bc33
YW
1003 if (r < 0)
1004 return log_error_errno(r, "Failed to allocate event loop: %m");
f401e48c 1005
754f0269
YW
1006 (void) sd_event_set_watchdog(event, true);
1007
1008 r = sd_event_add_signal(event, NULL, SIGINT, NULL, NULL);
1f47bc33
YW
1009 if (r < 0)
1010 return log_error_errno(r, "Failed to install SIGINT handler: %m");
754f0269
YW
1011
1012 r = sd_event_add_signal(event, NULL, SIGTERM, NULL, NULL);
1f47bc33
YW
1013 if (r < 0)
1014 return log_error_errno(r, "Failed to install SIGTERM handler: %m");
cde93897 1015
40ca29a1 1016 r = connect_bus(&context, event, &bus);
f401e48c 1017 if (r < 0)
1f47bc33 1018 return r;
f401e48c 1019
dc751688 1020 (void) sd_bus_negotiate_timestamp(bus, true);
2479df30 1021
40ca29a1 1022 r = context_read_data(&context);
1f47bc33
YW
1023 if (r < 0)
1024 return log_error_errno(r, "Failed to read time zone data: %m");
c5f0532f 1025
5d280742
YW
1026 r = context_parse_ntp_services(&context);
1027 if (r < 0)
1f47bc33 1028 return r;
ad740100 1029
37224a5f 1030 r = bus_event_loop_with_idle(event, bus, "org.freedesktop.timedate1", DEFAULT_EXIT_USEC, NULL, NULL);
1f47bc33
YW
1031 if (r < 0)
1032 return log_error_errno(r, "Failed to run event loop: %m");
f401e48c 1033
1f47bc33 1034 return 0;
f401e48c 1035}
1f47bc33
YW
1036
1037DEFINE_MAIN_FUNCTION(run);