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