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