]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/timedate/timedated.c
Merge pull request #11827 from keszybz/pkgconfig-variables
[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
b4356b57
YW
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
5d280742
YW
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
537static 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
b4356b57
YW
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
5d280742
YW
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
19070062 566static int method_set_timezone(sd_bus_message *m, void *userdata, sd_bus_error *error) {
40ca29a1 567 Context *c = userdata;
2c3def62 568 int interactive, r;
40ca29a1 569 const char *z;
c5f0532f 570
7e9cf16c
LP
571 assert(m);
572 assert(c);
573
40ca29a1
LP
574 r = sd_bus_message_read(m, "sb", &z, &interactive);
575 if (r < 0)
ebcf1f97 576 return r;
c5f0532f 577
089fb865 578 if (!timezone_is_valid(z, LOG_DEBUG))
ebcf1f97 579 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid time zone '%s'", z);
ac7019f3 580
539a68e0 581 if (streq_ptr(z, c->zone))
df2d202e 582 return sd_bus_reply_method_return(m, NULL);
c5f0532f 583
c529695e
LP
584 r = bus_verify_polkit_async(
585 m,
586 CAP_SYS_TIME,
587 "org.freedesktop.timedate1.set-timezone",
403ed0e5 588 NULL,
c529695e
LP
589 interactive,
590 UID_INVALID,
591 &c->polkit_registry,
592 error);
40ca29a1 593 if (r < 0)
ebcf1f97 594 return r;
40ca29a1 595 if (r == 0)
6fc60278 596 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
6ffe5e37 597
539a68e0
YW
598 r = free_and_strdup(&c->zone, z);
599 if (r < 0)
600 return r;
601
40ca29a1
LP
602 /* 1. Write new configuration file */
603 r = context_write_data_timezone(c);
604 if (r < 0) {
da927ba9 605 log_error_errno(r, "Failed to set time zone: %m");
10a87006 606 return sd_bus_error_set_errnof(error, r, "Failed to set time zone: %m");
40ca29a1 607 }
6ffe5e37 608
8a50b96f
LP
609 /* 2. Make glibc notice the new timezone */
610 tzset();
611
612 /* 3. Tell the kernel our timezone */
2a7ff45f
LP
613 r = clock_set_timezone(NULL);
614 if (r < 0)
615 log_debug_errno(r, "Failed to tell kernel about timezone, ignoring: %m");
6ffe5e37 616
40ca29a1
LP
617 if (c->local_rtc) {
618 struct timespec ts;
e0f691e1 619 struct tm tm;
c5f0532f 620
8a50b96f 621 /* 4. Sync RTC from system clock, with the new delta */
40ca29a1 622 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
e0f691e1 623 assert_se(localtime_r(&ts.tv_sec, &tm));
2a7ff45f 624
e0f691e1 625 r = clock_set_hwclock(&tm);
2a7ff45f
LP
626 if (r < 0)
627 log_debug_errno(r, "Failed to sync time to hardware clock, ignoring: %m");
40ca29a1 628 }
c5f0532f 629
40ca29a1 630 log_struct(LOG_INFO,
2b044526 631 "MESSAGE_ID=" SD_MESSAGE_TIMEZONE_CHANGE_STR,
40ca29a1 632 "TIMEZONE=%s", c->zone,
8a50b96f
LP
633 "TIMEZONE_SHORTNAME=%s", tzname[daylight],
634 "DAYLIGHT=%i", daylight,
a1230ff9 635 LOG_MESSAGE("Changed time zone to '%s' (%s).", c->zone, tzname[daylight]));
c5f0532f 636
19070062 637 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m), "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "Timezone", NULL);
c5f0532f 638
df2d202e 639 return sd_bus_reply_method_return(m, NULL);
c5f0532f
LP
640}
641
19070062 642static int method_set_local_rtc(sd_bus_message *m, void *userdata, sd_bus_error *error) {
102d8f81 643 int lrtc, fix_system, interactive;
40ca29a1
LP
644 Context *c = userdata;
645 struct timespec ts;
f401e48c
LP
646 int r;
647
40ca29a1
LP
648 assert(m);
649 assert(c);
f401e48c 650
40ca29a1
LP
651 r = sd_bus_message_read(m, "bbb", &lrtc, &fix_system, &interactive);
652 if (r < 0)
ebcf1f97 653 return r;
f401e48c 654
40ca29a1 655 if (lrtc == c->local_rtc)
df2d202e 656 return sd_bus_reply_method_return(m, NULL);
f401e48c 657
c529695e
LP
658 r = bus_verify_polkit_async(
659 m,
660 CAP_SYS_TIME,
661 "org.freedesktop.timedate1.set-local-rtc",
403ed0e5 662 NULL,
c529695e
LP
663 interactive,
664 UID_INVALID,
665 &c->polkit_registry,
666 error);
40ca29a1 667 if (r < 0)
ebcf1f97 668 return r;
40ca29a1
LP
669 if (r == 0)
670 return 1;
f401e48c 671
40ca29a1 672 c->local_rtc = lrtc;
f401e48c 673
40ca29a1
LP
674 /* 1. Write new configuration file */
675 r = context_write_data_local_rtc(c);
676 if (r < 0) {
da927ba9 677 log_error_errno(r, "Failed to set RTC to local/UTC: %m");
10a87006 678 return sd_bus_error_set_errnof(error, r, "Failed to set RTC to local/UTC: %m");
40ca29a1 679 }
f401e48c 680
40ca29a1 681 /* 2. Tell the kernel our timezone */
2a7ff45f
LP
682 r = clock_set_timezone(NULL);
683 if (r < 0)
684 log_debug_errno(r, "Failed to tell kernel about timezone, ignoring: %m");
f401e48c 685
40ca29a1
LP
686 /* 3. Synchronize clocks */
687 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
f401e48c 688
40ca29a1
LP
689 if (fix_system) {
690 struct tm tm;
f401e48c 691
2a7ff45f 692 /* Sync system clock from RTC; first, initialize the timezone fields of struct tm. */
40ca29a1 693 if (c->local_rtc)
e46acb79 694 localtime_r(&ts.tv_sec, &tm);
40ca29a1 695 else
e46acb79 696 gmtime_r(&ts.tv_sec, &tm);
72edcff5 697
2a7ff45f
LP
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 */
40ca29a1
LP
704 if (c->local_rtc)
705 ts.tv_sec = mktime(&tm);
706 else
707 ts.tv_sec = timegm(&tm);
2076cf88 708
2a7ff45f
LP
709 if (clock_settime(CLOCK_REALTIME, &ts) < 0)
710 log_debug_errno(errno, "Failed to update system clock, ignoring: %m");
f401e48c
LP
711 }
712
40ca29a1 713 } else {
e46acb79 714 struct tm tm;
f401e48c 715
40ca29a1
LP
716 /* Sync RTC from system clock */
717 if (c->local_rtc)
e46acb79 718 localtime_r(&ts.tv_sec, &tm);
40ca29a1 719 else
e46acb79 720 gmtime_r(&ts.tv_sec, &tm);
2076cf88 721
e46acb79 722 r = clock_set_hwclock(&tm);
2a7ff45f
LP
723 if (r < 0)
724 log_debug_errno(r, "Failed to sync time to hardware clock, ignoring: %m");
40ca29a1 725 }
2076cf88 726
40ca29a1 727 log_info("RTC configured to %s time.", c->local_rtc ? "local" : "UTC");
2076cf88 728
19070062 729 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m), "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "LocalRTC", NULL);
2076cf88 730
df2d202e 731 return sd_bus_reply_method_return(m, NULL);
40ca29a1 732}
2076cf88 733
19070062 734static int method_set_time(sd_bus_message *m, void *userdata, sd_bus_error *error) {
5d280742
YW
735 sd_bus *bus = sd_bus_message_get_bus(m);
736 int relative, interactive, r;
40ca29a1
LP
737 Context *c = userdata;
738 int64_t utc;
739 struct timespec ts;
2479df30 740 usec_t start;
e46acb79 741 struct tm tm;
2076cf88 742
40ca29a1
LP
743 assert(m);
744 assert(c);
2076cf88 745
b4356b57
YW
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
5d280742
YW
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)
e9e5ea88 754 return sd_bus_error_set(error, BUS_ERROR_AUTOMATIC_TIME_SYNC_ENABLED, "Automatic time synchronization is enabled");
82d115d9 755
6829cec4
SL
756 /* this only gets used if dbus does not provide a timestamp */
757 start = now(CLOCK_MONOTONIC);
758
40ca29a1
LP
759 r = sd_bus_message_read(m, "xbb", &utc, &relative, &interactive);
760 if (r < 0)
ebcf1f97 761 return r;
2076cf88 762
40ca29a1 763 if (!relative && utc <= 0)
e9e5ea88 764 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid absolute time");
2076cf88 765
40ca29a1 766 if (relative && utc == 0)
df2d202e 767 return sd_bus_reply_method_return(m, NULL);
2076cf88 768
40ca29a1
LP
769 if (relative) {
770 usec_t n, x;
f401e48c 771
40ca29a1
LP
772 n = now(CLOCK_REALTIME);
773 x = n + utc;
f401e48c 774
40ca29a1
LP
775 if ((utc > 0 && x < n) ||
776 (utc < 0 && x > n))
e9e5ea88 777 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Time value overflow");
f401e48c 778
40ca29a1
LP
779 timespec_store(&ts, x);
780 } else
781 timespec_store(&ts, (usec_t) utc);
2076cf88 782
c529695e
LP
783 r = bus_verify_polkit_async(
784 m,
785 CAP_SYS_TIME,
786 "org.freedesktop.timedate1.set-time",
403ed0e5 787 NULL,
c529695e
LP
788 interactive,
789 UID_INVALID,
790 &c->polkit_registry,
791 error);
40ca29a1 792 if (r < 0)
ebcf1f97 793 return r;
40ca29a1
LP
794 if (r == 0)
795 return 1;
796
2479df30
SL
797 /* adjust ts for time spent in program */
798 r = sd_bus_message_get_monotonic_usec(m, &start);
6829cec4 799 /* when sd_bus_message_get_monotonic_usec() returns -ENODATA it does not modify &start */
2479df30
SL
800 if (r < 0 && r != -ENODATA)
801 return r;
6829cec4
SL
802
803 timespec_store(&ts, timespec_load(&ts) + (now(CLOCK_MONOTONIC) - start));
2479df30 804
40ca29a1
LP
805 /* Set system clock */
806 if (clock_settime(CLOCK_REALTIME, &ts) < 0) {
56f64d95 807 log_error_errno(errno, "Failed to set local time: %m");
ebcf1f97 808 return sd_bus_error_set_errnof(error, errno, "Failed to set local time: %m");
40ca29a1 809 }
2076cf88 810
40ca29a1
LP
811 /* Sync down to RTC */
812 if (c->local_rtc)
e46acb79 813 localtime_r(&ts.tv_sec, &tm);
40ca29a1 814 else
e46acb79 815 gmtime_r(&ts.tv_sec, &tm);
2a7ff45f 816
e46acb79 817 r = clock_set_hwclock(&tm);
2a7ff45f
LP
818 if (r < 0)
819 log_debug_errno(r, "Failed to update hardware clock, ignoring: %m");
f401e48c 820
40ca29a1 821 log_struct(LOG_INFO,
2b044526 822 "MESSAGE_ID=" SD_MESSAGE_TIME_CHANGE_STR,
de0671ee 823 "REALTIME="USEC_FMT, timespec_load(&ts),
a1230ff9 824 LOG_MESSAGE("Changed local time to %s", ctime(&ts.tv_sec)));
f401e48c 825
df2d202e 826 return sd_bus_reply_method_return(m, NULL);
40ca29a1 827}
f401e48c 828
19070062 829static int method_set_ntp(sd_bus_message *m, void *userdata, sd_bus_error *error) {
cf3872bd 830 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
5d280742 831 sd_bus *bus = sd_bus_message_get_bus(m);
40ca29a1 832 Context *c = userdata;
5d280742
YW
833 UnitStatusInfo *u;
834 int enable, interactive, q, r;
f401e48c 835
19070062 836 assert(m);
5d280742 837 assert(bus);
19070062
LP
838 assert(c);
839
5d280742 840 r = sd_bus_message_read(m, "bb", &enable, &interactive);
40ca29a1 841 if (r < 0)
ebcf1f97 842 return r;
f401e48c 843
5d280742
YW
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");
f401e48c 850
c529695e
LP
851 r = bus_verify_polkit_async(
852 m,
853 CAP_SYS_TIME,
854 "org.freedesktop.timedate1.set-ntp",
403ed0e5 855 NULL,
c529695e
LP
856 interactive,
857 UID_INVALID,
858 &c->polkit_registry,
859 error);
40ca29a1 860 if (r < 0)
ebcf1f97 861 return r;
40ca29a1
LP
862 if (r == 0)
863 return 1;
f401e48c 864
cf3872bd
YW
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
5d280742
YW
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
cf3872bd 891 q = unit_start_or_stop(u, bus, error, enable);
5d280742
YW
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
cf3872bd 905 r = unit_start_or_stop(u, bus, error, enable);
5d280742
YW
906 break;
907 }
908
3af0a96c 909 else
5d280742
YW
910 LIST_FOREACH(units, u, c->units) {
911 if (!streq(u->load_state, "loaded") ||
912 !streq(u->unit_file_state, "enabled"))
913 continue;
914
cf3872bd 915 r = unit_start_or_stop(u, bus, error, enable);
5d280742
YW
916 break;
917 }
40ca29a1 918
40ca29a1 919 if (r < 0)
ebcf1f97 920 return r;
f401e48c 921
cf3872bd
YW
922 if (slot)
923 c->slot_job_removed = TAKE_PTR(slot);
924
5d280742 925 log_info("Set NTP to %sd", enable_disable(enable));
f401e48c 926
df2d202e 927 return sd_bus_reply_method_return(m, NULL);
f401e48c
LP
928}
929
2cf0b2fe
NT
930static 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
40ca29a1
LP
952static 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),
82d115d9 955 SD_BUS_PROPERTY("LocalRTC", "b", bus_property_get_bool, offsetof(Context, local_rtc), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
5d280742
YW
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),
03cc26dd
LP
958 SD_BUS_PROPERTY("NTPSynchronized", "b", property_get_ntp_sync, 0, 0),
959 SD_BUS_PROPERTY("TimeUSec", "t", property_get_time, 0, 0),
6fc60278 960 SD_BUS_PROPERTY("RTCTimeUSec", "t", property_get_rtc_time, 0, 0),
adacb957
LP
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),
2cf0b2fe 965 SD_BUS_METHOD("ListTimezones", NULL, "as", method_list_timezones, SD_BUS_VTABLE_UNPRIVILEGED),
40ca29a1
LP
966 SD_BUS_VTABLE_END,
967};
968
969static int connect_bus(Context *c, sd_event *event, sd_bus **_bus) {
4afd3348 970 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
f401e48c
LP
971 int r;
972
40ca29a1
LP
973 assert(c);
974 assert(event);
f401e48c
LP
975 assert(_bus);
976
76b54375 977 r = sd_bus_default_system(&bus);
f647962d
MS
978 if (r < 0)
979 return log_error_errno(r, "Failed to get system bus connection: %m");
f401e48c 980
19befb2d 981 r = sd_bus_add_object_vtable(bus, NULL, "/org/freedesktop/timedate1", "org.freedesktop.timedate1", timedate_vtable, c);
f647962d
MS
982 if (r < 0)
983 return log_error_errno(r, "Failed to register object: %m");
f401e48c 984
0c0b9306 985 r = sd_bus_request_name_async(bus, NULL, "org.freedesktop.timedate1", 0, NULL, NULL);
f647962d 986 if (r < 0)
0c0b9306 987 return log_error_errno(r, "Failed to request name: %m");
add10b5a 988
40ca29a1 989 r = sd_bus_attach_event(bus, event, 0);
f647962d
MS
990 if (r < 0)
991 return log_error_errno(r, "Failed to attach bus to event loop: %m");
f401e48c 992
1cc6c93a 993 *_bus = TAKE_PTR(bus);
f401e48c 994
40ca29a1 995 return 0;
f401e48c
LP
996}
997
1f47bc33
YW
998static int run(int argc, char *argv[]) {
999 _cleanup_(context_clear) Context context = {};
4afd3348
LP
1000 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
1001 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
f401e48c 1002 int r;
f401e48c 1003
6bf3c61c 1004 log_setup_service();
f401e48c 1005
4c12626c
LP
1006 umask(0022);
1007
1f47bc33
YW
1008 if (argc != 1)
1009 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program takes no arguments.");
f401e48c 1010
754f0269
YW
1011 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, -1) >= 0);
1012
afc6adb5 1013 r = sd_event_default(&event);
1f47bc33
YW
1014 if (r < 0)
1015 return log_error_errno(r, "Failed to allocate event loop: %m");
f401e48c 1016
754f0269
YW
1017 (void) sd_event_set_watchdog(event, true);
1018
1019 r = sd_event_add_signal(event, NULL, SIGINT, NULL, NULL);
1f47bc33
YW
1020 if (r < 0)
1021 return log_error_errno(r, "Failed to install SIGINT handler: %m");
754f0269
YW
1022
1023 r = sd_event_add_signal(event, NULL, SIGTERM, NULL, NULL);
1f47bc33
YW
1024 if (r < 0)
1025 return log_error_errno(r, "Failed to install SIGTERM handler: %m");
cde93897 1026
40ca29a1 1027 r = connect_bus(&context, event, &bus);
f401e48c 1028 if (r < 0)
1f47bc33 1029 return r;
f401e48c 1030
dc751688 1031 (void) sd_bus_negotiate_timestamp(bus, true);
2479df30 1032
40ca29a1 1033 r = context_read_data(&context);
1f47bc33
YW
1034 if (r < 0)
1035 return log_error_errno(r, "Failed to read time zone data: %m");
c5f0532f 1036
5d280742
YW
1037 r = context_parse_ntp_services(&context);
1038 if (r < 0)
1f47bc33 1039 return r;
ad740100 1040
37224a5f 1041 r = bus_event_loop_with_idle(event, bus, "org.freedesktop.timedate1", DEFAULT_EXIT_USEC, NULL, NULL);
1f47bc33
YW
1042 if (r < 0)
1043 return log_error_errno(r, "Failed to run event loop: %m");
f401e48c 1044
1f47bc33 1045 return 0;
f401e48c 1046}
1f47bc33
YW
1047
1048DEFINE_MAIN_FUNCTION(run);