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