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