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