]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/timedate/timedated.c
tree-wide: drop license boilerplate
[thirdparty/systemd.git] / src / timedate / timedated.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 This file is part of systemd.
4
5 Copyright 2011 Lennart Poettering
6 ***/
7
8 #include <errno.h>
9 #include <string.h>
10 #include <unistd.h>
11
12 #include "sd-bus.h"
13 #include "sd-event.h"
14 #include "sd-messages.h"
15
16 #include "alloc-util.h"
17 #include "bus-common-errors.h"
18 #include "bus-error.h"
19 #include "bus-util.h"
20 #include "clock-util.h"
21 #include "def.h"
22 #include "fileio-label.h"
23 #include "fs-util.h"
24 #include "path-util.h"
25 #include "selinux-util.h"
26 #include "strv.h"
27 #include "user-util.h"
28 #include "util.h"
29
30 #define NULL_ADJTIME_UTC "0.0 0 0\n0\nUTC\n"
31 #define NULL_ADJTIME_LOCAL "0.0 0 0\n0\nLOCAL\n"
32
33 static BUS_ERROR_MAP_ELF_REGISTER const sd_bus_error_map timedated_errors[] = {
34 SD_BUS_ERROR_MAP("org.freedesktop.timedate1.NoNTPSupport", EOPNOTSUPP),
35 SD_BUS_ERROR_MAP_END
36 };
37
38 typedef struct Context {
39 char *zone;
40 bool local_rtc;
41 bool can_ntp;
42 bool use_ntp;
43 Hashmap *polkit_registry;
44 } Context;
45
46 static void context_free(Context *c) {
47 assert(c);
48
49 free(c->zone);
50 bus_verify_polkit_async_registry_free(c->polkit_registry);
51 }
52
53 static int context_read_data(Context *c) {
54 _cleanup_free_ char *t = NULL;
55 int r;
56
57 assert(c);
58
59 r = get_timezone(&t);
60 if (r == -EINVAL)
61 log_warning_errno(r, "/etc/localtime should be a symbolic link to a time zone data file in /usr/share/zoneinfo/.");
62 else if (r < 0)
63 log_warning_errno(r, "Failed to get target of /etc/localtime: %m");
64
65 free_and_replace(c->zone, t);
66
67 c->local_rtc = clock_is_localtime(NULL) > 0;
68
69 return 0;
70 }
71
72 static int context_write_data_timezone(Context *c) {
73 _cleanup_free_ char *p = NULL;
74 int r = 0;
75
76 assert(c);
77
78 if (isempty(c->zone)) {
79 if (unlink("/etc/localtime") < 0 && errno != ENOENT)
80 r = -errno;
81
82 return r;
83 }
84
85 p = strappend("../usr/share/zoneinfo/", c->zone);
86 if (!p)
87 return log_oom();
88
89 r = symlink_atomic(p, "/etc/localtime");
90 if (r < 0)
91 return r;
92
93 return 0;
94 }
95
96 static int context_write_data_local_rtc(Context *c) {
97 int r;
98 _cleanup_free_ char *s = NULL, *w = NULL;
99
100 assert(c);
101
102 r = read_full_file("/etc/adjtime", &s, NULL);
103 if (r < 0) {
104 if (r != -ENOENT)
105 return r;
106
107 if (!c->local_rtc)
108 return 0;
109
110 w = strdup(NULL_ADJTIME_LOCAL);
111 if (!w)
112 return -ENOMEM;
113 } else {
114 char *p;
115 const char *e = "\n"; /* default if there is less than 3 lines */
116 const char *prepend = "";
117 size_t a, b;
118
119 p = strchrnul(s, '\n');
120 if (*p == '\0')
121 /* only one line, no \n terminator */
122 prepend = "\n0\n";
123 else if (p[1] == '\0') {
124 /* only one line, with \n terminator */
125 ++p;
126 prepend = "0\n";
127 } else {
128 p = strchr(p+1, '\n');
129 if (!p) {
130 /* only two lines, no \n terminator */
131 prepend = "\n";
132 p = s + strlen(s);
133 } else {
134 char *end;
135 /* third line might have a \n terminator or not */
136 p++;
137 end = strchr(p, '\n');
138 /* if we actually have a fourth line, use that as suffix "e", otherwise the default \n */
139 if (end)
140 e = end;
141 }
142 }
143
144 a = p - s;
145 b = strlen(e);
146
147 w = new(char, a + (c->local_rtc ? 5 : 3) + strlen(prepend) + b + 1);
148 if (!w)
149 return -ENOMEM;
150
151 *(char*) mempcpy(stpcpy(stpcpy(mempcpy(w, s, a), prepend), c->local_rtc ? "LOCAL" : "UTC"), e, b) = 0;
152
153 if (streq(w, NULL_ADJTIME_UTC)) {
154 if (unlink("/etc/adjtime") < 0)
155 if (errno != ENOENT)
156 return -errno;
157
158 return 0;
159 }
160 }
161
162 mac_selinux_init();
163 return write_string_file_atomic_label("/etc/adjtime", w);
164 }
165
166 static int context_read_ntp(Context *c, sd_bus *bus) {
167 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
168 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
169 const char *s;
170 int r;
171
172 assert(c);
173 assert(bus);
174
175 r = sd_bus_call_method(
176 bus,
177 "org.freedesktop.systemd1",
178 "/org/freedesktop/systemd1",
179 "org.freedesktop.systemd1.Manager",
180 "GetUnitFileState",
181 &error,
182 &reply,
183 "s",
184 "systemd-timesyncd.service");
185
186 if (r < 0) {
187 if (sd_bus_error_has_name(&error, SD_BUS_ERROR_FILE_NOT_FOUND) ||
188 sd_bus_error_has_name(&error, "org.freedesktop.systemd1.LoadFailed") ||
189 sd_bus_error_has_name(&error, "org.freedesktop.systemd1.NoSuchUnit"))
190 return 0;
191
192 return r;
193 }
194
195 r = sd_bus_message_read(reply, "s", &s);
196 if (r < 0)
197 return r;
198
199 c->can_ntp = true;
200 c->use_ntp = STR_IN_SET(s, "enabled", "enabled-runtime");
201
202 return 0;
203 }
204
205 static int context_start_ntp(sd_bus *bus, sd_bus_error *error, bool enabled) {
206 int r;
207
208 assert(bus);
209 assert(error);
210
211 r = sd_bus_call_method(
212 bus,
213 "org.freedesktop.systemd1",
214 "/org/freedesktop/systemd1",
215 "org.freedesktop.systemd1.Manager",
216 enabled ? "StartUnit" : "StopUnit",
217 error,
218 NULL,
219 "ss",
220 "systemd-timesyncd.service",
221 "replace");
222 if (r < 0) {
223 if (sd_bus_error_has_name(error, SD_BUS_ERROR_FILE_NOT_FOUND) ||
224 sd_bus_error_has_name(error, "org.freedesktop.systemd1.LoadFailed") ||
225 sd_bus_error_has_name(error, "org.freedesktop.systemd1.NoSuchUnit"))
226 return sd_bus_error_set_const(error, "org.freedesktop.timedate1.NoNTPSupport", "NTP not supported.");
227
228 return r;
229 }
230
231 return 0;
232 }
233
234 static int context_enable_ntp(sd_bus *bus, sd_bus_error *error, bool enabled) {
235 int r;
236
237 assert(bus);
238 assert(error);
239
240 if (enabled)
241 r = sd_bus_call_method(
242 bus,
243 "org.freedesktop.systemd1",
244 "/org/freedesktop/systemd1",
245 "org.freedesktop.systemd1.Manager",
246 "EnableUnitFiles",
247 error,
248 NULL,
249 "asbb", 1,
250 "systemd-timesyncd.service",
251 false, true);
252 else
253 r = sd_bus_call_method(
254 bus,
255 "org.freedesktop.systemd1",
256 "/org/freedesktop/systemd1",
257 "org.freedesktop.systemd1.Manager",
258 "DisableUnitFiles",
259 error,
260 NULL,
261 "asb", 1,
262 "systemd-timesyncd.service",
263 false);
264
265 if (r < 0) {
266 if (sd_bus_error_has_name(error, SD_BUS_ERROR_FILE_NOT_FOUND))
267 return sd_bus_error_set_const(error, "org.freedesktop.timedate1.NoNTPSupport", "NTP not supported.");
268
269 return r;
270 }
271
272 r = sd_bus_call_method(
273 bus,
274 "org.freedesktop.systemd1",
275 "/org/freedesktop/systemd1",
276 "org.freedesktop.systemd1.Manager",
277 "Reload",
278 error,
279 NULL,
280 NULL);
281 if (r < 0)
282 return r;
283
284 return 0;
285 }
286
287 static int property_get_rtc_time(
288 sd_bus *bus,
289 const char *path,
290 const char *interface,
291 const char *property,
292 sd_bus_message *reply,
293 void *userdata,
294 sd_bus_error *error) {
295
296 struct tm tm;
297 usec_t t;
298 int r;
299
300 zero(tm);
301 r = clock_get_hwclock(&tm);
302 if (r == -EBUSY) {
303 log_warning("/dev/rtc is busy. Is somebody keeping it open continuously? That's not a good idea... Returning a bogus RTC timestamp.");
304 t = 0;
305 } else if (r == -ENOENT) {
306 log_debug("/dev/rtc not found.");
307 t = 0; /* no RTC found */
308 } else if (r < 0)
309 return sd_bus_error_set_errnof(error, r, "Failed to read RTC: %m");
310 else
311 t = (usec_t) timegm(&tm) * USEC_PER_SEC;
312
313 return sd_bus_message_append(reply, "t", t);
314 }
315
316 static int property_get_time(
317 sd_bus *bus,
318 const char *path,
319 const char *interface,
320 const char *property,
321 sd_bus_message *reply,
322 void *userdata,
323 sd_bus_error *error) {
324
325 return sd_bus_message_append(reply, "t", now(CLOCK_REALTIME));
326 }
327
328 static int property_get_ntp_sync(
329 sd_bus *bus,
330 const char *path,
331 const char *interface,
332 const char *property,
333 sd_bus_message *reply,
334 void *userdata,
335 sd_bus_error *error) {
336
337 return sd_bus_message_append(reply, "b", ntp_synced());
338 }
339
340 static int method_set_timezone(sd_bus_message *m, void *userdata, sd_bus_error *error) {
341 Context *c = userdata;
342 const char *z;
343 int interactive;
344 char *t;
345 int r;
346
347 assert(m);
348 assert(c);
349
350 r = sd_bus_message_read(m, "sb", &z, &interactive);
351 if (r < 0)
352 return r;
353
354 if (!timezone_is_valid(z))
355 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid time zone '%s'", z);
356
357 if (streq_ptr(z, c->zone))
358 return sd_bus_reply_method_return(m, NULL);
359
360 r = bus_verify_polkit_async(
361 m,
362 CAP_SYS_TIME,
363 "org.freedesktop.timedate1.set-timezone",
364 NULL,
365 interactive,
366 UID_INVALID,
367 &c->polkit_registry,
368 error);
369 if (r < 0)
370 return r;
371 if (r == 0)
372 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
373
374 t = strdup(z);
375 if (!t)
376 return -ENOMEM;
377
378 free(c->zone);
379 c->zone = t;
380
381 /* 1. Write new configuration file */
382 r = context_write_data_timezone(c);
383 if (r < 0) {
384 log_error_errno(r, "Failed to set time zone: %m");
385 return sd_bus_error_set_errnof(error, r, "Failed to set time zone: %m");
386 }
387
388 /* 2. Tell the kernel our timezone */
389 clock_set_timezone(NULL);
390
391 if (c->local_rtc) {
392 struct timespec ts;
393 struct tm *tm;
394
395 /* 3. Sync RTC from system clock, with the new delta */
396 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
397 assert_se(tm = localtime(&ts.tv_sec));
398 clock_set_hwclock(tm);
399 }
400
401 log_struct(LOG_INFO,
402 "MESSAGE_ID=" SD_MESSAGE_TIMEZONE_CHANGE_STR,
403 "TIMEZONE=%s", c->zone,
404 LOG_MESSAGE("Changed time zone to '%s'.", c->zone),
405 NULL);
406
407 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m), "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "Timezone", NULL);
408
409 return sd_bus_reply_method_return(m, NULL);
410 }
411
412 static int method_set_local_rtc(sd_bus_message *m, void *userdata, sd_bus_error *error) {
413 int lrtc, fix_system, interactive;
414 Context *c = userdata;
415 struct timespec ts;
416 int r;
417
418 assert(m);
419 assert(c);
420
421 r = sd_bus_message_read(m, "bbb", &lrtc, &fix_system, &interactive);
422 if (r < 0)
423 return r;
424
425 if (lrtc == c->local_rtc)
426 return sd_bus_reply_method_return(m, NULL);
427
428 r = bus_verify_polkit_async(
429 m,
430 CAP_SYS_TIME,
431 "org.freedesktop.timedate1.set-local-rtc",
432 NULL,
433 interactive,
434 UID_INVALID,
435 &c->polkit_registry,
436 error);
437 if (r < 0)
438 return r;
439 if (r == 0)
440 return 1;
441
442 c->local_rtc = lrtc;
443
444 /* 1. Write new configuration file */
445 r = context_write_data_local_rtc(c);
446 if (r < 0) {
447 log_error_errno(r, "Failed to set RTC to local/UTC: %m");
448 return sd_bus_error_set_errnof(error, r, "Failed to set RTC to local/UTC: %m");
449 }
450
451 /* 2. Tell the kernel our timezone */
452 clock_set_timezone(NULL);
453
454 /* 3. Synchronize clocks */
455 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
456
457 if (fix_system) {
458 struct tm tm;
459
460 /* Sync system clock from RTC; first,
461 * initialize the timezone fields of
462 * struct tm. */
463 if (c->local_rtc)
464 tm = *localtime(&ts.tv_sec);
465 else
466 tm = *gmtime(&ts.tv_sec);
467
468 /* Override the main fields of
469 * struct tm, but not the timezone
470 * fields */
471 if (clock_get_hwclock(&tm) >= 0) {
472
473 /* And set the system clock
474 * with this */
475 if (c->local_rtc)
476 ts.tv_sec = mktime(&tm);
477 else
478 ts.tv_sec = timegm(&tm);
479
480 clock_settime(CLOCK_REALTIME, &ts);
481 }
482
483 } else {
484 struct tm *tm;
485
486 /* Sync RTC from system clock */
487 if (c->local_rtc)
488 tm = localtime(&ts.tv_sec);
489 else
490 tm = gmtime(&ts.tv_sec);
491
492 clock_set_hwclock(tm);
493 }
494
495 log_info("RTC configured to %s time.", c->local_rtc ? "local" : "UTC");
496
497 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m), "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "LocalRTC", NULL);
498
499 return sd_bus_reply_method_return(m, NULL);
500 }
501
502 static int method_set_time(sd_bus_message *m, void *userdata, sd_bus_error *error) {
503 int relative, interactive;
504 Context *c = userdata;
505 int64_t utc;
506 struct timespec ts;
507 usec_t start;
508 struct tm* tm;
509 int r;
510
511 assert(m);
512 assert(c);
513
514 if (c->use_ntp)
515 return sd_bus_error_setf(error, BUS_ERROR_AUTOMATIC_TIME_SYNC_ENABLED, "Automatic time synchronization is enabled");
516
517 /* this only gets used if dbus does not provide a timestamp */
518 start = now(CLOCK_MONOTONIC);
519
520 r = sd_bus_message_read(m, "xbb", &utc, &relative, &interactive);
521 if (r < 0)
522 return r;
523
524 if (!relative && utc <= 0)
525 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid absolute time");
526
527 if (relative && utc == 0)
528 return sd_bus_reply_method_return(m, NULL);
529
530 if (relative) {
531 usec_t n, x;
532
533 n = now(CLOCK_REALTIME);
534 x = n + utc;
535
536 if ((utc > 0 && x < n) ||
537 (utc < 0 && x > n))
538 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Time value overflow");
539
540 timespec_store(&ts, x);
541 } else
542 timespec_store(&ts, (usec_t) utc);
543
544 r = bus_verify_polkit_async(
545 m,
546 CAP_SYS_TIME,
547 "org.freedesktop.timedate1.set-time",
548 NULL,
549 interactive,
550 UID_INVALID,
551 &c->polkit_registry,
552 error);
553 if (r < 0)
554 return r;
555 if (r == 0)
556 return 1;
557
558 /* adjust ts for time spent in program */
559 r = sd_bus_message_get_monotonic_usec(m, &start);
560 /* when sd_bus_message_get_monotonic_usec() returns -ENODATA it does not modify &start */
561 if (r < 0 && r != -ENODATA)
562 return r;
563
564 timespec_store(&ts, timespec_load(&ts) + (now(CLOCK_MONOTONIC) - start));
565
566 /* Set system clock */
567 if (clock_settime(CLOCK_REALTIME, &ts) < 0) {
568 log_error_errno(errno, "Failed to set local time: %m");
569 return sd_bus_error_set_errnof(error, errno, "Failed to set local time: %m");
570 }
571
572 /* Sync down to RTC */
573 if (c->local_rtc)
574 tm = localtime(&ts.tv_sec);
575 else
576 tm = gmtime(&ts.tv_sec);
577 clock_set_hwclock(tm);
578
579 log_struct(LOG_INFO,
580 "MESSAGE_ID=" SD_MESSAGE_TIME_CHANGE_STR,
581 "REALTIME="USEC_FMT, timespec_load(&ts),
582 LOG_MESSAGE("Changed local time to %s", ctime(&ts.tv_sec)),
583 NULL);
584
585 return sd_bus_reply_method_return(m, NULL);
586 }
587
588 static int method_set_ntp(sd_bus_message *m, void *userdata, sd_bus_error *error) {
589 int enabled, interactive;
590 Context *c = userdata;
591 int r;
592
593 assert(m);
594 assert(c);
595
596 r = sd_bus_message_read(m, "bb", &enabled, &interactive);
597 if (r < 0)
598 return r;
599
600 if ((bool)enabled == c->use_ntp)
601 return sd_bus_reply_method_return(m, NULL);
602
603 r = bus_verify_polkit_async(
604 m,
605 CAP_SYS_TIME,
606 "org.freedesktop.timedate1.set-ntp",
607 NULL,
608 interactive,
609 UID_INVALID,
610 &c->polkit_registry,
611 error);
612 if (r < 0)
613 return r;
614 if (r == 0)
615 return 1;
616
617 r = context_enable_ntp(sd_bus_message_get_bus(m), error, enabled);
618 if (r < 0)
619 return r;
620
621 r = context_start_ntp(sd_bus_message_get_bus(m), error, enabled);
622 if (r < 0)
623 return r;
624
625 c->use_ntp = enabled;
626 log_info("Set NTP to %sd", enable_disable(enabled));
627
628 (void) sd_bus_emit_properties_changed(sd_bus_message_get_bus(m), "/org/freedesktop/timedate1", "org.freedesktop.timedate1", "NTP", NULL);
629
630 return sd_bus_reply_method_return(m, NULL);
631 }
632
633 static const sd_bus_vtable timedate_vtable[] = {
634 SD_BUS_VTABLE_START(0),
635 SD_BUS_PROPERTY("Timezone", "s", NULL, offsetof(Context, zone), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
636 SD_BUS_PROPERTY("LocalRTC", "b", bus_property_get_bool, offsetof(Context, local_rtc), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
637 SD_BUS_PROPERTY("CanNTP", "b", bus_property_get_bool, offsetof(Context, can_ntp), 0),
638 SD_BUS_PROPERTY("NTP", "b", bus_property_get_bool, offsetof(Context, use_ntp), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
639 SD_BUS_PROPERTY("NTPSynchronized", "b", property_get_ntp_sync, 0, 0),
640 SD_BUS_PROPERTY("TimeUSec", "t", property_get_time, 0, 0),
641 SD_BUS_PROPERTY("RTCTimeUSec", "t", property_get_rtc_time, 0, 0),
642 SD_BUS_METHOD("SetTime", "xbb", NULL, method_set_time, SD_BUS_VTABLE_UNPRIVILEGED),
643 SD_BUS_METHOD("SetTimezone", "sb", NULL, method_set_timezone, SD_BUS_VTABLE_UNPRIVILEGED),
644 SD_BUS_METHOD("SetLocalRTC", "bbb", NULL, method_set_local_rtc, SD_BUS_VTABLE_UNPRIVILEGED),
645 SD_BUS_METHOD("SetNTP", "bb", NULL, method_set_ntp, SD_BUS_VTABLE_UNPRIVILEGED),
646 SD_BUS_VTABLE_END,
647 };
648
649 static int connect_bus(Context *c, sd_event *event, sd_bus **_bus) {
650 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
651 int r;
652
653 assert(c);
654 assert(event);
655 assert(_bus);
656
657 r = sd_bus_default_system(&bus);
658 if (r < 0)
659 return log_error_errno(r, "Failed to get system bus connection: %m");
660
661 r = sd_bus_add_object_vtable(bus, NULL, "/org/freedesktop/timedate1", "org.freedesktop.timedate1", timedate_vtable, c);
662 if (r < 0)
663 return log_error_errno(r, "Failed to register object: %m");
664
665 r = sd_bus_request_name_async(bus, NULL, "org.freedesktop.timedate1", 0, NULL, NULL);
666 if (r < 0)
667 return log_error_errno(r, "Failed to request name: %m");
668
669 r = sd_bus_attach_event(bus, event, 0);
670 if (r < 0)
671 return log_error_errno(r, "Failed to attach bus to event loop: %m");
672
673 *_bus = TAKE_PTR(bus);
674
675 return 0;
676 }
677
678 int main(int argc, char *argv[]) {
679 Context context = {};
680 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
681 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
682 int r;
683
684 log_set_target(LOG_TARGET_AUTO);
685 log_parse_environment();
686 log_open();
687
688 umask(0022);
689
690 if (argc != 1) {
691 log_error("This program takes no arguments.");
692 r = -EINVAL;
693 goto finish;
694 }
695
696 r = sd_event_default(&event);
697 if (r < 0) {
698 log_error_errno(r, "Failed to allocate event loop: %m");
699 goto finish;
700 }
701
702 sd_event_set_watchdog(event, true);
703
704 r = connect_bus(&context, event, &bus);
705 if (r < 0)
706 goto finish;
707
708 (void) sd_bus_negotiate_timestamp(bus, true);
709
710 r = context_read_data(&context);
711 if (r < 0) {
712 log_error_errno(r, "Failed to read time zone data: %m");
713 goto finish;
714 }
715
716 r = context_read_ntp(&context, bus);
717 if (r < 0) {
718 log_error_errno(r, "Failed to determine whether NTP is enabled: %m");
719 goto finish;
720 }
721
722 r = bus_event_loop_with_idle(event, bus, "org.freedesktop.timedate1", DEFAULT_EXIT_USEC, NULL, NULL);
723 if (r < 0) {
724 log_error_errno(r, "Failed to run event loop: %m");
725 goto finish;
726 }
727
728 finish:
729 context_free(&context);
730
731 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
732 }