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