Debian Codegraph @

src/timedate/timedatectl.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <locale.h>
4 #include <math.h>
5 #include <stdlib.h>
6
7 #include "sd-bus.h"
8 #include "sd-event.h"
9
10 #include "alloc-util.h"
11 #include "build.h"
12 #include "bus-error.h"
13 #include "bus-locator.h"
14 #include "bus-map-properties.h"
15 #include "bus-print-properties.h"
16 #include "bus-util.h"
17 #include "constants.h"
18 #include "format-table.h"
19 #include "in-addr-util.h"
20 #include "log.h"
21 #include "main-func.h"
22 #include "options.h"
23 #include "pager.h"
24 #include "parse-argument.h"
25 #include "parse-util.h"
26 #include "polkit-agent.h"
27 #include "pretty-print.h"
28 #include "runtime-scope.h"
29 #include "sparse-endian.h"
30 #include "string-table.h"
31 #include "string-util.h"
32 #include "strv.h"
33 #include "terminal-util.h"
34 #include "time-util.h"
35 #include "verbs.h"
36
37 static PagerFlags arg_pager_flags = 0;
38 static bool arg_ask_password = true;
39 static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
40 static const char *arg_host = NULL;
41 static bool arg_adjust_system_clock = false;
42 static bool arg_monitor = false;
43 static char **arg_property = NULL;
44 static BusPrintPropertyFlags arg_print_flags = 0;
45
46 typedef struct StatusInfo {
47 usec_t time;
48 const char *timezone;
49
50 usec_t rtc_time;
51 bool rtc_local;
52
53 bool ntp_capable;
54 bool ntp_active;
55 bool ntp_synced;
56 } StatusInfo;
57
58 static int print_status_info(const StatusInfo *i) {
59 _cleanup_(table_unrefp) Table *table = NULL;
60 char a[LINE_MAX];
61 TableCell *cell;
62 struct tm tm;
63 usec_t t = USEC_INFINITY;
64 size_t n;
65 int r;
66
67 assert(i);
68
69 table = table_new_vertical();
70 if (!table)
71 return log_oom();
72
73 assert_se(cell = table_get_cell(table, 0, 0));
74 (void) table_set_ellipsize_percent(table, cell, 100);
75
76 assert_se(cell = table_get_cell(table, 0, 1));
77 (void) table_set_ellipsize_percent(table, cell, 100);
78
79 /* Save the old $TZ */
80 SAVE_TIMEZONE;
81
82 /* Set the new $TZ */
83 if (setenv("TZ", isempty(i->timezone) ? "UTC" : i->timezone, /* overwrite= */ true) < 0)
84 log_warning_errno(errno, "Failed to set TZ environment variable, ignoring: %m");
85 else
86 tzset();
87
88 if (timestamp_is_set(i->time))
89 t = i->time;
90 else if (IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_MACHINE))
91 t = now(CLOCK_REALTIME);
92 else
93 log_warning("Could not get time from timedated and not operating locally, ignoring.");
94
95 if (timestamp_is_set(t)) {
96 r = localtime_or_gmtime_usec(t, /* utc= */ false, &tm);
97 if (r < 0) {
98 log_warning_errno(r, "Failed to convert system time to local time, ignoring: %m");
99 n = 0;
100 } else
101 n = strftime(a, sizeof a, "%a %Y-%m-%d %H:%M:%S %Z", &tm);
102 } else
103 n = 0;
104 r = table_add_many(table,
105 TABLE_FIELD, "Local time",
106 TABLE_STRING, n > 0 ? a : "n/a");
107 if (r < 0)
108 return table_log_add_error(r);
109
110 if (timestamp_is_set(t)) {
111 r = localtime_or_gmtime_usec(t, /* utc= */ true, &tm);
112 if (r < 0) {
113 log_warning_errno(r, "Failed to convert system time to universal time, ignoring: %m");
114 n = 0;
115 } else
116 n = strftime(a, sizeof a, "%a %Y-%m-%d %H:%M:%S UTC", &tm);
117 } else
118 n = 0;
119 r = table_add_many(table,
120 TABLE_FIELD, "Universal time",
121 TABLE_STRING, n > 0 ? a : "n/a");
122 if (r < 0)
123 return table_log_add_error(r);
124
125 if (timestamp_is_set(i->rtc_time)) {
126 r = localtime_or_gmtime_usec(i->rtc_time, /* utc= */ true, &tm);
127 if (r < 0) {
128 log_warning_errno(r, "Failed to convert RTC time to universal time, ignoring: %m");
129 n = 0;
130 } else
131 n = strftime(a, sizeof a, "%a %Y-%m-%d %H:%M:%S", &tm);
132 } else
133 n = 0;
134 r = table_add_many(table,
135 TABLE_FIELD, "RTC time",
136 TABLE_STRING, n > 0 ? a : "n/a");
137 if (r < 0)
138 return table_log_add_error(r);
139
140 r = table_add_cell(table, NULL, TABLE_FIELD, "Time zone");
141 if (r < 0)
142 return table_log_add_error(r);
143 if (timestamp_is_set(t)) {
144 r = localtime_or_gmtime_usec(t, /* utc= */ false, &tm);
145 if (r < 0) {
146 log_warning_errno(r, "Failed to determine timezone from system time, ignoring: %m");
147 n = 0;
148 } else
149 n = strftime(a, sizeof a, "%Z, %z", &tm);
150 } else
151 n = 0;
152 r = table_add_cell_stringf(table, NULL, "%s (%s)", strna(i->timezone), n > 0 ? a : "n/a");
153 if (r < 0)
154 return table_log_add_error(r);
155
156 r = table_add_many(table,
157 TABLE_FIELD, "System clock synchronized",
158 TABLE_BOOLEAN, i->ntp_synced,
159 TABLE_FIELD, "NTP service",
160 TABLE_STRING, i->ntp_capable ? (i->ntp_active ? "active" : "inactive") : "n/a",
161 TABLE_FIELD, "RTC in local TZ",
162 TABLE_BOOLEAN, i->rtc_local);
163 if (r < 0)
164 return table_log_add_error(r);
165
166 r = table_print_or_warn(table);
167 if (r < 0)
168 return r;
169
170 if (i->rtc_local) {
171 fflush(stdout);
172 log_warning(" \nWarning: The system is configured to read the RTC time in the local time zone.\n"
173 " This mode cannot be fully supported. It will create various problems\n"
174 " with time zone changes and daylight saving time adjustments. The RTC\n"
175 " time is never updated, it relies on external facilities to maintain it.\n"
176 " If at all possible, use RTC in UTC by calling\n"
177 " 'timedatectl set-local-rtc 0'.\n");
178 }
179
180 return 0;
181 }
182
183 VERB_DEFAULT_NOARG(verb_status, "status", "Show current time settings");
184 static int verb_status(int argc, char *argv[], uintptr_t _data, void *userdata) {
185 StatusInfo info = {};
186 static const struct bus_properties_map map[] = {
187 { "Timezone", "s", NULL, offsetof(StatusInfo, timezone) },
188 { "LocalRTC", "b", NULL, offsetof(StatusInfo, rtc_local) },
189 { "NTP", "b", NULL, offsetof(StatusInfo, ntp_active) },
190 { "CanNTP", "b", NULL, offsetof(StatusInfo, ntp_capable) },
191 { "NTPSynchronized", "b", NULL, offsetof(StatusInfo, ntp_synced) },
192 { "TimeUSec", "t", NULL, offsetof(StatusInfo, time) },
193 { "RTCTimeUSec", "t", NULL, offsetof(StatusInfo, rtc_time) },
194 {}
195 };
196
197 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
198 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
199 sd_bus *bus = ASSERT_PTR(userdata);
200 int r;
201
202 r = bus_map_all_properties(bus,
203 "org.freedesktop.timedate1",
204 "/org/freedesktop/timedate1",
205 map,
206 BUS_MAP_BOOLEAN_AS_BOOL,
207 &error,
208 &m,
209 &info);
210 if (r < 0)
211 return log_error_errno(r, "Failed to query server: %s", bus_error_message(&error, r));
212
213 return print_status_info(&info);
214 }
215
216 VERB_NOARG(verb_show, "show", "Show properties of systemd-timedated");
217 static int verb_show(int argc, char *argv[], uintptr_t _data, void *userdata) {
218 sd_bus *bus = ASSERT_PTR(userdata);
219 int r;
220
221 r = bus_print_all_properties(bus,
222 "org.freedesktop.timedate1",
223 "/org/freedesktop/timedate1",
224 NULL,
225 arg_property,
226 arg_print_flags,
227 NULL);
228 if (r < 0)
229 return bus_log_parse_error(r);
230
231 return 0;
232 }
233
234 VERB(verb_set_time, "set-time", "TIME", 2, 2, 0, "Set system time");
235 static int verb_set_time(int argc, char *argv[], uintptr_t _data, void *userdata) {
236 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
237 sd_bus *bus = userdata;
238 usec_t t;
239 int r;
240
241 (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
242
243 r = parse_timestamp(argv[1], &t);
244 if (r < 0)
245 return log_error_errno(r, "Failed to parse time specification '%s': %m", argv[1]);
246
247 r = bus_call_method(
248 bus,
249 bus_timedate,
250 "SetTime",
251 &error,
252 NULL,
253 "xbb", (int64_t) t, false, arg_ask_password);
254 if (r < 0)
255 return log_error_errno(r, "Failed to set time: %s", bus_error_message(&error, r));
256
257 return 0;
258 }
259
260 VERB(verb_set_timezone, "set-timezone", "ZONE", 2, 2, 0, "Set system time zone");
261 static int verb_set_timezone(int argc, char *argv[], uintptr_t _data, void *userdata) {
262 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
263 sd_bus *bus = userdata;
264 int r;
265
266 (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
267
268 r = bus_call_method(bus, bus_timedate, "SetTimezone", &error, NULL, "sb", argv[1], arg_ask_password);
269 if (r < 0)
270 return log_error_errno(r, "Failed to set time zone: %s", bus_error_message(&error, r));
271
272 return 0;
273 }
274
275 VERB_NOARG(verb_list_timezones, "list-timezones", "Show known time zones");
276 static int verb_list_timezones(int argc, char *argv[], uintptr_t _data, void *userdata) {
277 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
278 sd_bus *bus = userdata;
279 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
280 int r;
281 _cleanup_strv_free_ char **zones = NULL;
282
283 r = bus_call_method(bus, bus_timedate, "ListTimezones", &error, &reply, NULL);
284 if (r < 0)
285 return log_error_errno(r, "Failed to request list of time zones: %s",
286 bus_error_message(&error, r));
287
288 r = sd_bus_message_read_strv(reply, &zones);
289 if (r < 0)
290 return bus_log_parse_error(r);
291
292 pager_open(arg_pager_flags);
293 strv_print(zones);
294
295 return 0;
296 }
297
298 VERB(verb_set_local_rtc, "set-local-rtc", "BOOL", 2, 2, 0, "Control whether RTC is in local time");
299 static int verb_set_local_rtc(int argc, char *argv[], uintptr_t _data, void *userdata) {
300 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
301 sd_bus *bus = userdata;
302 int r, b;
303
304 (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
305
306 b = parse_boolean(argv[1]);
307 if (b < 0)
308 return log_error_errno(b, "Failed to parse local RTC setting '%s': %m", argv[1]);
309
310 if (b == 1)
311 log_warning("Warning: The system is now being configured to read the RTC time in the local time zone\n"
312 " This mode cannot be fully supported. It will create various problems\n"
313 " with time zone changes and daylight saving time adjustments. The RTC\n"
314 " time is never updated, it relies on external facilities to maintain it.\n"
315 " If at all possible, use RTC in UTC");
316
317 r = bus_call_method(
318 bus,
319 bus_timedate,
320 "SetLocalRTC",
321 &error,
322 NULL,
323 "bbb", b, arg_adjust_system_clock, arg_ask_password);
324 if (r < 0)
325 return log_error_errno(r, "Failed to set local RTC: %s", bus_error_message(&error, r));
326
327 return 0;
328 }
329
330 VERB(verb_set_ntp, "set-ntp", "BOOL", 2, 2, 0, "Enable or disable network time synchronization");
331 static int verb_set_ntp(int argc, char *argv[], uintptr_t _data, void *userdata) {
332 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
333 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
334 sd_bus *bus = userdata;
335 int b, r;
336
337 (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
338
339 b = parse_boolean(argv[1]);
340 if (b < 0)
341 return log_error_errno(b, "Failed to parse NTP setting '%s': %m", argv[1]);
342
343 r = bus_message_new_method_call(bus, &m, bus_timedate, "SetNTP");
344 if (r < 0)
345 return bus_log_create_error(r);
346
347 r = sd_bus_message_append(m, "bb", b, arg_ask_password);
348 if (r < 0)
349 return bus_log_create_error(r);
350
351 /* Reloading the daemon may take long, hence set a longer timeout here */
352 r = sd_bus_call(bus, m, DAEMON_RELOAD_TIMEOUT_SEC, &error, NULL);
353 if (r < 0)
354 return log_error_errno(r, "Failed to set ntp: %s", bus_error_message(&error, r));
355
356 return 0;
357 }
358
359 typedef struct NTPStatusInfo {
360 const char *server_name;
361 char *server_address;
362 usec_t poll_interval, poll_max, poll_min;
363 usec_t root_distance_max;
364
365 uint32_t leap, version, mode, stratum;
366 int32_t precision;
367 usec_t root_delay, root_dispersion;
368 union {
369 char str[5];
370 uint32_t val;
371 } reference;
372 usec_t origin, recv, trans, dest;
373
374 bool spike;
375 uint64_t packet_count;
376 usec_t jitter;
377
378 int64_t freq;
379 } NTPStatusInfo;
380
381 static void ntp_status_info_clear(NTPStatusInfo *p) {
382 p->server_address = mfree(p->server_address);
383 }
384
385 static const char * const ntp_leap_table[4] = {
386 [0] = "normal",
387 [1] = "last minute of the day has 61 seconds",
388 [2] = "last minute of the day has 59 seconds",
389 [3] = "not synchronized",
390 };
391
392 DISABLE_WARNING_TYPE_LIMITS;
393 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(ntp_leap, uint32_t);
394 REENABLE_WARNING;
395
396 static int print_ntp_status_info(NTPStatusInfo *i) {
397 usec_t delay, t14, t23, offset, root_distance;
398 _cleanup_(table_unrefp) Table *table = NULL;
399 bool offset_sign;
400 TableCell *cell;
401 int r;
402
403 assert(i);
404
405 table = table_new_vertical();
406 if (!table)
407 return log_oom();
408
409 assert_se(cell = table_get_cell(table, 0, 0));
410 (void) table_set_ellipsize_percent(table, cell, 100);
411
412 assert_se(cell = table_get_cell(table, 0, 1));
413 (void) table_set_ellipsize_percent(table, cell, 100);
414
415 /*
416 * "Timestamp Name ID When Generated
417 * ------------------------------------------------------------
418 * Originate Timestamp T1 time request sent by client
419 * Receive Timestamp T2 time request received by server
420 * Transmit Timestamp T3 time reply sent by server
421 * Destination Timestamp T4 time reply received by client
422 *
423 * The round-trip delay, d, and system clock offset, t, are defined as:
424 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2"
425 */
426
427 r = table_add_cell(table, NULL, TABLE_FIELD, "Server");
428 if (r < 0)
429 return table_log_add_error(r);
430
431 r = table_add_cell_stringf(table, NULL, "%s (%s)", strna(i->server_address), strna(i->server_name));
432 if (r < 0)
433 return table_log_add_error(r);
434
435 r = table_add_cell(table, NULL, TABLE_FIELD, "Poll interval");
436 if (r < 0)
437 return table_log_add_error(r);
438
439 r = table_add_cell_stringf(table, NULL, "%s (min: %s; max %s)",
440 FORMAT_TIMESPAN(i->poll_interval, 0),
441 FORMAT_TIMESPAN(i->poll_min, 0),
442 FORMAT_TIMESPAN(i->poll_max, 0));
443 if (r < 0)
444 return table_log_add_error(r);
445
446 if (i->packet_count == 0) {
447 r = table_add_many(table,
448 TABLE_FIELD, "Packet count",
449 TABLE_STRING, "0");
450 if (r < 0)
451 return table_log_add_error(r);
452
453 return table_print_or_warn(table);
454 }
455
456 if (i->dest < i->origin || i->trans < i->recv || i->dest - i->origin < i->trans - i->recv) {
457 log_error("Invalid NTP response");
458 return table_print_or_warn(table);
459 }
460
461 delay = (i->dest - i->origin) - (i->trans - i->recv);
462
463 t14 = i->origin + i->dest;
464 t23 = i->recv + i->trans;
465 offset_sign = t14 < t23;
466 offset = (offset_sign ? t23 - t14 : t14 - t23) / 2;
467
468 root_distance = i->root_delay / 2 + i->root_dispersion;
469
470 r = table_add_many(table,
471 TABLE_FIELD, "Leap",
472 TABLE_STRING, ntp_leap_to_string(i->leap),
473 TABLE_FIELD, "Version",
474 TABLE_UINT32, i->version,
475 TABLE_FIELD, "Stratum",
476 TABLE_UINT32, i->stratum,
477 TABLE_FIELD, "Reference");
478 if (r < 0)
479 return table_log_add_error(r);
480
481 if (i->stratum <= 1)
482 r = table_add_cell(table, NULL, TABLE_STRING, i->reference.str);
483 else
484 r = table_add_cell_stringf(table, NULL, "%" PRIX32, be32toh(i->reference.val));
485 if (r < 0)
486 return table_log_add_error(r);
487
488 r = table_add_cell(table, NULL, TABLE_FIELD, "Precision");
489 if (r < 0)
490 return table_log_add_error(r);
491
492 r = table_add_cell_stringf(table, NULL, "%s (%" PRIi32 ")",
493 FORMAT_TIMESPAN(DIV_ROUND_UP((nsec_t) (exp2(i->precision) * NSEC_PER_SEC), NSEC_PER_USEC), 0),
494 i->precision);
495 if (r < 0)
496 return table_log_add_error(r);
497
498 r = table_add_cell(table, NULL, TABLE_FIELD, "Root distance");
499 if (r < 0)
500 return table_log_add_error(r);
501
502 r = table_add_cell_stringf(table, NULL, "%s (max: %s)",
503 FORMAT_TIMESPAN(root_distance, 0),
504 FORMAT_TIMESPAN(i->root_distance_max, 0));
505 if (r < 0)
506 return table_log_add_error(r);
507
508 r = table_add_cell(table, NULL, TABLE_FIELD, "Offset");
509 if (r < 0)
510 return table_log_add_error(r);
511
512 r = table_add_cell_stringf(table, NULL, "%s%s",
513 offset_sign ? "+" : "-",
514 FORMAT_TIMESPAN(offset, 0));
515 if (r < 0)
516 return table_log_add_error(r);
517
518 r = table_add_many(table,
519 TABLE_FIELD, "Delay",
520 TABLE_STRING, FORMAT_TIMESPAN(delay, 0),
521 TABLE_FIELD, "Jitter",
522 TABLE_STRING, FORMAT_TIMESPAN(i->jitter, 0),
523 TABLE_FIELD, "Packet count",
524 TABLE_UINT64, i->packet_count);
525 if (r < 0)
526 return table_log_add_error(r);
527
528 if (!i->spike) {
529 r = table_add_cell(table, NULL, TABLE_FIELD, "Frequency");
530 if (r < 0)
531 return table_log_add_error(r);
532
533 r = table_add_cell_stringf(table, NULL, "%+.3fppm", (double) i->freq / 0x10000);
534 if (r < 0)
535 return table_log_add_error(r);
536 }
537
538 return table_print_or_warn(table);
539 }
540
541 static int map_server_address(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
542 char **p = (char **) userdata;
543 const void *d;
544 int family, r;
545 size_t sz;
546
547 assert(p);
548
549 r = sd_bus_message_enter_container(m, 'r', "iay");
550 if (r < 0)
551 return r;
552
553 r = sd_bus_message_read(m, "i", &family);
554 if (r < 0)
555 return r;
556
557 r = sd_bus_message_read_array(m, 'y', &d, &sz);
558 if (r < 0)
559 return r;
560
561 r = sd_bus_message_exit_container(m);
562 if (r < 0)
563 return r;
564
565 if (sz == 0 && family == AF_UNSPEC) {
566 *p = mfree(*p);
567 return 0;
568 }
569
570 if (!IN_SET(family, AF_INET, AF_INET6))
571 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
572 "Unknown address family %i", family);
573
574 if (sz != FAMILY_ADDRESS_SIZE(family))
575 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
576 "Invalid address size");
577
578 r = in_addr_to_string(family, d, p);
579 if (r < 0)
580 return r;
581
582 return 0;
583 }
584
585 static int map_ntp_message(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
586 NTPStatusInfo *p = ASSERT_PTR(userdata);
587 const void *d;
588 size_t sz;
589 int32_t b;
590 int r;
591
592 r = sd_bus_message_enter_container(m, 'r', "uuuuittayttttbtt");
593 if (r < 0)
594 return r;
595
596 r = sd_bus_message_read(m, "uuuuitt",
597 &p->leap, &p->version, &p->mode, &p->stratum, &p->precision,
598 &p->root_delay, &p->root_dispersion);
599 if (r < 0)
600 return r;
601
602 r = sd_bus_message_read_array(m, 'y', &d, &sz);
603 if (r < 0)
604 return r;
605
606 r = sd_bus_message_read(m, "ttttbtt",
607 &p->origin, &p->recv, &p->trans, &p->dest,
608 &b, &p->packet_count, &p->jitter);
609 if (r < 0)
610 return r;
611
612 r = sd_bus_message_exit_container(m);
613 if (r < 0)
614 return r;
615
616 if (sz != 4)
617 return -EINVAL;
618
619 memcpy(p->reference.str, d, sz);
620
621 p->spike = b;
622
623 return 0;
624 }
625
626 static int show_timesync_status_once(sd_bus *bus) {
627 static const struct bus_properties_map map_timesync[] = {
628 { "ServerName", "s", NULL, offsetof(NTPStatusInfo, server_name) },
629 { "ServerAddress", "(iay)", map_server_address, offsetof(NTPStatusInfo, server_address) },
630 { "PollIntervalUSec", "t", NULL, offsetof(NTPStatusInfo, poll_interval) },
631 { "PollIntervalMinUSec", "t", NULL, offsetof(NTPStatusInfo, poll_min) },
632 { "PollIntervalMaxUSec", "t", NULL, offsetof(NTPStatusInfo, poll_max) },
633 { "RootDistanceMaxUSec", "t", NULL, offsetof(NTPStatusInfo, root_distance_max) },
634 { "NTPMessage", "(uuuuittayttttbtt)", map_ntp_message, 0 },
635 { "Frequency", "x", NULL, offsetof(NTPStatusInfo, freq) },
636 {}
637 };
638 _cleanup_(ntp_status_info_clear) NTPStatusInfo info = {};
639 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
640 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
641 int r;
642
643 assert(bus);
644
645 r = bus_map_all_properties(bus,
646 "org.freedesktop.timesync1",
647 "/org/freedesktop/timesync1",
648 map_timesync,
649 BUS_MAP_BOOLEAN_AS_BOOL,
650 &error,
651 &m,
652 &info);
653 if (r < 0) {
654 if (bus_error_is_unknown_service(&error))
655 return log_error_errno(r,
656 "Command requires systemd-timesyncd.service, but it is not available: %s",
657 bus_error_message(&error, r));
658
659 return log_error_errno(r, "Failed to query server: %s", bus_error_message(&error, r));
660 }
661
662 if (arg_monitor && !terminal_is_dumb())
663 fputs(ANSI_HOME_CLEAR, stdout);
664
665 print_ntp_status_info(&info);
666
667 return 0;
668 }
669
670 static int on_properties_changed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
671 const char *name;
672 int r;
673
674 assert(m);
675
676 r = sd_bus_message_read(m, "s", &name);
677 if (r < 0)
678 return bus_log_parse_error(r);
679
680 if (!streq_ptr(name, "org.freedesktop.timesync1.Manager"))
681 return 0;
682
683 return show_timesync_status_once(sd_bus_message_get_bus(m));
684 }
685
686 VERB_GROUP("systemd-timesyncd Commands");
687
688 VERB_NOARG(verb_timesync_status, "timesync-status", "Show status of systemd-timesyncd");
689 static int verb_timesync_status(int argc, char *argv[], uintptr_t _data, void *userdata) {
690 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
691 sd_bus *bus = ASSERT_PTR(userdata);
692 int r;
693
694 r = show_timesync_status_once(bus);
695 if (r < 0)
696 return r;
697
698 if (!arg_monitor)
699 return 0;
700
701 r = sd_event_default(&event);
702 if (r < 0)
703 return log_error_errno(r, "Failed to get event loop: %m");
704
705 r = sd_bus_match_signal(bus,
706 NULL,
707 "org.freedesktop.timesync1",
708 "/org/freedesktop/timesync1",
709 "org.freedesktop.DBus.Properties",
710 "PropertiesChanged",
711 on_properties_changed, NULL);
712 if (r < 0)
713 return log_error_errno(r, "Failed to request match for PropertiesChanged signal: %m");
714
715 r = sd_bus_attach_event(bus, event, SD_EVENT_PRIORITY_NORMAL);
716 if (r < 0)
717 return log_error_errno(r, "Failed to attach bus to event loop: %m");
718
719 r = sd_event_loop(event);
720 if (r < 0)
721 return log_error_errno(r, "Failed to run event loop: %m");
722
723 return 0;
724 }
725
726 static int print_timesync_property(const char *name, const char *expected_value, sd_bus_message *m, BusPrintPropertyFlags flags) {
727 char type;
728 const char *contents;
729 int r;
730
731 assert(name);
732 assert(m);
733
734 r = sd_bus_message_peek_type(m, &type, &contents);
735 if (r < 0)
736 return r;
737
738 switch (type) {
739
740 case SD_BUS_TYPE_STRUCT:
741 if (streq(name, "NTPMessage")) {
742 _cleanup_(ntp_status_info_clear) NTPStatusInfo i = {};
743
744 r = map_ntp_message(NULL, NULL, m, NULL, &i);
745 if (r < 0)
746 return r;
747
748 if (i.packet_count == 0)
749 return 1;
750
751 if (!FLAGS_SET(flags, BUS_PRINT_PROPERTY_ONLY_VALUE)) {
752 fputs(name, stdout);
753 fputc('=', stdout);
754 }
755
756 printf("{ Leap=%u, Version=%u, Mode=%u, Stratum=%u, Precision=%i,",
757 i.leap, i.version, i.mode, i.stratum, i.precision);
758 printf(" RootDelay=%s,", FORMAT_TIMESPAN(i.root_delay, 0));
759 printf(" RootDispersion=%s,", FORMAT_TIMESPAN(i.root_dispersion, 0));
760
761 if (i.stratum == 1)
762 printf(" Reference=%s,", i.reference.str);
763 else
764 printf(" Reference=%" PRIX32 ",", be32toh(i.reference.val));
765
766 printf(" OriginateTimestamp=%s,", FORMAT_TIMESTAMP(i.origin));
767 printf(" ReceiveTimestamp=%s,", FORMAT_TIMESTAMP(i.recv));
768 printf(" TransmitTimestamp=%s,", FORMAT_TIMESTAMP(i.trans));
769 printf(" DestinationTimestamp=%s,", FORMAT_TIMESTAMP(i.dest));
770 printf(" Ignored=%s, PacketCount=%" PRIu64 ",",
771 yes_no(i.spike), i.packet_count);
772 printf(" Jitter=%s }\n", FORMAT_TIMESPAN(i.jitter, 0));
773
774 return 1;
775
776 } else if (streq(name, "ServerAddress")) {
777 _cleanup_free_ char *str = NULL;
778
779 r = map_server_address(NULL, NULL, m, NULL, &str);
780 if (r < 0)
781 return r;
782
783 bus_print_property_value(name, expected_value, flags, str);
784
785 return 1;
786 }
787 break;
788 }
789
790 return 0;
791 }
792
793 VERB_NOARG(verb_show_timesync, "show-timesync", "Show properties of systemd-timesyncd");
794 static int verb_show_timesync(int argc, char *argv[], uintptr_t _data, void *userdata) {
795 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
796 sd_bus *bus = ASSERT_PTR(userdata);
797 int r;
798
799 r = bus_print_all_properties(bus,
800 "org.freedesktop.timesync1",
801 "/org/freedesktop/timesync1",
802 print_timesync_property,
803 arg_property,
804 arg_print_flags,
805 &error);
806 if (r < 0) {
807 if (bus_error_is_unknown_service(&error))
808 return log_error_errno(r,
809 "Command requires systemd-timesyncd.service, but it is not available: %s",
810 bus_error_message(&error, r));
811
812 return bus_log_parse_error(r);
813 }
814
815 return 0;
816 }
817
818 static int parse_ifindex_bus(sd_bus *bus, const char *str) {
819 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
820 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
821 int32_t i;
822 int r;
823
824 assert(bus);
825 assert(str);
826
827 r = parse_ifindex(str);
828 if (r > 0)
829 return r;
830 assert(r < 0);
831
832 r = bus_call_method(bus, bus_network_mgr, "GetLinkByName", &error, &reply, "s", str);
833 if (r < 0)
834 return log_error_errno(r, "Failed to get ifindex of interfaces %s: %s", str, bus_error_message(&error, r));
835
836 r = sd_bus_message_read(reply, "io", &i, NULL);
837 if (r < 0)
838 return bus_log_create_error(r);
839
840 return i;
841 }
842
843 VERB(verb_ntp_servers, "ntp-servers", "INTERFACE SERVER…", 3, VERB_ANY, 0,
844 "Set the interface specific NTP servers");
845 static int verb_ntp_servers(int argc, char *argv[], uintptr_t _data, void *userdata) {
846 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
847 _cleanup_(sd_bus_message_unrefp) sd_bus_message *req = NULL;
848 sd_bus *bus = ASSERT_PTR(userdata);
849 int ifindex, r;
850
851 ifindex = parse_ifindex_bus(bus, argv[1]);
852 if (ifindex < 0)
853 return ifindex;
854
855 (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
856
857 r = bus_message_new_method_call(bus, &req, bus_network_mgr, "SetLinkNTP");
858 if (r < 0)
859 return bus_log_create_error(r);
860
861 r = sd_bus_message_append(req, "i", ifindex);
862 if (r < 0)
863 return bus_log_create_error(r);
864
865 r = sd_bus_message_append_strv(req, argv + 2);
866 if (r < 0)
867 return bus_log_create_error(r);
868
869 r = sd_bus_call(bus, req, 0, &error, NULL);
870 if (r < 0)
871 return log_error_errno(r, "Failed to set NTP servers: %s", bus_error_message(&error, r));
872
873 return 0;
874 }
875
876 VERB(verb_revert, "revert", "INTERFACE", 2, 2, 0, "Revert the interface specific NTP servers");
877 static int verb_revert(int argc, char *argv[], uintptr_t _data, void *userdata) {
878 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
879 sd_bus *bus = ASSERT_PTR(userdata);
880 int ifindex, r;
881
882 ifindex = parse_ifindex_bus(bus, argv[1]);
883 if (ifindex < 0)
884 return ifindex;
885
886 (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
887
888 r = bus_call_method(bus, bus_network_mgr, "RevertLinkNTP", &error, NULL, "i", ifindex);
889 if (r < 0)
890 return log_error_errno(r, "Failed to revert interface configuration: %s", bus_error_message(&error, r));
891
892 return 0;
893 }
894
895 static int help(void) {
896 _cleanup_free_ char *link = NULL;
897 _cleanup_(table_unrefp) Table *verbs = NULL, *verbs2 = NULL, *options = NULL;
898 int r;
899
900 r = terminal_urlify_man("timedatectl", "1", &link);
901 if (r < 0)
902 return log_oom();
903
904 r = verbs_get_help_table(&verbs);
905 if (r < 0)
906 return r;
907
908 r = verbs_get_help_table_group("systemd-timesyncd Commands", &verbs2);
909 if (r < 0)
910 return r;
911
912 r = option_parser_get_help_table(&options);
913 if (r < 0)
914 return r;
915
916 (void) table_sync_column_widths(0, verbs, verbs2, options);
917
918 printf("%s [OPTIONS...] COMMAND ...\n"
919 "\n%sQuery or change system time and date settings.%s\n"
920 "\nCommands:\n",
921 program_invocation_short_name,
922 ansi_highlight(),
923 ansi_normal());
924 r = table_print_or_warn(verbs);
925 if (r < 0)
926 return r;
927
928 printf("\nsystemd-timesyncd Commands:\n");
929 r = table_print_or_warn(verbs2);
930 if (r < 0)
931 return r;
932
933 printf("\nOptions:\n");
934 r = table_print_or_warn(options);
935 if (r < 0)
936 return r;
937
938 printf("\nSee the %s for details.\n", link);
939 return 0;
940 }
941
942 VERB_COMMON_HELP_HIDDEN(help);
943
944 static int parse_argv(int argc, char *argv[], char ***ret_args) {
945 int r;
946
947 assert(argc >= 0);
948 assert(argv);
949
950 OptionParser opts = { argc, argv };
951
952 FOREACH_OPTION_OR_RETURN(c, &opts)
953 switch (c) {
954 OPTION_COMMON_HELP:
955 return help();
956
957 OPTION_COMMON_VERSION:
958 return version();
959
960 OPTION_COMMON_NO_PAGER:
961 arg_pager_flags |= PAGER_DISABLE;
962 break;
963
964 OPTION_COMMON_NO_ASK_PASSWORD:
965 arg_ask_password = false;
966 break;
967
968 OPTION_COMMON_HOST:
969 arg_transport = BUS_TRANSPORT_REMOTE;
970 arg_host = opts.arg;
971 break;
972
973 OPTION_COMMON_MACHINE:
974 r = parse_machine_argument(opts.arg, &arg_host, &arg_transport);
975 if (r < 0)
976 return r;
977 break;
978
979 OPTION_LONG("adjust-system-clock", NULL, "Adjust system clock when changing local RTC mode"):
980 arg_adjust_system_clock = true;
981 break;
982
983 OPTION_LONG("monitor", NULL, "Monitor status of systemd-timesyncd"):
984 arg_monitor = true;
985 break;
986
987 OPTION('p', "property", "NAME", "Show only properties by this name"): {}
988 OPTION_SHORT('P', "NAME", "Equivalent to --value --property=NAME"):
989 r = strv_extend(&arg_property, opts.arg);
990 if (r < 0)
991 return log_oom();
992
993 /* If the user asked for a particular property, show it to them, even if empty. */
994 SET_FLAG(arg_print_flags, BUS_PRINT_PROPERTY_SHOW_EMPTY, true);
995
996 if (opts.opt->short_code == 'P')
997 SET_FLAG(arg_print_flags, BUS_PRINT_PROPERTY_ONLY_VALUE, true);
998 break;
999
1000 OPTION_LONG("value", NULL, "When showing properties, only print the value"):
1001 SET_FLAG(arg_print_flags, BUS_PRINT_PROPERTY_ONLY_VALUE, true);
1002 break;
1003
1004 OPTION('a', "all", NULL, "Show all properties, including empty ones"):
1005 SET_FLAG(arg_print_flags, BUS_PRINT_PROPERTY_SHOW_EMPTY, true);
1006 break;
1007 }
1008
1009 *ret_args = option_parser_get_args(&opts);
1010 return 1;
1011 }
1012
1013 static int run(int argc, char *argv[]) {
1014 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1015 char **args = NULL;
1016 int r;
1017
1018 setlocale(LC_ALL, "");
1019 log_setup();
1020
1021 r = parse_argv(argc, argv, &args);
1022 if (r <= 0)
1023 return r;
1024
1025 r = bus_connect_transport(arg_transport, arg_host, RUNTIME_SCOPE_SYSTEM, &bus);
1026 if (r < 0)
1027 return bus_log_connect_error(r, arg_transport, RUNTIME_SCOPE_SYSTEM);
1028
1029 (void) sd_bus_set_allow_interactive_authorization(bus, arg_ask_password);
1030
1031 return dispatch_verb(args, bus);
1032 }
1033
1034 DEFINE_MAIN_FUNCTION(run);