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