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