]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/analyze/analyze.c
Merge pull request #20744 from yuwata/udev-netlink
[thirdparty/systemd.git] / src / analyze / analyze.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 /***
3 Copyright © 2013 Simon Peeters
4 ***/
5
6 #include <getopt.h>
7 #include <inttypes.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <unistd.h>
11
12 #include "sd-bus.h"
13
14 #include "alloc-util.h"
15 #include "analyze-condition.h"
16 #include "analyze-security.h"
17 #include "analyze-verify.h"
18 #include "bus-error.h"
19 #include "bus-locator.h"
20 #include "bus-map-properties.h"
21 #include "bus-unit-util.h"
22 #include "calendarspec.h"
23 #include "cap-list.h"
24 #include "capability-util.h"
25 #include "conf-files.h"
26 #include "copy.h"
27 #include "def.h"
28 #include "exit-status.h"
29 #include "fd-util.h"
30 #include "fileio.h"
31 #include "filesystems.h"
32 #include "format-table.h"
33 #include "glob-util.h"
34 #include "hashmap.h"
35 #include "locale-util.h"
36 #include "log.h"
37 #include "main-func.h"
38 #include "mount-util.h"
39 #include "nulstr-util.h"
40 #include "pager.h"
41 #include "parse-argument.h"
42 #include "parse-util.h"
43 #include "path-util.h"
44 #include "pretty-print.h"
45 #if HAVE_SECCOMP
46 # include "seccomp-util.h"
47 #endif
48 #include "sort-util.h"
49 #include "special.h"
50 #include "stat-util.h"
51 #include "string-table.h"
52 #include "strv.h"
53 #include "strxcpyx.h"
54 #include "terminal-util.h"
55 #include "time-util.h"
56 #include "unit-name.h"
57 #include "util.h"
58 #include "verb-log-control.h"
59 #include "verbs.h"
60 #include "version.h"
61
62 #define SCALE_X (0.1 / 1000.0) /* pixels per us */
63 #define SCALE_Y (20.0)
64
65 #define svg(...) printf(__VA_ARGS__)
66
67 #define svg_bar(class, x1, x2, y) \
68 svg(" <rect class=\"%s\" x=\"%.03f\" y=\"%.03f\" width=\"%.03f\" height=\"%.03f\" />\n", \
69 (class), \
70 SCALE_X * (x1), SCALE_Y * (y), \
71 SCALE_X * ((x2) - (x1)), SCALE_Y - 1.0)
72
73 #define svg_text(b, x, y, format, ...) \
74 do { \
75 svg(" <text class=\"%s\" x=\"%.03f\" y=\"%.03f\">", (b) ? "left" : "right", SCALE_X * (x) + (b ? 5.0 : -5.0), SCALE_Y * (y) + 14.0); \
76 svg(format, ## __VA_ARGS__); \
77 svg("</text>\n"); \
78 } while (false)
79
80 static enum dot {
81 DEP_ALL,
82 DEP_ORDER,
83 DEP_REQUIRE
84 } arg_dot = DEP_ALL;
85 static char **arg_dot_from_patterns = NULL;
86 static char **arg_dot_to_patterns = NULL;
87 static usec_t arg_fuzz = 0;
88 static PagerFlags arg_pager_flags = 0;
89 static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
90 static const char *arg_host = NULL;
91 static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
92 static RecursiveErrors arg_recursive_errors = RECURSIVE_ERRORS_YES;
93 static bool arg_man = true;
94 static bool arg_generators = false;
95 static char *arg_root = NULL;
96 static char *arg_image = NULL;
97 static char *arg_security_policy = NULL;
98 static bool arg_offline = false;
99 static unsigned arg_threshold = 100;
100 static unsigned arg_iterations = 1;
101 static usec_t arg_base_time = USEC_INFINITY;
102 static char *arg_unit = NULL;
103 static JsonFormatFlags arg_json_format_flags = JSON_FORMAT_OFF;
104
105 STATIC_DESTRUCTOR_REGISTER(arg_dot_from_patterns, strv_freep);
106 STATIC_DESTRUCTOR_REGISTER(arg_dot_to_patterns, strv_freep);
107 STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
108 STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
109 STATIC_DESTRUCTOR_REGISTER(arg_security_policy, freep);
110 STATIC_DESTRUCTOR_REGISTER(arg_unit, freep);
111
112 typedef struct BootTimes {
113 usec_t firmware_time;
114 usec_t loader_time;
115 usec_t kernel_time;
116 usec_t kernel_done_time;
117 usec_t initrd_time;
118 usec_t userspace_time;
119 usec_t finish_time;
120 usec_t security_start_time;
121 usec_t security_finish_time;
122 usec_t generators_start_time;
123 usec_t generators_finish_time;
124 usec_t unitsload_start_time;
125 usec_t unitsload_finish_time;
126 usec_t initrd_security_start_time;
127 usec_t initrd_security_finish_time;
128 usec_t initrd_generators_start_time;
129 usec_t initrd_generators_finish_time;
130 usec_t initrd_unitsload_start_time;
131 usec_t initrd_unitsload_finish_time;
132
133 /*
134 * If we're analyzing the user instance, all timestamps will be offset
135 * by its own start-up timestamp, which may be arbitrarily big.
136 * With "plot", this causes arbitrarily wide output SVG files which almost
137 * completely consist of empty space. Thus we cancel out this offset.
138 *
139 * This offset is subtracted from times above by acquire_boot_times(),
140 * but it still needs to be subtracted from unit-specific timestamps
141 * (so it is stored here for reference).
142 */
143 usec_t reverse_offset;
144 } BootTimes;
145
146 typedef struct UnitTimes {
147 bool has_data;
148 char *name;
149 usec_t activating;
150 usec_t activated;
151 usec_t deactivated;
152 usec_t deactivating;
153 usec_t time;
154 } UnitTimes;
155
156 typedef struct HostInfo {
157 char *hostname;
158 char *kernel_name;
159 char *kernel_release;
160 char *kernel_version;
161 char *os_pretty_name;
162 char *virtualization;
163 char *architecture;
164 } HostInfo;
165
166 static int acquire_bus(sd_bus **bus, bool *use_full_bus) {
167 bool user = arg_scope != UNIT_FILE_SYSTEM;
168 int r;
169
170 if (use_full_bus && *use_full_bus) {
171 r = bus_connect_transport(arg_transport, arg_host, user, bus);
172 if (IN_SET(r, 0, -EHOSTDOWN))
173 return r;
174
175 *use_full_bus = false;
176 }
177
178 return bus_connect_transport_systemd(arg_transport, arg_host, user, bus);
179 }
180
181 static int bus_get_uint64_property(sd_bus *bus, const char *path, const char *interface, const char *property, uint64_t *val) {
182 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
183 int r;
184
185 assert(bus);
186 assert(path);
187 assert(interface);
188 assert(property);
189 assert(val);
190
191 r = sd_bus_get_property_trivial(
192 bus,
193 "org.freedesktop.systemd1",
194 path,
195 interface,
196 property,
197 &error,
198 't', val);
199
200 if (r < 0)
201 return log_error_errno(r, "Failed to parse reply: %s", bus_error_message(&error, r));
202
203 return 0;
204 }
205
206 static int bus_get_unit_property_strv(sd_bus *bus, const char *path, const char *property, char ***strv) {
207 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
208 int r;
209
210 assert(bus);
211 assert(path);
212 assert(property);
213 assert(strv);
214
215 r = sd_bus_get_property_strv(
216 bus,
217 "org.freedesktop.systemd1",
218 path,
219 "org.freedesktop.systemd1.Unit",
220 property,
221 &error,
222 strv);
223 if (r < 0)
224 return log_error_errno(r, "Failed to get unit property %s: %s", property, bus_error_message(&error, r));
225
226 return 0;
227 }
228
229 static int compare_unit_start(const UnitTimes *a, const UnitTimes *b) {
230 return CMP(a->activating, b->activating);
231 }
232
233 static UnitTimes* unit_times_free_array(UnitTimes *t) {
234 for (UnitTimes *p = t; p && p->has_data; p++)
235 free(p->name);
236 return mfree(t);
237 }
238 DEFINE_TRIVIAL_CLEANUP_FUNC(UnitTimes*, unit_times_free_array);
239
240 static void subtract_timestamp(usec_t *a, usec_t b) {
241 assert(a);
242
243 if (*a > 0) {
244 assert(*a >= b);
245 *a -= b;
246 }
247 }
248
249 static int acquire_boot_times(sd_bus *bus, BootTimes **bt) {
250 static const struct bus_properties_map property_map[] = {
251 { "FirmwareTimestampMonotonic", "t", NULL, offsetof(BootTimes, firmware_time) },
252 { "LoaderTimestampMonotonic", "t", NULL, offsetof(BootTimes, loader_time) },
253 { "KernelTimestamp", "t", NULL, offsetof(BootTimes, kernel_time) },
254 { "InitRDTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_time) },
255 { "UserspaceTimestampMonotonic", "t", NULL, offsetof(BootTimes, userspace_time) },
256 { "FinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, finish_time) },
257 { "SecurityStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, security_start_time) },
258 { "SecurityFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, security_finish_time) },
259 { "GeneratorsStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, generators_start_time) },
260 { "GeneratorsFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, generators_finish_time) },
261 { "UnitsLoadStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, unitsload_start_time) },
262 { "UnitsLoadFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, unitsload_finish_time) },
263 { "InitRDSecurityStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_security_start_time) },
264 { "InitRDSecurityFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_security_finish_time) },
265 { "InitRDGeneratorsStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_generators_start_time) },
266 { "InitRDGeneratorsFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_generators_finish_time) },
267 { "InitRDUnitsLoadStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_unitsload_start_time) },
268 { "InitRDUnitsLoadFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_unitsload_finish_time) },
269 {},
270 };
271 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
272 static BootTimes times;
273 static bool cached = false;
274 int r;
275
276 if (cached)
277 goto finish;
278
279 assert_cc(sizeof(usec_t) == sizeof(uint64_t));
280
281 r = bus_map_all_properties(
282 bus,
283 "org.freedesktop.systemd1",
284 "/org/freedesktop/systemd1",
285 property_map,
286 BUS_MAP_STRDUP,
287 &error,
288 NULL,
289 &times);
290 if (r < 0)
291 return log_error_errno(r, "Failed to get timestamp properties: %s", bus_error_message(&error, r));
292
293 if (times.finish_time <= 0)
294 return log_error_errno(SYNTHETIC_ERRNO(EINPROGRESS),
295 "Bootup is not yet finished (org.freedesktop.systemd1.Manager.FinishTimestampMonotonic=%"PRIu64").\n"
296 "Please try again later.\n"
297 "Hint: Use 'systemctl%s list-jobs' to see active jobs",
298 times.finish_time,
299 arg_scope == UNIT_FILE_SYSTEM ? "" : " --user");
300
301 if (arg_scope == UNIT_FILE_SYSTEM && times.security_start_time > 0) {
302 /* security_start_time is set when systemd is not running under container environment. */
303 if (times.initrd_time > 0)
304 times.kernel_done_time = times.initrd_time;
305 else
306 times.kernel_done_time = times.userspace_time;
307 } else {
308 /*
309 * User-instance-specific or container-system-specific timestamps processing
310 * (see comment to reverse_offset in BootTimes).
311 */
312 times.reverse_offset = times.userspace_time;
313
314 times.firmware_time = times.loader_time = times.kernel_time = times.initrd_time =
315 times.userspace_time = times.security_start_time = times.security_finish_time = 0;
316
317 subtract_timestamp(&times.finish_time, times.reverse_offset);
318
319 subtract_timestamp(&times.generators_start_time, times.reverse_offset);
320 subtract_timestamp(&times.generators_finish_time, times.reverse_offset);
321
322 subtract_timestamp(&times.unitsload_start_time, times.reverse_offset);
323 subtract_timestamp(&times.unitsload_finish_time, times.reverse_offset);
324 }
325
326 cached = true;
327
328 finish:
329 *bt = &times;
330 return 0;
331 }
332
333 static HostInfo* free_host_info(HostInfo *hi) {
334 if (!hi)
335 return NULL;
336
337 free(hi->hostname);
338 free(hi->kernel_name);
339 free(hi->kernel_release);
340 free(hi->kernel_version);
341 free(hi->os_pretty_name);
342 free(hi->virtualization);
343 free(hi->architecture);
344 return mfree(hi);
345 }
346
347 DEFINE_TRIVIAL_CLEANUP_FUNC(HostInfo *, free_host_info);
348
349 static int acquire_time_data(sd_bus *bus, UnitTimes **out) {
350 static const struct bus_properties_map property_map[] = {
351 { "InactiveExitTimestampMonotonic", "t", NULL, offsetof(UnitTimes, activating) },
352 { "ActiveEnterTimestampMonotonic", "t", NULL, offsetof(UnitTimes, activated) },
353 { "ActiveExitTimestampMonotonic", "t", NULL, offsetof(UnitTimes, deactivating) },
354 { "InactiveEnterTimestampMonotonic", "t", NULL, offsetof(UnitTimes, deactivated) },
355 {},
356 };
357 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
358 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
359 _cleanup_(unit_times_free_arrayp) UnitTimes *unit_times = NULL;
360 BootTimes *boot_times = NULL;
361 size_t c = 0;
362 UnitInfo u;
363 int r;
364
365 r = acquire_boot_times(bus, &boot_times);
366 if (r < 0)
367 return r;
368
369 r = bus_call_method(bus, bus_systemd_mgr, "ListUnits", &error, &reply, NULL);
370 if (r < 0)
371 return log_error_errno(r, "Failed to list units: %s", bus_error_message(&error, r));
372
373 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)");
374 if (r < 0)
375 return bus_log_parse_error(r);
376
377 while ((r = bus_parse_unit_info(reply, &u)) > 0) {
378 UnitTimes *t;
379
380 if (!GREEDY_REALLOC(unit_times, c + 2))
381 return log_oom();
382
383 unit_times[c + 1].has_data = false;
384 t = &unit_times[c];
385 t->name = NULL;
386
387 assert_cc(sizeof(usec_t) == sizeof(uint64_t));
388
389 r = bus_map_all_properties(
390 bus,
391 "org.freedesktop.systemd1",
392 u.unit_path,
393 property_map,
394 BUS_MAP_STRDUP,
395 &error,
396 NULL,
397 t);
398 if (r < 0)
399 return log_error_errno(r, "Failed to get timestamp properties of unit %s: %s",
400 u.id, bus_error_message(&error, r));
401
402 subtract_timestamp(&t->activating, boot_times->reverse_offset);
403 subtract_timestamp(&t->activated, boot_times->reverse_offset);
404 subtract_timestamp(&t->deactivating, boot_times->reverse_offset);
405 subtract_timestamp(&t->deactivated, boot_times->reverse_offset);
406
407 if (t->activated >= t->activating)
408 t->time = t->activated - t->activating;
409 else if (t->deactivated >= t->activating)
410 t->time = t->deactivated - t->activating;
411 else
412 t->time = 0;
413
414 if (t->activating == 0)
415 continue;
416
417 t->name = strdup(u.id);
418 if (!t->name)
419 return log_oom();
420
421 t->has_data = true;
422 c++;
423 }
424 if (r < 0)
425 return bus_log_parse_error(r);
426
427 *out = TAKE_PTR(unit_times);
428 return c;
429 }
430
431 static int acquire_host_info(sd_bus *bus, HostInfo **hi) {
432 static const struct bus_properties_map hostname_map[] = {
433 { "Hostname", "s", NULL, offsetof(HostInfo, hostname) },
434 { "KernelName", "s", NULL, offsetof(HostInfo, kernel_name) },
435 { "KernelRelease", "s", NULL, offsetof(HostInfo, kernel_release) },
436 { "KernelVersion", "s", NULL, offsetof(HostInfo, kernel_version) },
437 { "OperatingSystemPrettyName", "s", NULL, offsetof(HostInfo, os_pretty_name) },
438 {}
439 };
440
441 static const struct bus_properties_map manager_map[] = {
442 { "Virtualization", "s", NULL, offsetof(HostInfo, virtualization) },
443 { "Architecture", "s", NULL, offsetof(HostInfo, architecture) },
444 {}
445 };
446
447 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
448 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *system_bus = NULL;
449 _cleanup_(free_host_infop) HostInfo *host = NULL;
450 int r;
451
452 host = new0(HostInfo, 1);
453 if (!host)
454 return log_oom();
455
456 if (arg_scope != UNIT_FILE_SYSTEM) {
457 r = bus_connect_transport(arg_transport, arg_host, false, &system_bus);
458 if (r < 0) {
459 log_debug_errno(r, "Failed to connect to system bus, ignoring: %m");
460 goto manager;
461 }
462 }
463
464 r = bus_map_all_properties(
465 system_bus ?: bus,
466 "org.freedesktop.hostname1",
467 "/org/freedesktop/hostname1",
468 hostname_map,
469 BUS_MAP_STRDUP,
470 &error,
471 NULL,
472 host);
473 if (r < 0) {
474 log_debug_errno(r, "Failed to get host information from systemd-hostnamed, ignoring: %s",
475 bus_error_message(&error, r));
476 sd_bus_error_free(&error);
477 }
478
479 manager:
480 r = bus_map_all_properties(
481 bus,
482 "org.freedesktop.systemd1",
483 "/org/freedesktop/systemd1",
484 manager_map,
485 BUS_MAP_STRDUP,
486 &error,
487 NULL,
488 host);
489 if (r < 0)
490 return log_error_errno(r, "Failed to get host information from systemd: %s",
491 bus_error_message(&error, r));
492
493 *hi = TAKE_PTR(host);
494 return 0;
495 }
496
497 static int pretty_boot_time(sd_bus *bus, char **_buf) {
498 BootTimes *t;
499 static char buf[4096];
500 size_t size;
501 char *ptr;
502 int r;
503 usec_t activated_time = USEC_INFINITY;
504 _cleanup_free_ char *path = NULL, *unit_id = NULL;
505 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
506
507 r = acquire_boot_times(bus, &t);
508 if (r < 0)
509 return r;
510
511 path = unit_dbus_path_from_name(SPECIAL_DEFAULT_TARGET);
512 if (!path)
513 return log_oom();
514
515 r = sd_bus_get_property_string(
516 bus,
517 "org.freedesktop.systemd1",
518 path,
519 "org.freedesktop.systemd1.Unit",
520 "Id",
521 &error,
522 &unit_id);
523 if (r < 0) {
524 log_error_errno(r, "default.target doesn't seem to exist: %s", bus_error_message(&error, r));
525 unit_id = NULL;
526 }
527
528 r = bus_get_uint64_property(bus, path,
529 "org.freedesktop.systemd1.Unit",
530 "ActiveEnterTimestampMonotonic",
531 &activated_time);
532 if (r < 0) {
533 log_info_errno(r, "Could not get time to reach default.target, ignoring: %m");
534 activated_time = USEC_INFINITY;
535 }
536
537 ptr = buf;
538 size = sizeof(buf);
539
540 size = strpcpyf(&ptr, size, "Startup finished in ");
541 if (t->firmware_time > 0)
542 size = strpcpyf(&ptr, size, "%s (firmware) + ", FORMAT_TIMESPAN(t->firmware_time - t->loader_time, USEC_PER_MSEC));
543 if (t->loader_time > 0)
544 size = strpcpyf(&ptr, size, "%s (loader) + ", FORMAT_TIMESPAN(t->loader_time, USEC_PER_MSEC));
545 if (t->kernel_done_time > 0)
546 size = strpcpyf(&ptr, size, "%s (kernel) + ", FORMAT_TIMESPAN(t->kernel_done_time, USEC_PER_MSEC));
547 if (t->initrd_time > 0)
548 size = strpcpyf(&ptr, size, "%s (initrd) + ", FORMAT_TIMESPAN(t->userspace_time - t->initrd_time, USEC_PER_MSEC));
549
550 size = strpcpyf(&ptr, size, "%s (userspace) ", FORMAT_TIMESPAN(t->finish_time - t->userspace_time, USEC_PER_MSEC));
551 if (t->kernel_done_time > 0)
552 strpcpyf(&ptr, size, "= %s ", FORMAT_TIMESPAN(t->firmware_time + t->finish_time, USEC_PER_MSEC));
553
554 if (unit_id && timestamp_is_set(activated_time)) {
555 usec_t base = t->userspace_time > 0 ? t->userspace_time : t->reverse_offset;
556
557 size = strpcpyf(&ptr, size, "\n%s reached after %s in userspace", unit_id,
558 FORMAT_TIMESPAN(activated_time - base, USEC_PER_MSEC));
559 } else if (unit_id && activated_time == 0)
560 size = strpcpyf(&ptr, size, "\n%s was never reached", unit_id);
561 else if (unit_id && activated_time == USEC_INFINITY)
562 size = strpcpyf(&ptr, size, "\nCould not get time to reach %s.", unit_id);
563 else if (!unit_id)
564 size = strpcpyf(&ptr, size, "\ncould not find default.target");
565
566 ptr = strdup(buf);
567 if (!ptr)
568 return log_oom();
569
570 *_buf = ptr;
571 return 0;
572 }
573
574 static void svg_graph_box(double height, double begin, double end) {
575 /* outside box, fill */
576 svg("<rect class=\"box\" x=\"0\" y=\"0\" width=\"%.03f\" height=\"%.03f\" />\n",
577 SCALE_X * (end - begin),
578 SCALE_Y * height);
579
580 for (long long i = ((long long) (begin / 100000)) * 100000; i <= end; i += 100000) {
581 /* lines for each second */
582 if (i % 5000000 == 0)
583 svg(" <line class=\"sec5\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n"
584 " <text class=\"sec\" x=\"%.03f\" y=\"%.03f\" >%.01fs</text>\n",
585 SCALE_X * i,
586 SCALE_X * i,
587 SCALE_Y * height,
588 SCALE_X * i,
589 -5.0,
590 0.000001 * i);
591 else if (i % 1000000 == 0)
592 svg(" <line class=\"sec1\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n"
593 " <text class=\"sec\" x=\"%.03f\" y=\"%.03f\" >%.01fs</text>\n",
594 SCALE_X * i,
595 SCALE_X * i,
596 SCALE_Y * height,
597 SCALE_X * i,
598 -5.0,
599 0.000001 * i);
600 else
601 svg(" <line class=\"sec01\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n",
602 SCALE_X * i,
603 SCALE_X * i,
604 SCALE_Y * height);
605 }
606 }
607
608 static int plot_unit_times(UnitTimes *u, double width, int y) {
609 bool b;
610
611 if (!u->name)
612 return 0;
613
614 svg_bar("activating", u->activating, u->activated, y);
615 svg_bar("active", u->activated, u->deactivating, y);
616 svg_bar("deactivating", u->deactivating, u->deactivated, y);
617
618 /* place the text on the left if we have passed the half of the svg width */
619 b = u->activating * SCALE_X < width / 2;
620 if (u->time)
621 svg_text(b, u->activating, y, "%s (%s)",
622 u->name, FORMAT_TIMESPAN(u->time, USEC_PER_MSEC));
623 else
624 svg_text(b, u->activating, y, "%s", u->name);
625
626 return 1;
627 }
628
629 static int analyze_plot(int argc, char *argv[], void *userdata) {
630 _cleanup_(free_host_infop) HostInfo *host = NULL;
631 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
632 _cleanup_(unit_times_free_arrayp) UnitTimes *times = NULL;
633 _cleanup_free_ char *pretty_times = NULL;
634 bool use_full_bus = arg_scope == UNIT_FILE_SYSTEM;
635 BootTimes *boot;
636 UnitTimes *u;
637 int n, m = 1, y = 0, r;
638 double width;
639
640 r = acquire_bus(&bus, &use_full_bus);
641 if (r < 0)
642 return bus_log_connect_error(r);
643
644 n = acquire_boot_times(bus, &boot);
645 if (n < 0)
646 return n;
647
648 n = pretty_boot_time(bus, &pretty_times);
649 if (n < 0)
650 return n;
651
652 if (use_full_bus || arg_scope != UNIT_FILE_SYSTEM) {
653 n = acquire_host_info(bus, &host);
654 if (n < 0)
655 return n;
656 }
657
658 n = acquire_time_data(bus, &times);
659 if (n <= 0)
660 return n;
661
662 typesafe_qsort(times, n, compare_unit_start);
663
664 width = SCALE_X * (boot->firmware_time + boot->finish_time);
665 if (width < 800.0)
666 width = 800.0;
667
668 if (boot->firmware_time > boot->loader_time)
669 m++;
670 if (boot->loader_time > 0) {
671 m++;
672 if (width < 1000.0)
673 width = 1000.0;
674 }
675 if (boot->initrd_time > 0)
676 m++;
677 if (boot->kernel_done_time > 0)
678 m++;
679
680 for (u = times; u->has_data; u++) {
681 double text_start, text_width;
682
683 if (u->activating > boot->finish_time) {
684 u->name = mfree(u->name);
685 continue;
686 }
687
688 /* If the text cannot fit on the left side then
689 * increase the svg width so it fits on the right.
690 * TODO: calculate the text width more accurately */
691 text_width = 8.0 * strlen(u->name);
692 text_start = (boot->firmware_time + u->activating) * SCALE_X;
693 if (text_width > text_start && text_width + text_start > width)
694 width = text_width + text_start;
695
696 if (u->deactivated > u->activating &&
697 u->deactivated <= boot->finish_time &&
698 u->activated == 0 && u->deactivating == 0)
699 u->activated = u->deactivating = u->deactivated;
700 if (u->activated < u->activating || u->activated > boot->finish_time)
701 u->activated = boot->finish_time;
702 if (u->deactivating < u->activated || u->deactivating > boot->finish_time)
703 u->deactivating = boot->finish_time;
704 if (u->deactivated < u->deactivating || u->deactivated > boot->finish_time)
705 u->deactivated = boot->finish_time;
706 m++;
707 }
708
709 svg("<?xml version=\"1.0\" standalone=\"no\"?>\n"
710 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" "
711 "\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
712
713 svg("<svg width=\"%.0fpx\" height=\"%.0fpx\" version=\"1.1\" "
714 "xmlns=\"http://www.w3.org/2000/svg\">\n\n",
715 80.0 + width, 150.0 + (m * SCALE_Y) +
716 5 * SCALE_Y /* legend */);
717
718 /* write some basic info as a comment, including some help */
719 svg("<!-- This file is a systemd-analyze SVG file. It is best rendered in a -->\n"
720 "<!-- browser such as Chrome, Chromium or Firefox. Other applications -->\n"
721 "<!-- that render these files properly but much slower are ImageMagick, -->\n"
722 "<!-- gimp, inkscape, etc. To display the files on your system, just -->\n"
723 "<!-- point your browser to this file. -->\n\n"
724 "<!-- This plot was generated by systemd-analyze version %-16.16s -->\n\n", GIT_VERSION);
725
726 /* style sheet */
727 svg("<defs>\n <style type=\"text/css\">\n <![CDATA[\n"
728 " rect { stroke-width: 1; stroke-opacity: 0; }\n"
729 " rect.background { fill: rgb(255,255,255); }\n"
730 " rect.activating { fill: rgb(255,0,0); fill-opacity: 0.7; }\n"
731 " rect.active { fill: rgb(200,150,150); fill-opacity: 0.7; }\n"
732 " rect.deactivating { fill: rgb(150,100,100); fill-opacity: 0.7; }\n"
733 " rect.kernel { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
734 " rect.initrd { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
735 " rect.firmware { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
736 " rect.loader { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
737 " rect.userspace { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
738 " rect.security { fill: rgb(144,238,144); fill-opacity: 0.7; }\n"
739 " rect.generators { fill: rgb(102,204,255); fill-opacity: 0.7; }\n"
740 " rect.unitsload { fill: rgb( 82,184,255); fill-opacity: 0.7; }\n"
741 " rect.box { fill: rgb(240,240,240); stroke: rgb(192,192,192); }\n"
742 " line { stroke: rgb(64,64,64); stroke-width: 1; }\n"
743 "// line.sec1 { }\n"
744 " line.sec5 { stroke-width: 2; }\n"
745 " line.sec01 { stroke: rgb(224,224,224); stroke-width: 1; }\n"
746 " text { font-family: Verdana, Helvetica; font-size: 14px; }\n"
747 " text.left { font-family: Verdana, Helvetica; font-size: 14px; text-anchor: start; }\n"
748 " text.right { font-family: Verdana, Helvetica; font-size: 14px; text-anchor: end; }\n"
749 " text.sec { font-size: 10px; }\n"
750 " ]]>\n </style>\n</defs>\n\n");
751
752 svg("<rect class=\"background\" width=\"100%%\" height=\"100%%\" />\n");
753 svg("<text x=\"20\" y=\"50\">%s</text>", pretty_times);
754 if (host)
755 svg("<text x=\"20\" y=\"30\">%s %s (%s %s %s) %s %s</text>",
756 isempty(host->os_pretty_name) ? "Linux" : host->os_pretty_name,
757 strempty(host->hostname),
758 strempty(host->kernel_name),
759 strempty(host->kernel_release),
760 strempty(host->kernel_version),
761 strempty(host->architecture),
762 strempty(host->virtualization));
763
764 svg("<g transform=\"translate(%.3f,100)\">\n", 20.0 + (SCALE_X * boot->firmware_time));
765 svg_graph_box(m, -(double) boot->firmware_time, boot->finish_time);
766
767 if (boot->firmware_time > 0) {
768 svg_bar("firmware", -(double) boot->firmware_time, -(double) boot->loader_time, y);
769 svg_text(true, -(double) boot->firmware_time, y, "firmware");
770 y++;
771 }
772 if (boot->loader_time > 0) {
773 svg_bar("loader", -(double) boot->loader_time, 0, y);
774 svg_text(true, -(double) boot->loader_time, y, "loader");
775 y++;
776 }
777 if (boot->kernel_done_time > 0) {
778 svg_bar("kernel", 0, boot->kernel_done_time, y);
779 svg_text(true, 0, y, "kernel");
780 y++;
781 }
782 if (boot->initrd_time > 0) {
783 svg_bar("initrd", boot->initrd_time, boot->userspace_time, y);
784 if (boot->initrd_security_start_time < boot->initrd_security_finish_time)
785 svg_bar("security", boot->initrd_security_start_time, boot->initrd_security_finish_time, y);
786 if (boot->initrd_generators_start_time < boot->initrd_generators_finish_time)
787 svg_bar("generators", boot->initrd_generators_start_time, boot->initrd_generators_finish_time, y);
788 if (boot->initrd_unitsload_start_time < boot->initrd_unitsload_finish_time)
789 svg_bar("unitsload", boot->initrd_unitsload_start_time, boot->initrd_unitsload_finish_time, y);
790 svg_text(true, boot->initrd_time, y, "initrd");
791 y++;
792 }
793
794 for (u = times; u->has_data; u++) {
795 if (u->activating >= boot->userspace_time)
796 break;
797
798 y += plot_unit_times(u, width, y);
799 }
800
801 svg_bar("active", boot->userspace_time, boot->finish_time, y);
802 if (boot->security_start_time > 0)
803 svg_bar("security", boot->security_start_time, boot->security_finish_time, y);
804 svg_bar("generators", boot->generators_start_time, boot->generators_finish_time, y);
805 svg_bar("unitsload", boot->unitsload_start_time, boot->unitsload_finish_time, y);
806 svg_text(true, boot->userspace_time, y, "systemd");
807 y++;
808
809 for (; u->has_data; u++)
810 y += plot_unit_times(u, width, y);
811
812 svg("</g>\n");
813
814 /* Legend */
815 svg("<g transform=\"translate(20,100)\">\n");
816 y++;
817 svg_bar("activating", 0, 300000, y);
818 svg_text(true, 400000, y, "Activating");
819 y++;
820 svg_bar("active", 0, 300000, y);
821 svg_text(true, 400000, y, "Active");
822 y++;
823 svg_bar("deactivating", 0, 300000, y);
824 svg_text(true, 400000, y, "Deactivating");
825 y++;
826 if (boot->security_start_time > 0) {
827 svg_bar("security", 0, 300000, y);
828 svg_text(true, 400000, y, "Setting up security module");
829 y++;
830 }
831 svg_bar("generators", 0, 300000, y);
832 svg_text(true, 400000, y, "Generators");
833 y++;
834 svg_bar("unitsload", 0, 300000, y);
835 svg_text(true, 400000, y, "Loading unit files");
836 y++;
837
838 svg("</g>\n\n");
839
840 svg("</svg>\n");
841
842 return 0;
843 }
844
845 static int list_dependencies_print(
846 const char *name,
847 unsigned level,
848 unsigned branches,
849 bool last,
850 UnitTimes *times,
851 BootTimes *boot) {
852
853 for (unsigned i = level; i != 0; i--)
854 printf("%s", special_glyph(branches & (1 << (i-1)) ? SPECIAL_GLYPH_TREE_VERTICAL : SPECIAL_GLYPH_TREE_SPACE));
855
856 printf("%s", special_glyph(last ? SPECIAL_GLYPH_TREE_RIGHT : SPECIAL_GLYPH_TREE_BRANCH));
857
858 if (times) {
859 if (times->time > 0)
860 printf("%s%s @%s +%s%s", ansi_highlight_red(), name,
861 FORMAT_TIMESPAN(times->activating - boot->userspace_time, USEC_PER_MSEC),
862 FORMAT_TIMESPAN(times->time, USEC_PER_MSEC), ansi_normal());
863 else if (times->activated > boot->userspace_time)
864 printf("%s @%s", name, FORMAT_TIMESPAN(times->activated - boot->userspace_time, USEC_PER_MSEC));
865 else
866 printf("%s", name);
867 } else
868 printf("%s", name);
869 printf("\n");
870
871 return 0;
872 }
873
874 static int list_dependencies_get_dependencies(sd_bus *bus, const char *name, char ***deps) {
875 _cleanup_free_ char *path = NULL;
876
877 assert(bus);
878 assert(name);
879 assert(deps);
880
881 path = unit_dbus_path_from_name(name);
882 if (!path)
883 return -ENOMEM;
884
885 return bus_get_unit_property_strv(bus, path, "After", deps);
886 }
887
888 static Hashmap *unit_times_hashmap;
889
890 static int list_dependencies_compare(char *const *a, char *const *b) {
891 usec_t usa = 0, usb = 0;
892 UnitTimes *times;
893
894 times = hashmap_get(unit_times_hashmap, *a);
895 if (times)
896 usa = times->activated;
897 times = hashmap_get(unit_times_hashmap, *b);
898 if (times)
899 usb = times->activated;
900
901 return CMP(usb, usa);
902 }
903
904 static bool times_in_range(const UnitTimes *times, const BootTimes *boot) {
905 return times && times->activated > 0 && times->activated <= boot->finish_time;
906 }
907
908 static int list_dependencies_one(sd_bus *bus, const char *name, unsigned level, char ***units, unsigned branches) {
909 _cleanup_strv_free_ char **deps = NULL;
910 char **c;
911 int r;
912 usec_t service_longest = 0;
913 int to_print = 0;
914 UnitTimes *times;
915 BootTimes *boot;
916
917 if (strv_extend(units, name))
918 return log_oom();
919
920 r = list_dependencies_get_dependencies(bus, name, &deps);
921 if (r < 0)
922 return r;
923
924 typesafe_qsort(deps, strv_length(deps), list_dependencies_compare);
925
926 r = acquire_boot_times(bus, &boot);
927 if (r < 0)
928 return r;
929
930 STRV_FOREACH(c, deps) {
931 times = hashmap_get(unit_times_hashmap, *c);
932 if (times_in_range(times, boot) && times->activated >= service_longest)
933 service_longest = times->activated;
934 }
935
936 if (service_longest == 0)
937 return r;
938
939 STRV_FOREACH(c, deps) {
940 times = hashmap_get(unit_times_hashmap, *c);
941 if (times_in_range(times, boot) && service_longest - times->activated <= arg_fuzz)
942 to_print++;
943 }
944
945 if (!to_print)
946 return r;
947
948 STRV_FOREACH(c, deps) {
949 times = hashmap_get(unit_times_hashmap, *c);
950 if (!times_in_range(times, boot) || service_longest - times->activated > arg_fuzz)
951 continue;
952
953 to_print--;
954
955 r = list_dependencies_print(*c, level, branches, to_print == 0, times, boot);
956 if (r < 0)
957 return r;
958
959 if (strv_contains(*units, *c)) {
960 r = list_dependencies_print("...", level + 1, (branches << 1) | (to_print ? 1 : 0),
961 true, NULL, boot);
962 if (r < 0)
963 return r;
964 continue;
965 }
966
967 r = list_dependencies_one(bus, *c, level + 1, units, (branches << 1) | (to_print ? 1 : 0));
968 if (r < 0)
969 return r;
970
971 if (to_print == 0)
972 break;
973 }
974 return 0;
975 }
976
977 static int list_dependencies(sd_bus *bus, const char *name) {
978 _cleanup_strv_free_ char **units = NULL;
979 UnitTimes *times;
980 int r;
981 const char *id;
982 _cleanup_free_ char *path = NULL;
983 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
984 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
985 BootTimes *boot;
986
987 assert(bus);
988
989 path = unit_dbus_path_from_name(name);
990 if (!path)
991 return -ENOMEM;
992
993 r = sd_bus_get_property(
994 bus,
995 "org.freedesktop.systemd1",
996 path,
997 "org.freedesktop.systemd1.Unit",
998 "Id",
999 &error,
1000 &reply,
1001 "s");
1002 if (r < 0)
1003 return log_error_errno(r, "Failed to get ID: %s", bus_error_message(&error, r));
1004
1005 r = sd_bus_message_read(reply, "s", &id);
1006 if (r < 0)
1007 return bus_log_parse_error(r);
1008
1009 times = hashmap_get(unit_times_hashmap, id);
1010
1011 r = acquire_boot_times(bus, &boot);
1012 if (r < 0)
1013 return r;
1014
1015 if (times) {
1016 if (times->time)
1017 printf("%s%s +%s%s\n", ansi_highlight_red(), id,
1018 FORMAT_TIMESPAN(times->time, USEC_PER_MSEC), ansi_normal());
1019 else if (times->activated > boot->userspace_time)
1020 printf("%s @%s\n", id,
1021 FORMAT_TIMESPAN(times->activated - boot->userspace_time, USEC_PER_MSEC));
1022 else
1023 printf("%s\n", id);
1024 }
1025
1026 return list_dependencies_one(bus, name, 0, &units, 0);
1027 }
1028
1029 static int analyze_critical_chain(int argc, char *argv[], void *userdata) {
1030 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1031 _cleanup_(unit_times_free_arrayp) UnitTimes *times = NULL;
1032 Hashmap *h;
1033 int n, r;
1034
1035 r = acquire_bus(&bus, NULL);
1036 if (r < 0)
1037 return bus_log_connect_error(r);
1038
1039 n = acquire_time_data(bus, &times);
1040 if (n <= 0)
1041 return n;
1042
1043 h = hashmap_new(&string_hash_ops);
1044 if (!h)
1045 return log_oom();
1046
1047 for (UnitTimes *u = times; u->has_data; u++) {
1048 r = hashmap_put(h, u->name, u);
1049 if (r < 0)
1050 return log_error_errno(r, "Failed to add entry to hashmap: %m");
1051 }
1052 unit_times_hashmap = h;
1053
1054 (void) pager_open(arg_pager_flags);
1055
1056 puts("The time when unit became active or started is printed after the \"@\" character.\n"
1057 "The time the unit took to start is printed after the \"+\" character.\n");
1058
1059 if (argc > 1) {
1060 char **name;
1061 STRV_FOREACH(name, strv_skip(argv, 1))
1062 list_dependencies(bus, *name);
1063 } else
1064 list_dependencies(bus, SPECIAL_DEFAULT_TARGET);
1065
1066 h = hashmap_free(h);
1067 return 0;
1068 }
1069
1070 static int analyze_blame(int argc, char *argv[], void *userdata) {
1071 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1072 _cleanup_(unit_times_free_arrayp) UnitTimes *times = NULL;
1073 _cleanup_(table_unrefp) Table *table = NULL;
1074 TableCell *cell;
1075 int n, r;
1076
1077 r = acquire_bus(&bus, NULL);
1078 if (r < 0)
1079 return bus_log_connect_error(r);
1080
1081 n = acquire_time_data(bus, &times);
1082 if (n <= 0)
1083 return n;
1084
1085 table = table_new("time", "unit");
1086 if (!table)
1087 return log_oom();
1088
1089 table_set_header(table, false);
1090
1091 assert_se(cell = table_get_cell(table, 0, 0));
1092 r = table_set_ellipsize_percent(table, cell, 100);
1093 if (r < 0)
1094 return r;
1095
1096 r = table_set_align_percent(table, cell, 100);
1097 if (r < 0)
1098 return r;
1099
1100 assert_se(cell = table_get_cell(table, 0, 1));
1101 r = table_set_ellipsize_percent(table, cell, 100);
1102 if (r < 0)
1103 return r;
1104
1105 r = table_set_sort(table, (size_t) 0);
1106 if (r < 0)
1107 return r;
1108
1109 r = table_set_reverse(table, 0, true);
1110 if (r < 0)
1111 return r;
1112
1113 for (UnitTimes *u = times; u->has_data; u++) {
1114 if (u->time <= 0)
1115 continue;
1116
1117 r = table_add_many(table,
1118 TABLE_TIMESPAN_MSEC, u->time,
1119 TABLE_STRING, u->name);
1120 if (r < 0)
1121 return table_log_add_error(r);
1122 }
1123
1124 (void) pager_open(arg_pager_flags);
1125
1126 return table_print(table, NULL);
1127 }
1128
1129 static int analyze_time(int argc, char *argv[], void *userdata) {
1130 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1131 _cleanup_free_ char *buf = NULL;
1132 int r;
1133
1134 r = acquire_bus(&bus, NULL);
1135 if (r < 0)
1136 return bus_log_connect_error(r);
1137
1138 r = pretty_boot_time(bus, &buf);
1139 if (r < 0)
1140 return r;
1141
1142 puts(buf);
1143 return 0;
1144 }
1145
1146 static int graph_one_property(
1147 sd_bus *bus,
1148 const UnitInfo *u,
1149 const char *prop,
1150 const char *color,
1151 char *patterns[],
1152 char *from_patterns[],
1153 char *to_patterns[]) {
1154
1155 _cleanup_strv_free_ char **units = NULL;
1156 char **unit;
1157 int r;
1158 bool match_patterns;
1159
1160 assert(u);
1161 assert(prop);
1162 assert(color);
1163
1164 match_patterns = strv_fnmatch(patterns, u->id);
1165
1166 if (!strv_isempty(from_patterns) && !match_patterns && !strv_fnmatch(from_patterns, u->id))
1167 return 0;
1168
1169 r = bus_get_unit_property_strv(bus, u->unit_path, prop, &units);
1170 if (r < 0)
1171 return r;
1172
1173 STRV_FOREACH(unit, units) {
1174 bool match_patterns2;
1175
1176 match_patterns2 = strv_fnmatch(patterns, *unit);
1177
1178 if (!strv_isempty(to_patterns) && !match_patterns2 && !strv_fnmatch(to_patterns, *unit))
1179 continue;
1180
1181 if (!strv_isempty(patterns) && !match_patterns && !match_patterns2)
1182 continue;
1183
1184 printf("\t\"%s\"->\"%s\" [color=\"%s\"];\n", u->id, *unit, color);
1185 }
1186
1187 return 0;
1188 }
1189
1190 static int graph_one(sd_bus *bus, const UnitInfo *u, char *patterns[], char *from_patterns[], char *to_patterns[]) {
1191 int r;
1192
1193 assert(bus);
1194 assert(u);
1195
1196 if (IN_SET(arg_dot, DEP_ORDER, DEP_ALL)) {
1197 r = graph_one_property(bus, u, "After", "green", patterns, from_patterns, to_patterns);
1198 if (r < 0)
1199 return r;
1200 }
1201
1202 if (IN_SET(arg_dot, DEP_REQUIRE, DEP_ALL)) {
1203 r = graph_one_property(bus, u, "Requires", "black", patterns, from_patterns, to_patterns);
1204 if (r < 0)
1205 return r;
1206 r = graph_one_property(bus, u, "Requisite", "darkblue", patterns, from_patterns, to_patterns);
1207 if (r < 0)
1208 return r;
1209 r = graph_one_property(bus, u, "Wants", "grey66", patterns, from_patterns, to_patterns);
1210 if (r < 0)
1211 return r;
1212 r = graph_one_property(bus, u, "Conflicts", "red", patterns, from_patterns, to_patterns);
1213 if (r < 0)
1214 return r;
1215 }
1216
1217 return 0;
1218 }
1219
1220 static int expand_patterns(sd_bus *bus, char **patterns, char ***ret) {
1221 _cleanup_strv_free_ char **expanded_patterns = NULL;
1222 char **pattern;
1223 int r;
1224
1225 STRV_FOREACH(pattern, patterns) {
1226 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1227 _cleanup_free_ char *unit = NULL, *unit_id = NULL;
1228
1229 if (strv_extend(&expanded_patterns, *pattern) < 0)
1230 return log_oom();
1231
1232 if (string_is_glob(*pattern))
1233 continue;
1234
1235 unit = unit_dbus_path_from_name(*pattern);
1236 if (!unit)
1237 return log_oom();
1238
1239 r = sd_bus_get_property_string(
1240 bus,
1241 "org.freedesktop.systemd1",
1242 unit,
1243 "org.freedesktop.systemd1.Unit",
1244 "Id",
1245 &error,
1246 &unit_id);
1247 if (r < 0)
1248 return log_error_errno(r, "Failed to get ID: %s", bus_error_message(&error, r));
1249
1250 if (!streq(*pattern, unit_id)) {
1251 if (strv_extend(&expanded_patterns, unit_id) < 0)
1252 return log_oom();
1253 }
1254 }
1255
1256 *ret = TAKE_PTR(expanded_patterns); /* do not free */
1257
1258 return 0;
1259 }
1260
1261 static int dot(int argc, char *argv[], void *userdata) {
1262 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1263 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1264 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1265 _cleanup_strv_free_ char **expanded_patterns = NULL;
1266 _cleanup_strv_free_ char **expanded_from_patterns = NULL;
1267 _cleanup_strv_free_ char **expanded_to_patterns = NULL;
1268 int r;
1269 UnitInfo u;
1270
1271 r = acquire_bus(&bus, NULL);
1272 if (r < 0)
1273 return bus_log_connect_error(r);
1274
1275 r = expand_patterns(bus, strv_skip(argv, 1), &expanded_patterns);
1276 if (r < 0)
1277 return r;
1278
1279 r = expand_patterns(bus, arg_dot_from_patterns, &expanded_from_patterns);
1280 if (r < 0)
1281 return r;
1282
1283 r = expand_patterns(bus, arg_dot_to_patterns, &expanded_to_patterns);
1284 if (r < 0)
1285 return r;
1286
1287 r = bus_call_method(bus, bus_systemd_mgr, "ListUnits", &error, &reply, NULL);
1288 if (r < 0)
1289 log_error_errno(r, "Failed to list units: %s", bus_error_message(&error, r));
1290
1291 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)");
1292 if (r < 0)
1293 return bus_log_parse_error(r);
1294
1295 printf("digraph systemd {\n");
1296
1297 while ((r = bus_parse_unit_info(reply, &u)) > 0) {
1298
1299 r = graph_one(bus, &u, expanded_patterns, expanded_from_patterns, expanded_to_patterns);
1300 if (r < 0)
1301 return r;
1302 }
1303 if (r < 0)
1304 return bus_log_parse_error(r);
1305
1306 printf("}\n");
1307
1308 log_info(" Color legend: black = Requires\n"
1309 " dark blue = Requisite\n"
1310 " dark grey = Wants\n"
1311 " red = Conflicts\n"
1312 " green = After\n");
1313
1314 if (on_tty())
1315 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
1316 "-- Try a shell pipeline like 'systemd-analyze dot | dot -Tsvg > systemd.svg'!\n");
1317
1318 return 0;
1319 }
1320
1321 static int dump_fallback(sd_bus *bus) {
1322 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1323 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1324 const char *text = NULL;
1325 int r;
1326
1327 assert(bus);
1328
1329 r = bus_call_method(bus, bus_systemd_mgr, "Dump", &error, &reply, NULL);
1330 if (r < 0)
1331 return log_error_errno(r, "Failed to issue method call Dump: %s", bus_error_message(&error, r));
1332
1333 r = sd_bus_message_read(reply, "s", &text);
1334 if (r < 0)
1335 return bus_log_parse_error(r);
1336
1337 fputs(text, stdout);
1338 return 0;
1339 }
1340
1341 static int dump(int argc, char *argv[], void *userdata) {
1342 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1343 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1344 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1345 int fd = -1;
1346 int r;
1347
1348 r = acquire_bus(&bus, NULL);
1349 if (r < 0)
1350 return bus_log_connect_error(r);
1351
1352 (void) pager_open(arg_pager_flags);
1353
1354 if (!sd_bus_can_send(bus, SD_BUS_TYPE_UNIX_FD))
1355 return dump_fallback(bus);
1356
1357 r = bus_call_method(bus, bus_systemd_mgr, "DumpByFileDescriptor", &error, &reply, NULL);
1358 if (r < 0) {
1359 /* fall back to Dump if DumpByFileDescriptor is not supported */
1360 if (!IN_SET(r, -EACCES, -EBADR))
1361 return log_error_errno(r, "Failed to issue method call DumpByFileDescriptor: %s",
1362 bus_error_message(&error, r));
1363
1364 return dump_fallback(bus);
1365 }
1366
1367 r = sd_bus_message_read(reply, "h", &fd);
1368 if (r < 0)
1369 return bus_log_parse_error(r);
1370
1371 fflush(stdout);
1372 return copy_bytes(fd, STDOUT_FILENO, UINT64_MAX, 0);
1373 }
1374
1375 static int cat_config(int argc, char *argv[], void *userdata) {
1376 char **arg, **list;
1377 int r;
1378
1379 (void) pager_open(arg_pager_flags);
1380
1381 list = strv_skip(argv, 1);
1382 STRV_FOREACH(arg, list) {
1383 const char *t = NULL;
1384
1385 if (arg != list)
1386 print_separator();
1387
1388 if (path_is_absolute(*arg)) {
1389 const char *dir;
1390
1391 NULSTR_FOREACH(dir, CONF_PATHS_NULSTR("")) {
1392 t = path_startswith(*arg, dir);
1393 if (t)
1394 break;
1395 }
1396
1397 if (!t)
1398 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1399 "Path %s does not start with any known prefix.", *arg);
1400 } else
1401 t = *arg;
1402
1403 r = conf_files_cat(arg_root, t);
1404 if (r < 0)
1405 return r;
1406 }
1407
1408 return 0;
1409 }
1410
1411 static int verb_log_control(int argc, char *argv[], void *userdata) {
1412 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1413 int r;
1414
1415 assert(IN_SET(argc, 1, 2));
1416
1417 r = acquire_bus(&bus, NULL);
1418 if (r < 0)
1419 return bus_log_connect_error(r);
1420
1421 return verb_log_control_common(bus, "org.freedesktop.systemd1", argv[0], argc == 2 ? argv[1] : NULL);
1422 }
1423
1424 static bool strv_fnmatch_strv_or_empty(char* const* patterns, char **strv, int flags) {
1425 char **s;
1426 STRV_FOREACH(s, strv)
1427 if (strv_fnmatch_or_empty(patterns, *s, flags))
1428 return true;
1429
1430 return false;
1431 }
1432
1433 static int do_unit_files(int argc, char *argv[], void *userdata) {
1434 _cleanup_(lookup_paths_free) LookupPaths lp = {};
1435 _cleanup_hashmap_free_ Hashmap *unit_ids = NULL;
1436 _cleanup_hashmap_free_ Hashmap *unit_names = NULL;
1437 char **patterns = strv_skip(argv, 1);
1438 const char *k, *dst;
1439 char **v;
1440 int r;
1441
1442 r = lookup_paths_init(&lp, arg_scope, 0, NULL);
1443 if (r < 0)
1444 return log_error_errno(r, "lookup_paths_init() failed: %m");
1445
1446 r = unit_file_build_name_map(&lp, NULL, &unit_ids, &unit_names, NULL);
1447 if (r < 0)
1448 return log_error_errno(r, "unit_file_build_name_map() failed: %m");
1449
1450 HASHMAP_FOREACH_KEY(dst, k, unit_ids) {
1451 if (!strv_fnmatch_or_empty(patterns, k, FNM_NOESCAPE) &&
1452 !strv_fnmatch_or_empty(patterns, dst, FNM_NOESCAPE))
1453 continue;
1454
1455 printf("ids: %s → %s\n", k, dst);
1456 }
1457
1458 HASHMAP_FOREACH_KEY(v, k, unit_names) {
1459 if (!strv_fnmatch_or_empty(patterns, k, FNM_NOESCAPE) &&
1460 !strv_fnmatch_strv_or_empty(patterns, v, FNM_NOESCAPE))
1461 continue;
1462
1463 _cleanup_free_ char *j = strv_join(v, ", ");
1464 printf("aliases: %s ← %s\n", k, j);
1465 }
1466
1467 return 0;
1468 }
1469
1470 static int dump_unit_paths(int argc, char *argv[], void *userdata) {
1471 _cleanup_(lookup_paths_free) LookupPaths paths = {};
1472 int r;
1473 char **p;
1474
1475 r = lookup_paths_init(&paths, arg_scope, 0, NULL);
1476 if (r < 0)
1477 return log_error_errno(r, "lookup_paths_init() failed: %m");
1478
1479 STRV_FOREACH(p, paths.search_path)
1480 puts(*p);
1481
1482 return 0;
1483 }
1484
1485 static int dump_exit_status(int argc, char *argv[], void *userdata) {
1486 _cleanup_(table_unrefp) Table *table = NULL;
1487 int r;
1488
1489 table = table_new("name", "status", "class");
1490 if (!table)
1491 return log_oom();
1492
1493 r = table_set_align_percent(table, table_get_cell(table, 0, 1), 100);
1494 if (r < 0)
1495 return log_error_errno(r, "Failed to right-align status: %m");
1496
1497 if (strv_isempty(strv_skip(argv, 1)))
1498 for (size_t i = 0; i < ELEMENTSOF(exit_status_mappings); i++) {
1499 if (!exit_status_mappings[i].name)
1500 continue;
1501
1502 r = table_add_many(table,
1503 TABLE_STRING, exit_status_mappings[i].name,
1504 TABLE_INT, (int) i,
1505 TABLE_STRING, exit_status_class(i));
1506 if (r < 0)
1507 return table_log_add_error(r);
1508 }
1509 else
1510 for (int i = 1; i < argc; i++) {
1511 int status;
1512
1513 status = exit_status_from_string(argv[i]);
1514 if (status < 0)
1515 return log_error_errno(status, "Invalid exit status \"%s\".", argv[i]);
1516
1517 assert(status >= 0 && (size_t) status < ELEMENTSOF(exit_status_mappings));
1518 r = table_add_many(table,
1519 TABLE_STRING, exit_status_mappings[status].name ?: "-",
1520 TABLE_INT, status,
1521 TABLE_STRING, exit_status_class(status) ?: "-");
1522 if (r < 0)
1523 return table_log_add_error(r);
1524 }
1525
1526 (void) pager_open(arg_pager_flags);
1527
1528 return table_print(table, NULL);
1529 }
1530
1531 static int dump_capabilities(int argc, char *argv[], void *userdata) {
1532 _cleanup_(table_unrefp) Table *table = NULL;
1533 unsigned last_cap;
1534 int r;
1535
1536 table = table_new("name", "number");
1537 if (!table)
1538 return log_oom();
1539
1540 (void) table_set_align_percent(table, table_get_cell(table, 0, 1), 100);
1541
1542 /* Determine the maximum of the last cap known by the kernel and by us */
1543 last_cap = MAX((unsigned) CAP_LAST_CAP, cap_last_cap());
1544
1545 if (strv_isempty(strv_skip(argv, 1)))
1546 for (unsigned c = 0; c <= last_cap; c++) {
1547 r = table_add_many(table,
1548 TABLE_STRING, capability_to_name(c) ?: "cap_???",
1549 TABLE_UINT, c);
1550 if (r < 0)
1551 return table_log_add_error(r);
1552 }
1553 else {
1554 for (int i = 1; i < argc; i++) {
1555 int c;
1556
1557 c = capability_from_name(argv[i]);
1558 if (c < 0 || (unsigned) c > last_cap)
1559 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Capability \"%s\" not known.", argv[i]);
1560
1561 r = table_add_many(table,
1562 TABLE_STRING, capability_to_name(c) ?: "cap_???",
1563 TABLE_UINT, (unsigned) c);
1564 if (r < 0)
1565 return table_log_add_error(r);
1566 }
1567
1568 (void) table_set_sort(table, (size_t) 1);
1569 }
1570
1571 (void) pager_open(arg_pager_flags);
1572
1573 return table_print(table, NULL);
1574 }
1575
1576 #if HAVE_SECCOMP
1577
1578 static int load_kernel_syscalls(Set **ret) {
1579 _cleanup_set_free_ Set *syscalls = NULL;
1580 _cleanup_fclose_ FILE *f = NULL;
1581 int r;
1582
1583 /* Let's read the available system calls from the list of available tracing events. Slightly dirty,
1584 * but good enough for analysis purposes. */
1585
1586 f = fopen("/sys/kernel/tracing/available_events", "re");
1587 if (!f) {
1588 /* We tried the non-debugfs mount point and that didn't work. If it wasn't mounted, maybe the
1589 * old debugfs mount point works? */
1590 f = fopen("/sys/kernel/debug/tracing/available_events", "re");
1591 if (!f)
1592 return log_full_errno(IN_SET(errno, EPERM, EACCES, ENOENT) ? LOG_DEBUG : LOG_WARNING, errno,
1593 "Can't read open tracefs' available_events file: %m");
1594 }
1595
1596 for (;;) {
1597 _cleanup_free_ char *line = NULL;
1598 const char *e;
1599
1600 r = read_line(f, LONG_LINE_MAX, &line);
1601 if (r < 0)
1602 return log_error_errno(r, "Failed to read system call list: %m");
1603 if (r == 0)
1604 break;
1605
1606 e = startswith(line, "syscalls:sys_enter_");
1607 if (!e)
1608 continue;
1609
1610 /* These are named differently inside the kernel than their external name for historical
1611 * reasons. Let's hide them here. */
1612 if (STR_IN_SET(e, "newuname", "newfstat", "newstat", "newlstat", "sysctl"))
1613 continue;
1614
1615 r = set_put_strdup(&syscalls, e);
1616 if (r < 0)
1617 return log_error_errno(r, "Failed to add system call to list: %m");
1618 }
1619
1620 *ret = TAKE_PTR(syscalls);
1621 return 0;
1622 }
1623
1624 static void syscall_set_remove(Set *s, const SyscallFilterSet *set) {
1625 const char *syscall;
1626
1627 if (!set)
1628 return;
1629
1630 NULSTR_FOREACH(syscall, set->value) {
1631 if (syscall[0] == '@')
1632 continue;
1633
1634 free(set_remove(s, syscall));
1635 }
1636 }
1637
1638 static void dump_syscall_filter(const SyscallFilterSet *set) {
1639 const char *syscall;
1640
1641 printf("%s%s%s\n"
1642 " # %s\n",
1643 ansi_highlight(),
1644 set->name,
1645 ansi_normal(),
1646 set->help);
1647
1648 NULSTR_FOREACH(syscall, set->value)
1649 printf(" %s%s%s\n", syscall[0] == '@' ? ansi_underline() : "", syscall, ansi_normal());
1650 }
1651
1652 static int dump_syscall_filters(int argc, char *argv[], void *userdata) {
1653 bool first = true;
1654
1655 (void) pager_open(arg_pager_flags);
1656
1657 if (strv_isempty(strv_skip(argv, 1))) {
1658 _cleanup_set_free_ Set *kernel = NULL, *known = NULL;
1659 const char *sys;
1660 int k;
1661
1662 NULSTR_FOREACH(sys, syscall_filter_sets[SYSCALL_FILTER_SET_KNOWN].value)
1663 if (set_put_strdup(&known, sys) < 0)
1664 return log_oom();
1665
1666 k = load_kernel_syscalls(&kernel);
1667
1668 for (int i = 0; i < _SYSCALL_FILTER_SET_MAX; i++) {
1669 const SyscallFilterSet *set = syscall_filter_sets + i;
1670 if (!first)
1671 puts("");
1672
1673 dump_syscall_filter(set);
1674 syscall_set_remove(kernel, set);
1675 if (i != SYSCALL_FILTER_SET_KNOWN)
1676 syscall_set_remove(known, set);
1677 first = false;
1678 }
1679
1680 if (!set_isempty(known)) {
1681 _cleanup_free_ char **l = NULL;
1682 char **syscall;
1683
1684 printf("\n"
1685 "# %sUngrouped System Calls%s (known but not included in any of the groups except @known):\n",
1686 ansi_highlight(), ansi_normal());
1687
1688 l = set_get_strv(known);
1689 if (!l)
1690 return log_oom();
1691
1692 strv_sort(l);
1693
1694 STRV_FOREACH(syscall, l)
1695 printf("# %s\n", *syscall);
1696 }
1697
1698 if (k < 0) {
1699 fputc('\n', stdout);
1700 fflush(stdout);
1701 log_notice_errno(k, "# Not showing unlisted system calls, couldn't retrieve kernel system call list: %m");
1702 } else if (!set_isempty(kernel)) {
1703 _cleanup_free_ char **l = NULL;
1704 char **syscall;
1705
1706 printf("\n"
1707 "# %sUnlisted System Calls%s (supported by the local kernel, but not included in any of the groups listed above):\n",
1708 ansi_highlight(), ansi_normal());
1709
1710 l = set_get_strv(kernel);
1711 if (!l)
1712 return log_oom();
1713
1714 strv_sort(l);
1715
1716 STRV_FOREACH(syscall, l)
1717 printf("# %s\n", *syscall);
1718 }
1719 } else {
1720 char **name;
1721
1722 STRV_FOREACH(name, strv_skip(argv, 1)) {
1723 const SyscallFilterSet *set;
1724
1725 if (!first)
1726 puts("");
1727
1728 set = syscall_filter_set_find(*name);
1729 if (!set) {
1730 /* make sure the error appears below normal output */
1731 fflush(stdout);
1732
1733 return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
1734 "Filter set \"%s\" not found.", *name);
1735 }
1736
1737 dump_syscall_filter(set);
1738 first = false;
1739 }
1740 }
1741
1742 return 0;
1743 }
1744
1745 #else
1746 static int dump_syscall_filters(int argc, char *argv[], void *userdata) {
1747 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Not compiled with syscall filters, sorry.");
1748 }
1749 #endif
1750
1751 static int load_available_kernel_filesystems(Set **ret) {
1752 _cleanup_set_free_ Set *filesystems = NULL;
1753 int r;
1754 char *t;
1755
1756 assert(ret);
1757
1758 /* Let's read the available filesystems */
1759
1760 r = read_virtual_file("/proc/filesystems", SIZE_MAX, &t, NULL);
1761 if (r < 0)
1762 return r;
1763
1764 for (int i = 0;;) {
1765 _cleanup_free_ char *line = NULL;
1766 const char *p;
1767
1768 r = string_extract_line(t, i++, &line);
1769 if (r < 0)
1770 return log_oom();
1771 if (r == 0)
1772 break;
1773
1774 if (!line)
1775 line = t;
1776
1777 p = strchr(line, '\t');
1778 if (!p)
1779 continue;
1780
1781 p += strspn(p, WHITESPACE);
1782
1783 r = set_put_strdup(&filesystems, p);
1784 if (r < 0)
1785 return log_error_errno(r, "Failed to add filesystem to list: %m");
1786 }
1787
1788 *ret = TAKE_PTR(filesystems);
1789 return 0;
1790 }
1791
1792 static void filesystem_set_remove(Set *s, const FilesystemSet *set) {
1793 const char *filesystem;
1794
1795 NULSTR_FOREACH(filesystem, set->value) {
1796 if (filesystem[0] == '@')
1797 continue;
1798
1799 free(set_remove(s, filesystem));
1800 }
1801 }
1802
1803 static void dump_filesystem(const FilesystemSet *set) {
1804 const char *filesystem;
1805
1806 if (!set)
1807 return;
1808
1809 printf("%s%s%s\n"
1810 " # %s\n",
1811 ansi_highlight(),
1812 set->name,
1813 ansi_normal(),
1814 set->help);
1815
1816 NULSTR_FOREACH(filesystem, set->value)
1817 printf(" %s%s%s\n", filesystem[0] == '@' ? ansi_underline() : "", filesystem, ansi_normal());
1818 }
1819
1820 static int dump_filesystems(int argc, char *argv[], void *userdata) {
1821 bool first = true;
1822
1823 #if ! HAVE_LIBBPF
1824 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Not compiled with libbpf support, sorry.");
1825 #endif
1826
1827 (void) pager_open(arg_pager_flags);
1828
1829 if (strv_isempty(strv_skip(argv, 1))) {
1830 _cleanup_set_free_ Set *kernel = NULL, *known = NULL;
1831 const char *fs;
1832 int k;
1833
1834 NULSTR_FOREACH(fs, filesystem_sets[FILESYSTEM_SET_KNOWN].value)
1835 if (set_put_strdup(&known, fs) < 0)
1836 return log_oom();
1837
1838 k = load_available_kernel_filesystems(&kernel);
1839
1840 for (FilesystemGroups i = 0; i < _FILESYSTEM_SET_MAX; i++) {
1841 const FilesystemSet *set = filesystem_sets + i;
1842 if (!first)
1843 puts("");
1844
1845 dump_filesystem(set);
1846 filesystem_set_remove(kernel, set);
1847 if (i != FILESYSTEM_SET_KNOWN)
1848 filesystem_set_remove(known, set);
1849 first = false;
1850 }
1851
1852 if (!set_isempty(known)) {
1853 _cleanup_free_ char **l = NULL;
1854 char **filesystem;
1855
1856 printf("\n"
1857 "# %sUngrouped filesystems%s (known but not included in any of the groups except @known):\n",
1858 ansi_highlight(), ansi_normal());
1859
1860 l = set_get_strv(known);
1861 if (!l)
1862 return log_oom();
1863
1864 strv_sort(l);
1865
1866 STRV_FOREACH(filesystem, l)
1867 printf("# %s\n", *filesystem);
1868 }
1869
1870 if (k < 0) {
1871 fputc('\n', stdout);
1872 fflush(stdout);
1873 log_notice_errno(k, "# Not showing unlisted filesystems, couldn't retrieve kernel filesystem list: %m");
1874 } else if (!set_isempty(kernel)) {
1875 _cleanup_free_ char **l = NULL;
1876 char **filesystem;
1877
1878 printf("\n"
1879 "# %sUnlisted filesystems%s (available to the local kernel, but not included in any of the groups listed above):\n",
1880 ansi_highlight(), ansi_normal());
1881
1882 l = set_get_strv(kernel);
1883 if (!l)
1884 return log_oom();
1885
1886 strv_sort(l);
1887
1888 STRV_FOREACH(filesystem, l)
1889 printf("# %s\n", *filesystem);
1890 }
1891 } else {
1892 char **name;
1893
1894 STRV_FOREACH(name, strv_skip(argv, 1)) {
1895 const FilesystemSet *set;
1896
1897 if (!first)
1898 puts("");
1899
1900 set = filesystem_set_find(*name);
1901 if (!set) {
1902 /* make sure the error appears below normal output */
1903 fflush(stdout);
1904
1905 return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
1906 "Filesystem set \"%s\" not found.", *name);
1907 }
1908
1909 dump_filesystem(set);
1910 first = false;
1911 }
1912 }
1913
1914 return 0;
1915 }
1916
1917 static void parsing_hint(const char *p, bool calendar, bool timestamp, bool timespan) {
1918 if (calendar && calendar_spec_from_string(p, NULL) >= 0)
1919 log_notice("Hint: this expression is a valid calendar specification. "
1920 "Use 'systemd-analyze calendar \"%s\"' instead?", p);
1921 if (timestamp && parse_timestamp(p, NULL) >= 0)
1922 log_notice("Hint: this expression is a valid timestamp. "
1923 "Use 'systemd-analyze timestamp \"%s\"' instead?", p);
1924 if (timespan && parse_time(p, NULL, USEC_PER_SEC) >= 0)
1925 log_notice("Hint: this expression is a valid timespan. "
1926 "Use 'systemd-analyze timespan \"%s\"' instead?", p);
1927 }
1928
1929 static int dump_timespan(int argc, char *argv[], void *userdata) {
1930 char **input_timespan;
1931
1932 STRV_FOREACH(input_timespan, strv_skip(argv, 1)) {
1933 _cleanup_(table_unrefp) Table *table = NULL;
1934 usec_t output_usecs;
1935 TableCell *cell;
1936 int r;
1937
1938 r = parse_time(*input_timespan, &output_usecs, USEC_PER_SEC);
1939 if (r < 0) {
1940 log_error_errno(r, "Failed to parse time span '%s': %m", *input_timespan);
1941 parsing_hint(*input_timespan, true, true, false);
1942 return r;
1943 }
1944
1945 table = table_new("name", "value");
1946 if (!table)
1947 return log_oom();
1948
1949 table_set_header(table, false);
1950
1951 assert_se(cell = table_get_cell(table, 0, 0));
1952 r = table_set_ellipsize_percent(table, cell, 100);
1953 if (r < 0)
1954 return r;
1955
1956 r = table_set_align_percent(table, cell, 100);
1957 if (r < 0)
1958 return r;
1959
1960 assert_se(cell = table_get_cell(table, 0, 1));
1961 r = table_set_ellipsize_percent(table, cell, 100);
1962 if (r < 0)
1963 return r;
1964
1965 r = table_add_many(table,
1966 TABLE_STRING, "Original:",
1967 TABLE_STRING, *input_timespan);
1968 if (r < 0)
1969 return table_log_add_error(r);
1970
1971 r = table_add_cell_stringf(table, NULL, "%ss:", special_glyph(SPECIAL_GLYPH_MU));
1972 if (r < 0)
1973 return table_log_add_error(r);
1974
1975 r = table_add_many(table,
1976 TABLE_UINT64, output_usecs,
1977 TABLE_STRING, "Human:",
1978 TABLE_TIMESPAN, output_usecs,
1979 TABLE_SET_COLOR, ansi_highlight());
1980 if (r < 0)
1981 return table_log_add_error(r);
1982
1983 r = table_print(table, NULL);
1984 if (r < 0)
1985 return r;
1986
1987 if (input_timespan[1])
1988 putchar('\n');
1989 }
1990
1991 return EXIT_SUCCESS;
1992 }
1993
1994 static int test_timestamp_one(const char *p) {
1995 _cleanup_(table_unrefp) Table *table = NULL;
1996 TableCell *cell;
1997 usec_t usec;
1998 int r;
1999
2000 r = parse_timestamp(p, &usec);
2001 if (r < 0) {
2002 log_error_errno(r, "Failed to parse \"%s\": %m", p);
2003 parsing_hint(p, true, false, true);
2004 return r;
2005 }
2006
2007 table = table_new("name", "value");
2008 if (!table)
2009 return log_oom();
2010
2011 table_set_header(table, false);
2012
2013 assert_se(cell = table_get_cell(table, 0, 0));
2014 r = table_set_ellipsize_percent(table, cell, 100);
2015 if (r < 0)
2016 return r;
2017
2018 r = table_set_align_percent(table, cell, 100);
2019 if (r < 0)
2020 return r;
2021
2022 assert_se(cell = table_get_cell(table, 0, 1));
2023 r = table_set_ellipsize_percent(table, cell, 100);
2024 if (r < 0)
2025 return r;
2026
2027 r = table_add_many(table,
2028 TABLE_STRING, "Original form:",
2029 TABLE_STRING, p,
2030 TABLE_STRING, "Normalized form:",
2031 TABLE_TIMESTAMP, usec,
2032 TABLE_SET_COLOR, ansi_highlight_blue());
2033 if (r < 0)
2034 return table_log_add_error(r);
2035
2036 if (!in_utc_timezone()) {
2037 r = table_add_many(table,
2038 TABLE_STRING, "(in UTC):",
2039 TABLE_TIMESTAMP_UTC, usec);
2040 if (r < 0)
2041 return table_log_add_error(r);
2042 }
2043
2044 r = table_add_cell(table, NULL, TABLE_STRING, "UNIX seconds:");
2045 if (r < 0)
2046 return table_log_add_error(r);
2047
2048 if (usec % USEC_PER_SEC == 0)
2049 r = table_add_cell_stringf(table, NULL, "@%"PRI_USEC,
2050 usec / USEC_PER_SEC);
2051 else
2052 r = table_add_cell_stringf(table, NULL, "@%"PRI_USEC".%06"PRI_USEC"",
2053 usec / USEC_PER_SEC,
2054 usec % USEC_PER_SEC);
2055 if (r < 0)
2056 return r;
2057
2058 r = table_add_many(table,
2059 TABLE_STRING, "From now:",
2060 TABLE_TIMESTAMP_RELATIVE, usec);
2061 if (r < 0)
2062 return table_log_add_error(r);
2063
2064 return table_print(table, NULL);
2065 }
2066
2067 static int test_timestamp(int argc, char *argv[], void *userdata) {
2068 int ret = 0, r;
2069 char **p;
2070
2071 STRV_FOREACH(p, strv_skip(argv, 1)) {
2072 r = test_timestamp_one(*p);
2073 if (ret == 0 && r < 0)
2074 ret = r;
2075
2076 if (*(p + 1))
2077 putchar('\n');
2078 }
2079
2080 return ret;
2081 }
2082
2083 static int test_calendar_one(usec_t n, const char *p) {
2084 _cleanup_(calendar_spec_freep) CalendarSpec *spec = NULL;
2085 _cleanup_(table_unrefp) Table *table = NULL;
2086 _cleanup_free_ char *t = NULL;
2087 TableCell *cell;
2088 int r;
2089
2090 r = calendar_spec_from_string(p, &spec);
2091 if (r < 0) {
2092 log_error_errno(r, "Failed to parse calendar specification '%s': %m", p);
2093 parsing_hint(p, false, true, true);
2094 return r;
2095 }
2096
2097 r = calendar_spec_to_string(spec, &t);
2098 if (r < 0)
2099 return log_error_errno(r, "Failed to format calendar specification '%s': %m", p);
2100
2101 table = table_new("name", "value");
2102 if (!table)
2103 return log_oom();
2104
2105 table_set_header(table, false);
2106
2107 assert_se(cell = table_get_cell(table, 0, 0));
2108 r = table_set_ellipsize_percent(table, cell, 100);
2109 if (r < 0)
2110 return r;
2111
2112 r = table_set_align_percent(table, cell, 100);
2113 if (r < 0)
2114 return r;
2115
2116 assert_se(cell = table_get_cell(table, 0, 1));
2117 r = table_set_ellipsize_percent(table, cell, 100);
2118 if (r < 0)
2119 return r;
2120
2121 if (!streq(t, p)) {
2122 r = table_add_many(table,
2123 TABLE_STRING, "Original form:",
2124 TABLE_STRING, p);
2125 if (r < 0)
2126 return table_log_add_error(r);
2127 }
2128
2129 r = table_add_many(table,
2130 TABLE_STRING, "Normalized form:",
2131 TABLE_STRING, t);
2132 if (r < 0)
2133 return table_log_add_error(r);
2134
2135 for (unsigned i = 0; i < arg_iterations; i++) {
2136 usec_t next;
2137
2138 r = calendar_spec_next_usec(spec, n, &next);
2139 if (r == -ENOENT) {
2140 if (i == 0) {
2141 r = table_add_many(table,
2142 TABLE_STRING, "Next elapse:",
2143 TABLE_STRING, "never",
2144 TABLE_SET_COLOR, ansi_highlight_yellow());
2145 if (r < 0)
2146 return table_log_add_error(r);
2147 }
2148 break;
2149 }
2150 if (r < 0)
2151 return log_error_errno(r, "Failed to determine next elapse for '%s': %m", p);
2152
2153 if (i == 0) {
2154 r = table_add_many(table,
2155 TABLE_STRING, "Next elapse:",
2156 TABLE_TIMESTAMP, next,
2157 TABLE_SET_COLOR, ansi_highlight_blue());
2158 if (r < 0)
2159 return table_log_add_error(r);
2160 } else {
2161 int k = DECIMAL_STR_WIDTH(i + 1);
2162
2163 if (k < 8)
2164 k = 8 - k;
2165 else
2166 k = 0;
2167
2168 r = table_add_cell_stringf(table, NULL, "Iter. #%u:", i+1);
2169 if (r < 0)
2170 return table_log_add_error(r);
2171
2172 r = table_add_many(table,
2173 TABLE_TIMESTAMP, next,
2174 TABLE_SET_COLOR, ansi_highlight_blue());
2175 if (r < 0)
2176 return table_log_add_error(r);
2177 }
2178
2179 if (!in_utc_timezone()) {
2180 r = table_add_many(table,
2181 TABLE_STRING, "(in UTC):",
2182 TABLE_TIMESTAMP_UTC, next);
2183 if (r < 0)
2184 return table_log_add_error(r);
2185 }
2186
2187 r = table_add_many(table,
2188 TABLE_STRING, "From now:",
2189 TABLE_TIMESTAMP_RELATIVE, next);
2190 if (r < 0)
2191 return table_log_add_error(r);
2192
2193 n = next;
2194 }
2195
2196 return table_print(table, NULL);
2197 }
2198
2199 static int test_calendar(int argc, char *argv[], void *userdata) {
2200 int ret = 0, r;
2201 char **p;
2202 usec_t n;
2203
2204 if (arg_base_time != USEC_INFINITY)
2205 n = arg_base_time;
2206 else
2207 n = now(CLOCK_REALTIME); /* We want to use the same "base" for all expressions */
2208
2209 STRV_FOREACH(p, strv_skip(argv, 1)) {
2210 r = test_calendar_one(n, *p);
2211 if (ret == 0 && r < 0)
2212 ret = r;
2213
2214 if (*(p + 1))
2215 putchar('\n');
2216 }
2217
2218 return ret;
2219 }
2220
2221 static int service_watchdogs(int argc, char *argv[], void *userdata) {
2222 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2223 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
2224 int b, r;
2225
2226 assert(IN_SET(argc, 1, 2));
2227 assert(argv);
2228
2229 r = acquire_bus(&bus, NULL);
2230 if (r < 0)
2231 return bus_log_connect_error(r);
2232
2233 if (argc == 1) {
2234 /* get ServiceWatchdogs */
2235 r = bus_get_property_trivial(bus, bus_systemd_mgr, "ServiceWatchdogs", &error, 'b', &b);
2236 if (r < 0)
2237 return log_error_errno(r, "Failed to get service-watchdog state: %s", bus_error_message(&error, r));
2238
2239 printf("%s\n", yes_no(!!b));
2240
2241 } else {
2242 /* set ServiceWatchdogs */
2243 b = parse_boolean(argv[1]);
2244 if (b < 0)
2245 return log_error_errno(b, "Failed to parse service-watchdogs argument: %m");
2246
2247 r = bus_set_property(bus, bus_systemd_mgr, "ServiceWatchdogs", &error, "b", b);
2248 if (r < 0)
2249 return log_error_errno(r, "Failed to set service-watchdog state: %s", bus_error_message(&error, r));
2250 }
2251
2252 return 0;
2253 }
2254
2255 static int do_condition(int argc, char *argv[], void *userdata) {
2256 return verify_conditions(strv_skip(argv, 1), arg_scope, arg_unit, arg_root);
2257 }
2258
2259 static int do_verify(int argc, char *argv[], void *userdata) {
2260 return verify_units(strv_skip(argv, 1), arg_scope, arg_man, arg_generators, arg_recursive_errors, arg_root);
2261 }
2262
2263 static int do_security(int argc, char *argv[], void *userdata) {
2264 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
2265 _cleanup_(json_variant_unrefp) JsonVariant *policy = NULL;
2266 int r;
2267 unsigned line, column;
2268
2269 r = acquire_bus(&bus, NULL);
2270 if (r < 0)
2271 return bus_log_connect_error(r);
2272
2273 (void) pager_open(arg_pager_flags);
2274
2275 if (arg_security_policy) {
2276 r = json_parse_file(/*f=*/ NULL, arg_security_policy, /*flags=*/ 0, &policy, &line, &column);
2277 if (r < 0)
2278 return log_error_errno(r, "Failed to parse '%s' at %u:%u: %m", arg_security_policy, line, column);
2279 } else {
2280 _cleanup_fclose_ FILE *f = NULL;
2281 _cleanup_free_ char *pp = NULL;
2282
2283 r = search_and_fopen_nulstr("systemd-analyze-security.policy", "re", /*root=*/ NULL, CONF_PATHS_NULSTR("systemd"), &f, &pp);
2284 if (r < 0 && r != -ENOENT)
2285 return r;
2286
2287 if (f) {
2288 r = json_parse_file(f, pp, /*flags=*/ 0, &policy, &line, &column);
2289 if (r < 0)
2290 return log_error_errno(r, "[%s:%u:%u] Failed to parse JSON policy: %m", pp, line, column);
2291 }
2292 }
2293
2294 return analyze_security(bus,
2295 strv_skip(argv, 1),
2296 policy,
2297 arg_scope,
2298 arg_man,
2299 arg_generators,
2300 arg_offline,
2301 arg_threshold,
2302 arg_root,
2303 arg_json_format_flags,
2304 arg_pager_flags,
2305 /*flags=*/ 0);
2306 }
2307
2308 static int help(int argc, char *argv[], void *userdata) {
2309 _cleanup_free_ char *link = NULL, *dot_link = NULL;
2310 int r;
2311
2312 (void) pager_open(arg_pager_flags);
2313
2314 r = terminal_urlify_man("systemd-analyze", "1", &link);
2315 if (r < 0)
2316 return log_oom();
2317
2318 /* Not using terminal_urlify_man() for this, since we don't want the "man page" text suffix in this case. */
2319 r = terminal_urlify("man:dot(1)", "dot(1)", &dot_link);
2320 if (r < 0)
2321 return log_oom();
2322
2323 printf("%s [OPTIONS...] COMMAND ...\n\n"
2324 "%sProfile systemd, show unit dependencies, check unit files.%s\n"
2325 "\nCommands:\n"
2326 " [time] Print time required to boot the machine\n"
2327 " blame Print list of running units ordered by\n"
2328 " time to init\n"
2329 " critical-chain [UNIT...] Print a tree of the time critical chain\n"
2330 " of units\n"
2331 " plot Output SVG graphic showing service\n"
2332 " initialization\n"
2333 " dot [UNIT...] Output dependency graph in %s format\n"
2334 " dump Output state serialization of service\n"
2335 " manager\n"
2336 " cat-config Show configuration file and drop-ins\n"
2337 " unit-files List files and symlinks for units\n"
2338 " unit-paths List load directories for units\n"
2339 " exit-status [STATUS...] List exit status definitions\n"
2340 " capability [CAP...] List capability definitions\n"
2341 " syscall-filter [NAME...] Print list of syscalls in seccomp\n"
2342 " filter\n"
2343 " filesystems [NAME...] Print list of filesystems\n"
2344 " condition CONDITION... Evaluate conditions and asserts\n"
2345 " verify FILE... Check unit files for correctness\n"
2346 " calendar SPEC... Validate repetitive calendar time\n"
2347 " events\n"
2348 " timestamp TIMESTAMP... Validate a timestamp\n"
2349 " timespan SPAN... Validate a time span\n"
2350 " security [UNIT...] Analyze security of unit\n"
2351 "\nOptions:\n"
2352 " -h --help Show this help\n"
2353 " --recursive-errors=MODE Control which units are verified\n"
2354 " --offline=BOOL Perform a security review on unit file(s)\n"
2355 " --threshold=N Exit with a non-zero status when overall\n"
2356 " exposure level is over threshold value\n"
2357 " --version Show package version\n"
2358 " --security-policy=PATH Use custom JSON security policy instead\n"
2359 " of built-in one\n"
2360 " --json=pretty|short|off Generate JSON output of the security\n"
2361 " analysis table\n"
2362 " --no-pager Do not pipe output into a pager\n"
2363 " --system Operate on system systemd instance\n"
2364 " --user Operate on user systemd instance\n"
2365 " --global Operate on global user configuration\n"
2366 " -H --host=[USER@]HOST Operate on remote host\n"
2367 " -M --machine=CONTAINER Operate on local container\n"
2368 " --order Show only order in the graph\n"
2369 " --require Show only requirement in the graph\n"
2370 " --from-pattern=GLOB Show only origins in the graph\n"
2371 " --to-pattern=GLOB Show only destinations in the graph\n"
2372 " --fuzz=SECONDS Also print services which finished SECONDS\n"
2373 " earlier than the latest in the branch\n"
2374 " --man[=BOOL] Do [not] check for existence of man pages\n"
2375 " --generators[=BOOL] Do [not] run unit generators\n"
2376 " (requires privileges)\n"
2377 " --iterations=N Show the specified number of iterations\n"
2378 " --base-time=TIMESTAMP Calculate calendar times relative to\n"
2379 " specified time\n"
2380 "\nSee the %s for details.\n",
2381 program_invocation_short_name,
2382 ansi_highlight(),
2383 ansi_normal(),
2384 dot_link,
2385 link);
2386
2387 /* When updating this list, including descriptions, apply changes to
2388 * shell-completion/bash/systemd-analyze and shell-completion/zsh/_systemd-analyze too. */
2389
2390 return 0;
2391 }
2392
2393 static int parse_argv(int argc, char *argv[]) {
2394 enum {
2395 ARG_VERSION = 0x100,
2396 ARG_ORDER,
2397 ARG_REQUIRE,
2398 ARG_ROOT,
2399 ARG_IMAGE,
2400 ARG_SYSTEM,
2401 ARG_USER,
2402 ARG_GLOBAL,
2403 ARG_DOT_FROM_PATTERN,
2404 ARG_DOT_TO_PATTERN,
2405 ARG_FUZZ,
2406 ARG_NO_PAGER,
2407 ARG_MAN,
2408 ARG_GENERATORS,
2409 ARG_ITERATIONS,
2410 ARG_BASE_TIME,
2411 ARG_RECURSIVE_ERRORS,
2412 ARG_OFFLINE,
2413 ARG_THRESHOLD,
2414 ARG_SECURITY_POLICY,
2415 ARG_JSON,
2416 };
2417
2418 static const struct option options[] = {
2419 { "help", no_argument, NULL, 'h' },
2420 { "version", no_argument, NULL, ARG_VERSION },
2421 { "order", no_argument, NULL, ARG_ORDER },
2422 { "require", no_argument, NULL, ARG_REQUIRE },
2423 { "root", required_argument, NULL, ARG_ROOT },
2424 { "image", required_argument, NULL, ARG_IMAGE },
2425 { "recursive-errors", required_argument, NULL, ARG_RECURSIVE_ERRORS },
2426 { "offline", required_argument, NULL, ARG_OFFLINE },
2427 { "threshold", required_argument, NULL, ARG_THRESHOLD },
2428 { "security-policy", required_argument, NULL, ARG_SECURITY_POLICY },
2429 { "system", no_argument, NULL, ARG_SYSTEM },
2430 { "user", no_argument, NULL, ARG_USER },
2431 { "global", no_argument, NULL, ARG_GLOBAL },
2432 { "from-pattern", required_argument, NULL, ARG_DOT_FROM_PATTERN },
2433 { "to-pattern", required_argument, NULL, ARG_DOT_TO_PATTERN },
2434 { "fuzz", required_argument, NULL, ARG_FUZZ },
2435 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
2436 { "man", optional_argument, NULL, ARG_MAN },
2437 { "generators", optional_argument, NULL, ARG_GENERATORS },
2438 { "host", required_argument, NULL, 'H' },
2439 { "machine", required_argument, NULL, 'M' },
2440 { "iterations", required_argument, NULL, ARG_ITERATIONS },
2441 { "base-time", required_argument, NULL, ARG_BASE_TIME },
2442 { "unit", required_argument, NULL, 'U' },
2443 { "json", required_argument, NULL, ARG_JSON },
2444 {}
2445 };
2446
2447 int r, c;
2448
2449 assert(argc >= 0);
2450 assert(argv);
2451
2452 while ((c = getopt_long(argc, argv, "hH:M:U:", options, NULL)) >= 0)
2453 switch (c) {
2454
2455 case 'h':
2456 return help(0, NULL, NULL);
2457
2458 case ARG_RECURSIVE_ERRORS:
2459 if (streq(optarg, "help")) {
2460 DUMP_STRING_TABLE(recursive_errors, RecursiveErrors, _RECURSIVE_ERRORS_MAX);
2461 return 0;
2462 }
2463 r = recursive_errors_from_string(optarg);
2464 if (r < 0)
2465 return log_error_errno(r, "Unknown mode passed to --recursive-errors='%s'.", optarg);
2466
2467 arg_recursive_errors = r;
2468 break;
2469
2470 case ARG_VERSION:
2471 return version();
2472
2473 case ARG_ROOT:
2474 r = parse_path_argument(optarg, /* suppress_root= */ true, &arg_root);
2475 if (r < 0)
2476 return r;
2477 break;
2478
2479 case ARG_IMAGE:
2480 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
2481 if (r < 0)
2482 return r;
2483 break;
2484
2485 case ARG_SYSTEM:
2486 arg_scope = UNIT_FILE_SYSTEM;
2487 break;
2488
2489 case ARG_USER:
2490 arg_scope = UNIT_FILE_USER;
2491 break;
2492
2493 case ARG_GLOBAL:
2494 arg_scope = UNIT_FILE_GLOBAL;
2495 break;
2496
2497 case ARG_ORDER:
2498 arg_dot = DEP_ORDER;
2499 break;
2500
2501 case ARG_REQUIRE:
2502 arg_dot = DEP_REQUIRE;
2503 break;
2504
2505 case ARG_DOT_FROM_PATTERN:
2506 if (strv_extend(&arg_dot_from_patterns, optarg) < 0)
2507 return log_oom();
2508
2509 break;
2510
2511 case ARG_DOT_TO_PATTERN:
2512 if (strv_extend(&arg_dot_to_patterns, optarg) < 0)
2513 return log_oom();
2514
2515 break;
2516
2517 case ARG_FUZZ:
2518 r = parse_sec(optarg, &arg_fuzz);
2519 if (r < 0)
2520 return r;
2521 break;
2522
2523 case ARG_NO_PAGER:
2524 arg_pager_flags |= PAGER_DISABLE;
2525 break;
2526
2527 case 'H':
2528 arg_transport = BUS_TRANSPORT_REMOTE;
2529 arg_host = optarg;
2530 break;
2531
2532 case 'M':
2533 arg_transport = BUS_TRANSPORT_MACHINE;
2534 arg_host = optarg;
2535 break;
2536
2537 case ARG_MAN:
2538 r = parse_boolean_argument("--man", optarg, &arg_man);
2539 if (r < 0)
2540 return r;
2541 break;
2542
2543 case ARG_GENERATORS:
2544 r = parse_boolean_argument("--generators", optarg, &arg_generators);
2545 if (r < 0)
2546 return r;
2547 break;
2548
2549 case ARG_OFFLINE:
2550 r = parse_boolean_argument("--offline", optarg, &arg_offline);
2551 if (r < 0)
2552 return r;
2553 break;
2554
2555 case ARG_THRESHOLD:
2556 r = safe_atou(optarg, &arg_threshold);
2557 if (r < 0 || arg_threshold > 100)
2558 return log_error_errno(r < 0 ? r : SYNTHETIC_ERRNO(EINVAL), "Failed to parse threshold: %s", optarg);
2559
2560 break;
2561
2562 case ARG_SECURITY_POLICY:
2563 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_security_policy);
2564 if (r < 0)
2565 return r;
2566 break;
2567
2568 case ARG_JSON:
2569 r = parse_json_argument(optarg, &arg_json_format_flags);
2570 if (r <= 0)
2571 return r;
2572 break;
2573
2574 case ARG_ITERATIONS:
2575 r = safe_atou(optarg, &arg_iterations);
2576 if (r < 0)
2577 return log_error_errno(r, "Failed to parse iterations: %s", optarg);
2578
2579 break;
2580
2581 case ARG_BASE_TIME:
2582 r = parse_timestamp(optarg, &arg_base_time);
2583 if (r < 0)
2584 return log_error_errno(r, "Failed to parse --base-time= parameter: %s", optarg);
2585
2586 break;
2587
2588 case 'U': {
2589 _cleanup_free_ char *mangled = NULL;
2590
2591 r = unit_name_mangle(optarg, UNIT_NAME_MANGLE_WARN, &mangled);
2592 if (r < 0)
2593 return log_error_errno(r, "Failed to mangle unit name %s: %m", optarg);
2594
2595 free_and_replace(arg_unit, mangled);
2596 break;
2597 }
2598 case '?':
2599 return -EINVAL;
2600
2601 default:
2602 assert_not_reached();
2603 }
2604
2605 if (arg_offline && !streq_ptr(argv[optind], "security"))
2606 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2607 "Option --offline= is only supported for security right now.");
2608
2609 if (arg_json_format_flags != JSON_FORMAT_OFF && !streq_ptr(argv[optind], "security"))
2610 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2611 "Option --json= is only supported for security right now.");
2612
2613 if (arg_threshold != 100 && !streq_ptr(argv[optind], "security"))
2614 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2615 "Option --threshold= is only supported for security right now.");
2616
2617 if (arg_scope == UNIT_FILE_GLOBAL &&
2618 !STR_IN_SET(argv[optind] ?: "time", "dot", "unit-paths", "verify"))
2619 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2620 "Option --global only makes sense with verbs dot, unit-paths, verify.");
2621
2622 if (streq_ptr(argv[optind], "cat-config") && arg_scope == UNIT_FILE_USER)
2623 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2624 "Option --user is not supported for cat-config right now.");
2625
2626 if (arg_security_policy && !streq_ptr(argv[optind], "security"))
2627 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2628 "Option --security-policy= is only supported for security.");
2629
2630 if ((arg_root || arg_image) && (!STRPTR_IN_SET(argv[optind], "cat-config", "verify", "condition")) &&
2631 (!(streq_ptr(argv[optind], "security") && arg_offline)))
2632 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2633 "Options --root= and --image= are only supported for cat-config, verify, condition and security when used with --offline= right now.");
2634
2635 /* Having both an image and a root is not supported by the code */
2636 if (arg_root && arg_image)
2637 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Please specify either --root= or --image=, the combination of both is not supported.");
2638
2639 if (arg_unit && !streq_ptr(argv[optind], "condition"))
2640 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Option --unit= is only supported for condition");
2641
2642 if (streq_ptr(argv[optind], "condition") && !arg_unit && optind >= argc - 1)
2643 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Too few arguments for condition");
2644
2645 if (streq_ptr(argv[optind], "condition") && arg_unit && optind < argc - 1)
2646 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No conditions can be passed if --unit= is used.");
2647
2648 return 1; /* work to do */
2649 }
2650
2651 static int run(int argc, char *argv[]) {
2652 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
2653 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
2654 _cleanup_(umount_and_rmdir_and_freep) char *unlink_dir = NULL;
2655
2656 static const Verb verbs[] = {
2657 { "help", VERB_ANY, VERB_ANY, 0, help },
2658 { "time", VERB_ANY, 1, VERB_DEFAULT, analyze_time },
2659 { "blame", VERB_ANY, 1, 0, analyze_blame },
2660 { "critical-chain", VERB_ANY, VERB_ANY, 0, analyze_critical_chain },
2661 { "plot", VERB_ANY, 1, 0, analyze_plot },
2662 { "dot", VERB_ANY, VERB_ANY, 0, dot },
2663 /* The following seven verbs are deprecated */
2664 { "log-level", VERB_ANY, 2, 0, verb_log_control },
2665 { "log-target", VERB_ANY, 2, 0, verb_log_control },
2666 { "set-log-level", 2, 2, 0, verb_log_control },
2667 { "get-log-level", VERB_ANY, 1, 0, verb_log_control },
2668 { "set-log-target", 2, 2, 0, verb_log_control },
2669 { "get-log-target", VERB_ANY, 1, 0, verb_log_control },
2670 { "service-watchdogs", VERB_ANY, 2, 0, service_watchdogs },
2671 { "dump", VERB_ANY, 1, 0, dump },
2672 { "cat-config", 2, VERB_ANY, 0, cat_config },
2673 { "unit-files", VERB_ANY, VERB_ANY, 0, do_unit_files },
2674 { "unit-paths", 1, 1, 0, dump_unit_paths },
2675 { "exit-status", VERB_ANY, VERB_ANY, 0, dump_exit_status },
2676 { "syscall-filter", VERB_ANY, VERB_ANY, 0, dump_syscall_filters },
2677 { "capability", VERB_ANY, VERB_ANY, 0, dump_capabilities },
2678 { "filesystems", VERB_ANY, VERB_ANY, 0, dump_filesystems },
2679 { "condition", VERB_ANY, VERB_ANY, 0, do_condition },
2680 { "verify", 2, VERB_ANY, 0, do_verify },
2681 { "calendar", 2, VERB_ANY, 0, test_calendar },
2682 { "timestamp", 2, VERB_ANY, 0, test_timestamp },
2683 { "timespan", 2, VERB_ANY, 0, dump_timespan },
2684 { "security", VERB_ANY, VERB_ANY, 0, do_security },
2685 {}
2686 };
2687
2688 int r;
2689
2690 setlocale(LC_ALL, "");
2691 setlocale(LC_NUMERIC, "C"); /* we want to format/parse floats in C style */
2692
2693 log_setup();
2694
2695 r = parse_argv(argc, argv);
2696 if (r <= 0)
2697 return r;
2698
2699 /* Open up and mount the image */
2700 if (arg_image) {
2701 assert(!arg_root);
2702
2703 r = mount_image_privately_interactively(
2704 arg_image,
2705 DISSECT_IMAGE_GENERIC_ROOT |
2706 DISSECT_IMAGE_RELAX_VAR_CHECK |
2707 DISSECT_IMAGE_READ_ONLY,
2708 &unlink_dir,
2709 &loop_device,
2710 &decrypted_image);
2711 if (r < 0)
2712 return r;
2713
2714 arg_root = strdup(unlink_dir);
2715 if (!arg_root)
2716 return log_oom();
2717 }
2718
2719 return dispatch_verb(argc, argv, verbs, NULL);
2720 }
2721
2722 DEFINE_MAIN_FUNCTION(run);