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