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