]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/coredump/coredumpctl.c
Merge pull request #9504 from poettering/nss-deadlock
[thirdparty/systemd.git] / src / coredump / coredumpctl.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <fcntl.h>
4 #include <getopt.h>
5 #include <locale.h>
6 #include <stdio.h>
7 #include <string.h>
8 #include <unistd.h>
9
10 #include "sd-bus.h"
11 #include "sd-journal.h"
12 #include "sd-messages.h"
13
14 #include "alloc-util.h"
15 #include "bus-error.h"
16 #include "bus-util.h"
17 #include "compress.h"
18 #include "fd-util.h"
19 #include "fileio.h"
20 #include "fs-util.h"
21 #include "journal-internal.h"
22 #include "journal-util.h"
23 #include "log.h"
24 #include "macro.h"
25 #include "pager.h"
26 #include "parse-util.h"
27 #include "path-util.h"
28 #include "process-util.h"
29 #include "sigbus.h"
30 #include "signal-util.h"
31 #include "string-util.h"
32 #include "strv.h"
33 #include "terminal-util.h"
34 #include "user-util.h"
35 #include "util.h"
36 #include "verbs.h"
37
38 #define SHORT_BUS_CALL_TIMEOUT_USEC (3 * USEC_PER_SEC)
39
40 static usec_t arg_since = USEC_INFINITY, arg_until = USEC_INFINITY;
41 static const char* arg_field = NULL;
42 static const char *arg_debugger = NULL;
43 static const char *arg_directory = NULL;
44 static bool arg_no_pager = false;
45 static int arg_no_legend = false;
46 static int arg_one = false;
47 static FILE* arg_output = NULL;
48 static bool arg_reverse = false;
49 static bool arg_quiet = false;
50
51 static int add_match(sd_journal *j, const char *match) {
52 _cleanup_free_ char *p = NULL;
53 const char* prefix, *pattern;
54 pid_t pid;
55 int r;
56
57 if (strchr(match, '='))
58 prefix = "";
59 else if (strchr(match, '/')) {
60 r = path_make_absolute_cwd(match, &p);
61 if (r < 0)
62 return log_error_errno(r, "path_make_absolute_cwd(\"%s\"): %m", match);
63
64 match = p;
65 prefix = "COREDUMP_EXE=";
66 } else if (parse_pid(match, &pid) >= 0)
67 prefix = "COREDUMP_PID=";
68 else
69 prefix = "COREDUMP_COMM=";
70
71 pattern = strjoina(prefix, match);
72 log_debug("Adding match: %s", pattern);
73 r = sd_journal_add_match(j, pattern, 0);
74 if (r < 0)
75 return log_error_errno(r, "Failed to add match \"%s\": %m", match);
76
77 return 0;
78 }
79
80 static int add_matches(sd_journal *j, char **matches) {
81 char **match;
82 int r;
83
84 r = sd_journal_add_match(j, "MESSAGE_ID=" SD_MESSAGE_COREDUMP_STR, 0);
85 if (r < 0)
86 return log_error_errno(r, "Failed to add match \"%s\": %m", "MESSAGE_ID=" SD_MESSAGE_COREDUMP_STR);
87
88 r = sd_journal_add_match(j, "MESSAGE_ID=" SD_MESSAGE_BACKTRACE_STR, 0);
89 if (r < 0)
90 return log_error_errno(r, "Failed to add match \"%s\": %m", "MESSAGE_ID=" SD_MESSAGE_BACKTRACE_STR);
91
92 STRV_FOREACH(match, matches) {
93 r = add_match(j, *match);
94 if (r < 0)
95 return r;
96 }
97
98 return 0;
99 }
100
101 static int acquire_journal(sd_journal **ret, char **matches) {
102 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
103 int r;
104
105 assert(ret);
106
107 if (arg_directory) {
108 r = sd_journal_open_directory(&j, arg_directory, 0);
109 if (r < 0)
110 return log_error_errno(r, "Failed to open journals in directory: %s: %m", arg_directory);
111 } else {
112 r = sd_journal_open(&j, SD_JOURNAL_LOCAL_ONLY);
113 if (r < 0)
114 return log_error_errno(r, "Failed to open journal: %m");
115 }
116
117 r = journal_access_check_and_warn(j, arg_quiet, true);
118 if (r < 0)
119 return r;
120
121 r = add_matches(j, matches);
122 if (r < 0)
123 return r;
124
125 if (DEBUG_LOGGING) {
126 _cleanup_free_ char *filter;
127
128 filter = journal_make_match_string(j);
129 log_debug("Journal filter: %s", filter);
130 }
131
132 *ret = TAKE_PTR(j);
133
134 return 0;
135 }
136
137 static int help(void) {
138 printf("%s [OPTIONS...]\n\n"
139 "List or retrieve coredumps from the journal.\n\n"
140 "Flags:\n"
141 " -h --help Show this help\n"
142 " --version Print version string\n"
143 " --no-pager Do not pipe output into a pager\n"
144 " --no-legend Do not print the column headers\n"
145 " --debugger=DEBUGGER Use the given debugger\n"
146 " -1 Show information about most recent entry only\n"
147 " -S --since=DATE Only print coredumps since the date\n"
148 " -U --until=DATE Only print coredumps until the date\n"
149 " -r --reverse Show the newest entries first\n"
150 " -F --field=FIELD List all values a certain field takes\n"
151 " -o --output=FILE Write output to FILE\n"
152 " -D --directory=DIR Use journal files from directory\n\n"
153 " -q --quiet Do not show info messages and privilege warning\n"
154 "Commands:\n"
155 " list [MATCHES...] List available coredumps (default)\n"
156 " info [MATCHES...] Show detailed information about one or more coredumps\n"
157 " dump [MATCHES...] Print first matching coredump to stdout\n"
158 " debug [MATCHES...] Start a debugger for the first matching coredump\n"
159 , program_invocation_short_name);
160
161 return 0;
162 }
163
164 static int parse_argv(int argc, char *argv[]) {
165 enum {
166 ARG_VERSION = 0x100,
167 ARG_NO_PAGER,
168 ARG_NO_LEGEND,
169 ARG_DEBUGGER,
170 };
171
172 int c, r;
173
174 static const struct option options[] = {
175 { "help", no_argument, NULL, 'h' },
176 { "version" , no_argument, NULL, ARG_VERSION },
177 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
178 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
179 { "debugger", required_argument, NULL, ARG_DEBUGGER },
180 { "output", required_argument, NULL, 'o' },
181 { "field", required_argument, NULL, 'F' },
182 { "directory", required_argument, NULL, 'D' },
183 { "reverse", no_argument, NULL, 'r' },
184 { "since", required_argument, NULL, 'S' },
185 { "until", required_argument, NULL, 'U' },
186 { "quiet", no_argument, NULL, 'q' },
187 {}
188 };
189
190 assert(argc >= 0);
191 assert(argv);
192
193 while ((c = getopt_long(argc, argv, "ho:F:1D:rS:U:q", options, NULL)) >= 0)
194 switch(c) {
195 case 'h':
196 return help();
197
198 case ARG_VERSION:
199 return version();
200
201 case ARG_NO_PAGER:
202 arg_no_pager = true;
203 break;
204
205 case ARG_NO_LEGEND:
206 arg_no_legend = true;
207 break;
208
209 case ARG_DEBUGGER:
210 arg_debugger = optarg;
211 break;
212
213 case 'o':
214 if (arg_output) {
215 log_error("Cannot set output more than once.");
216 return -EINVAL;
217 }
218
219 arg_output = fopen(optarg, "we");
220 if (!arg_output)
221 return log_error_errno(errno, "writing to '%s': %m", optarg);
222
223 break;
224
225 case 'S':
226 r = parse_timestamp(optarg, &arg_since);
227 if (r < 0)
228 return log_error_errno(r, "Failed to parse timestamp: %s", optarg);
229 break;
230
231 case 'U':
232 r = parse_timestamp(optarg, &arg_until);
233 if (r < 0)
234 return log_error_errno(r, "Failed to parse timestamp: %s", optarg);
235 break;
236
237 case 'F':
238 if (arg_field) {
239 log_error("Cannot use --field/-F more than once.");
240 return -EINVAL;
241 }
242 arg_field = optarg;
243 break;
244
245 case '1':
246 arg_one = true;
247 break;
248
249 case 'D':
250 arg_directory = optarg;
251 break;
252
253 case 'r':
254 arg_reverse = true;
255 break;
256
257 case 'q':
258 arg_quiet = true;
259 break;
260
261 case '?':
262 return -EINVAL;
263
264 default:
265 assert_not_reached("Unhandled option");
266 }
267
268 if (arg_since != USEC_INFINITY && arg_until != USEC_INFINITY &&
269 arg_since > arg_until) {
270 log_error("--since= must be before --until=.");
271 return -EINVAL;
272 }
273
274 return 1;
275 }
276
277 static int retrieve(const void *data,
278 size_t len,
279 const char *name,
280 char **var) {
281
282 size_t ident;
283 char *v;
284
285 ident = strlen(name) + 1; /* name + "=" */
286
287 if (len < ident)
288 return 0;
289
290 if (memcmp(data, name, ident - 1) != 0)
291 return 0;
292
293 if (((const char*) data)[ident - 1] != '=')
294 return 0;
295
296 v = strndup((const char*)data + ident, len - ident);
297 if (!v)
298 return log_oom();
299
300 free(*var);
301 *var = v;
302
303 return 1;
304 }
305
306 static int print_field(FILE* file, sd_journal *j) {
307 const void *d;
308 size_t l;
309
310 assert(file);
311 assert(j);
312
313 assert(arg_field);
314
315 /* A (user-specified) field may appear more than once for a given entry.
316 * We will print all of the occurences.
317 * This is different below for fields that systemd-coredump uses,
318 * because they cannot meaningfully appear more than once.
319 */
320 SD_JOURNAL_FOREACH_DATA(j, d, l) {
321 _cleanup_free_ char *value = NULL;
322 int r;
323
324 r = retrieve(d, l, arg_field, &value);
325 if (r < 0)
326 return r;
327 if (r > 0)
328 fprintf(file, "%s\n", value);
329 }
330
331 return 0;
332 }
333
334 #define RETRIEVE(d, l, name, arg) \
335 { \
336 int _r = retrieve(d, l, name, &arg); \
337 if (_r < 0) \
338 return _r; \
339 if (_r > 0) \
340 continue; \
341 }
342
343 static int print_list(FILE* file, sd_journal *j, int had_legend) {
344 _cleanup_free_ char
345 *mid = NULL, *pid = NULL, *uid = NULL, *gid = NULL,
346 *sgnl = NULL, *exe = NULL, *comm = NULL, *cmdline = NULL,
347 *filename = NULL, *truncated = NULL, *coredump = NULL;
348 const void *d;
349 size_t l;
350 usec_t t;
351 char buf[FORMAT_TIMESTAMP_MAX];
352 int r;
353 const char *present;
354 bool normal_coredump;
355
356 assert(file);
357 assert(j);
358
359 SD_JOURNAL_FOREACH_DATA(j, d, l) {
360 RETRIEVE(d, l, "MESSAGE_ID", mid);
361 RETRIEVE(d, l, "COREDUMP_PID", pid);
362 RETRIEVE(d, l, "COREDUMP_UID", uid);
363 RETRIEVE(d, l, "COREDUMP_GID", gid);
364 RETRIEVE(d, l, "COREDUMP_SIGNAL", sgnl);
365 RETRIEVE(d, l, "COREDUMP_EXE", exe);
366 RETRIEVE(d, l, "COREDUMP_COMM", comm);
367 RETRIEVE(d, l, "COREDUMP_CMDLINE", cmdline);
368 RETRIEVE(d, l, "COREDUMP_FILENAME", filename);
369 RETRIEVE(d, l, "COREDUMP_TRUNCATED", truncated);
370 RETRIEVE(d, l, "COREDUMP", coredump);
371 }
372
373 if (!pid && !uid && !gid && !sgnl && !exe && !comm && !cmdline && !filename) {
374 log_warning("Empty coredump log entry");
375 return -EINVAL;
376 }
377
378 r = sd_journal_get_realtime_usec(j, &t);
379 if (r < 0)
380 return log_error_errno(r, "Failed to get realtime timestamp: %m");
381
382 format_timestamp(buf, sizeof(buf), t);
383
384 if (!had_legend && !arg_no_legend)
385 fprintf(file, "%-*s %*s %*s %*s %*s %-*s %s\n",
386 FORMAT_TIMESTAMP_WIDTH, "TIME",
387 6, "PID",
388 5, "UID",
389 5, "GID",
390 3, "SIG",
391 9, "COREFILE",
392 "EXE");
393
394 normal_coredump = streq_ptr(mid, SD_MESSAGE_COREDUMP_STR);
395
396 if (filename)
397 if (access(filename, R_OK) == 0)
398 present = "present";
399 else if (errno == ENOENT)
400 present = "missing";
401 else
402 present = "error";
403 else if (coredump)
404 present = "journal";
405 else if (normal_coredump)
406 present = "none";
407 else
408 present = "-";
409
410 if (STR_IN_SET(present, "present", "journal") && truncated && parse_boolean(truncated) > 0)
411 present = "truncated";
412
413 fprintf(file, "%-*s %*s %*s %*s %*s %-*s %s\n",
414 FORMAT_TIMESTAMP_WIDTH, buf,
415 6, strna(pid),
416 5, strna(uid),
417 5, strna(gid),
418 3, normal_coredump ? strna(sgnl) : "-",
419 9, present,
420 strna(exe ?: (comm ?: cmdline)));
421
422 return 0;
423 }
424
425 static int print_info(FILE *file, sd_journal *j, bool need_space) {
426 _cleanup_free_ char
427 *mid = NULL, *pid = NULL, *uid = NULL, *gid = NULL,
428 *sgnl = NULL, *exe = NULL, *comm = NULL, *cmdline = NULL,
429 *unit = NULL, *user_unit = NULL, *session = NULL,
430 *boot_id = NULL, *machine_id = NULL, *hostname = NULL,
431 *slice = NULL, *cgroup = NULL, *owner_uid = NULL,
432 *message = NULL, *timestamp = NULL, *filename = NULL,
433 *truncated = NULL, *coredump = NULL;
434 const void *d;
435 size_t l;
436 bool normal_coredump;
437 int r;
438
439 assert(file);
440 assert(j);
441
442 SD_JOURNAL_FOREACH_DATA(j, d, l) {
443 RETRIEVE(d, l, "MESSAGE_ID", mid);
444 RETRIEVE(d, l, "COREDUMP_PID", pid);
445 RETRIEVE(d, l, "COREDUMP_UID", uid);
446 RETRIEVE(d, l, "COREDUMP_GID", gid);
447 RETRIEVE(d, l, "COREDUMP_SIGNAL", sgnl);
448 RETRIEVE(d, l, "COREDUMP_EXE", exe);
449 RETRIEVE(d, l, "COREDUMP_COMM", comm);
450 RETRIEVE(d, l, "COREDUMP_CMDLINE", cmdline);
451 RETRIEVE(d, l, "COREDUMP_UNIT", unit);
452 RETRIEVE(d, l, "COREDUMP_USER_UNIT", user_unit);
453 RETRIEVE(d, l, "COREDUMP_SESSION", session);
454 RETRIEVE(d, l, "COREDUMP_OWNER_UID", owner_uid);
455 RETRIEVE(d, l, "COREDUMP_SLICE", slice);
456 RETRIEVE(d, l, "COREDUMP_CGROUP", cgroup);
457 RETRIEVE(d, l, "COREDUMP_TIMESTAMP", timestamp);
458 RETRIEVE(d, l, "COREDUMP_FILENAME", filename);
459 RETRIEVE(d, l, "COREDUMP_TRUNCATED", truncated);
460 RETRIEVE(d, l, "COREDUMP", coredump);
461 RETRIEVE(d, l, "_BOOT_ID", boot_id);
462 RETRIEVE(d, l, "_MACHINE_ID", machine_id);
463 RETRIEVE(d, l, "_HOSTNAME", hostname);
464 RETRIEVE(d, l, "MESSAGE", message);
465 }
466
467 if (need_space)
468 fputs("\n", file);
469
470 normal_coredump = streq_ptr(mid, SD_MESSAGE_COREDUMP_STR);
471
472 if (comm)
473 fprintf(file,
474 " PID: %s%s%s (%s)\n",
475 ansi_highlight(), strna(pid), ansi_normal(), comm);
476 else
477 fprintf(file,
478 " PID: %s%s%s\n",
479 ansi_highlight(), strna(pid), ansi_normal());
480
481 if (uid) {
482 uid_t n;
483
484 if (parse_uid(uid, &n) >= 0) {
485 _cleanup_free_ char *u = NULL;
486
487 u = uid_to_name(n);
488 fprintf(file,
489 " UID: %s (%s)\n",
490 uid, u);
491 } else {
492 fprintf(file,
493 " UID: %s\n",
494 uid);
495 }
496 }
497
498 if (gid) {
499 gid_t n;
500
501 if (parse_gid(gid, &n) >= 0) {
502 _cleanup_free_ char *g = NULL;
503
504 g = gid_to_name(n);
505 fprintf(file,
506 " GID: %s (%s)\n",
507 gid, g);
508 } else {
509 fprintf(file,
510 " GID: %s\n",
511 gid);
512 }
513 }
514
515 if (sgnl) {
516 int sig;
517 const char *name = normal_coredump ? "Signal" : "Reason";
518
519 if (normal_coredump && safe_atoi(sgnl, &sig) >= 0)
520 fprintf(file, " %s: %s (%s)\n", name, sgnl, signal_to_string(sig));
521 else
522 fprintf(file, " %s: %s\n", name, sgnl);
523 }
524
525 if (timestamp) {
526 usec_t u;
527
528 r = safe_atou64(timestamp, &u);
529 if (r >= 0) {
530 char absolute[FORMAT_TIMESTAMP_MAX], relative[FORMAT_TIMESPAN_MAX];
531
532 fprintf(file,
533 " Timestamp: %s (%s)\n",
534 format_timestamp(absolute, sizeof(absolute), u),
535 format_timestamp_relative(relative, sizeof(relative), u));
536
537 } else
538 fprintf(file, " Timestamp: %s\n", timestamp);
539 }
540
541 if (cmdline)
542 fprintf(file, " Command Line: %s\n", cmdline);
543 if (exe)
544 fprintf(file, " Executable: %s%s%s\n", ansi_highlight(), exe, ansi_normal());
545 if (cgroup)
546 fprintf(file, " Control Group: %s\n", cgroup);
547 if (unit)
548 fprintf(file, " Unit: %s\n", unit);
549 if (user_unit)
550 fprintf(file, " User Unit: %s\n", user_unit);
551 if (slice)
552 fprintf(file, " Slice: %s\n", slice);
553 if (session)
554 fprintf(file, " Session: %s\n", session);
555 if (owner_uid) {
556 uid_t n;
557
558 if (parse_uid(owner_uid, &n) >= 0) {
559 _cleanup_free_ char *u = NULL;
560
561 u = uid_to_name(n);
562 fprintf(file,
563 " Owner UID: %s (%s)\n",
564 owner_uid, u);
565 } else {
566 fprintf(file,
567 " Owner UID: %s\n",
568 owner_uid);
569 }
570 }
571 if (boot_id)
572 fprintf(file, " Boot ID: %s\n", boot_id);
573 if (machine_id)
574 fprintf(file, " Machine ID: %s\n", machine_id);
575 if (hostname)
576 fprintf(file, " Hostname: %s\n", hostname);
577
578 if (filename) {
579 bool inacc, trunc;
580
581 inacc = access(filename, R_OK) < 0;
582 trunc = truncated && parse_boolean(truncated) > 0;
583
584 if (inacc || trunc)
585 fprintf(file, " Storage: %s%s (%s%s%s)%s\n",
586 ansi_highlight_red(),
587 filename,
588 inacc ? "inaccessible" : "",
589 inacc && trunc ? ", " : "",
590 trunc ? "truncated" : "",
591 ansi_normal());
592 else
593 fprintf(file, " Storage: %s\n", filename);
594 }
595
596 else if (coredump)
597 fprintf(file, " Storage: journal\n");
598 else
599 fprintf(file, " Storage: none\n");
600
601 if (message) {
602 _cleanup_free_ char *m = NULL;
603
604 m = strreplace(message, "\n", "\n ");
605
606 fprintf(file, " Message: %s\n", strstrip(m ?: message));
607 }
608
609 return 0;
610 }
611
612 static int focus(sd_journal *j) {
613 int r;
614
615 r = sd_journal_seek_tail(j);
616 if (r == 0)
617 r = sd_journal_previous(j);
618 if (r < 0)
619 return log_error_errno(r, "Failed to search journal: %m");
620 if (r == 0) {
621 log_error("No match found.");
622 return -ESRCH;
623 }
624 return r;
625 }
626
627 static int print_entry(sd_journal *j, unsigned n_found, bool verb_is_info) {
628 assert(j);
629
630 if (verb_is_info)
631 return print_info(stdout, j, n_found);
632 else if (arg_field)
633 return print_field(stdout, j);
634 else
635 return print_list(stdout, j, n_found);
636 }
637
638 static int dump_list(int argc, char **argv, void *userdata) {
639 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
640 unsigned n_found = 0;
641 bool verb_is_info;
642 int r;
643
644 verb_is_info = (argc >= 1 && streq(argv[0], "info"));
645
646 r = acquire_journal(&j, argv + 1);
647 if (r < 0)
648 return r;
649
650 (void) pager_open(arg_no_pager, false);
651
652 /* The coredumps are likely to compressed, and for just
653 * listing them we don't need to decompress them, so let's
654 * pick a fairly low data threshold here */
655 sd_journal_set_data_threshold(j, 4096);
656
657 /* "info" without pattern implies "-1" */
658 if (arg_one || (verb_is_info && argc == 1)) {
659 r = focus(j);
660 if (r < 0)
661 return r;
662
663 return print_entry(j, 0, verb_is_info);
664 } else {
665 if (arg_since != USEC_INFINITY && !arg_reverse)
666 r = sd_journal_seek_realtime_usec(j, arg_since);
667 else if (arg_until != USEC_INFINITY && arg_reverse)
668 r = sd_journal_seek_realtime_usec(j, arg_until);
669 else if (arg_reverse)
670 r = sd_journal_seek_tail(j);
671 else
672 r = sd_journal_seek_head(j);
673 if (r < 0)
674 return log_error_errno(r, "Failed to seek to date: %m");
675
676 for (;;) {
677 if (!arg_reverse)
678 r = sd_journal_next(j);
679 else
680 r = sd_journal_previous(j);
681
682 if (r < 0)
683 return log_error_errno(r, "Failed to iterate through journal: %m");
684
685 if (r == 0)
686 break;
687
688 if (arg_until != USEC_INFINITY && !arg_reverse) {
689 usec_t usec;
690
691 r = sd_journal_get_realtime_usec(j, &usec);
692 if (r < 0)
693 return log_error_errno(r, "Failed to determine timestamp: %m");
694 if (usec > arg_until)
695 continue;
696 }
697
698 if (arg_since != USEC_INFINITY && arg_reverse) {
699 usec_t usec;
700
701 r = sd_journal_get_realtime_usec(j, &usec);
702 if (r < 0)
703 return log_error_errno(r, "Failed to determine timestamp: %m");
704 if (usec < arg_since)
705 continue;
706 }
707
708 r = print_entry(j, n_found++, verb_is_info);
709 if (r < 0)
710 return r;
711 }
712
713 if (!arg_field && n_found <= 0) {
714 if (!arg_quiet)
715 log_notice("No coredumps found.");
716 return -ESRCH;
717 }
718 }
719
720 return 0;
721 }
722
723 static int save_core(sd_journal *j, FILE *file, char **path, bool *unlink_temp) {
724 const char *data;
725 _cleanup_free_ char *filename = NULL;
726 size_t len;
727 int r, fd;
728 _cleanup_close_ int fdt = -1;
729 char *temp = NULL;
730
731 assert(!(file && path)); /* At most one can be specified */
732 assert(!!path == !!unlink_temp); /* Those must be specified together */
733
734 /* Look for a coredump on disk first. */
735 r = sd_journal_get_data(j, "COREDUMP_FILENAME", (const void**) &data, &len);
736 if (r == 0)
737 retrieve(data, len, "COREDUMP_FILENAME", &filename);
738 else {
739 if (r != -ENOENT)
740 return log_error_errno(r, "Failed to retrieve COREDUMP_FILENAME field: %m");
741 /* Check that we can have a COREDUMP field. We still haven't set a high
742 * data threshold, so we'll get a few kilobytes at most.
743 */
744
745 r = sd_journal_get_data(j, "COREDUMP", (const void**) &data, &len);
746 if (r == -ENOENT)
747 return log_error_errno(r, "Coredump entry has no core attached (neither internally in the journal nor externally on disk).");
748 if (r < 0)
749 return log_error_errno(r, "Failed to retrieve COREDUMP field: %m");
750 }
751
752 if (filename) {
753 if (access(filename, R_OK) < 0)
754 return log_error_errno(errno, "File \"%s\" is not readable: %m", filename);
755
756 if (path && !endswith(filename, ".xz") && !endswith(filename, ".lz4")) {
757 *path = TAKE_PTR(filename);
758
759 return 0;
760 }
761 }
762
763 if (path) {
764 const char *vt;
765
766 /* Create a temporary file to write the uncompressed core to. */
767
768 r = var_tmp_dir(&vt);
769 if (r < 0)
770 return log_error_errno(r, "Failed to acquire temporary directory path: %m");
771
772 temp = strjoin(vt, "/coredump-XXXXXX");
773 if (!temp)
774 return log_oom();
775
776 fdt = mkostemp_safe(temp);
777 if (fdt < 0)
778 return log_error_errno(fdt, "Failed to create temporary file: %m");
779 log_debug("Created temporary file %s", temp);
780
781 fd = fdt;
782 } else {
783 /* If neither path or file are specified, we will write to stdout. Let's now check
784 * if stdout is connected to a tty. We checked that the file exists, or that the
785 * core might be stored in the journal. In this second case, if we found the entry,
786 * in all likelyhood we will be able to access the COREDUMP= field. In either case,
787 * we stop before doing any "real" work, i.e. before starting decompression or
788 * reading from the file or creating temporary files.
789 */
790 if (!file) {
791 if (on_tty())
792 return log_error_errno(ENOTTY, "Refusing to dump core to tty"
793 " (use shell redirection or specify --output).");
794 file = stdout;
795 }
796
797 fd = fileno(file);
798 }
799
800 if (filename) {
801 #if HAVE_XZ || HAVE_LZ4
802 _cleanup_close_ int fdf;
803
804 fdf = open(filename, O_RDONLY | O_CLOEXEC);
805 if (fdf < 0) {
806 r = log_error_errno(errno, "Failed to open %s: %m", filename);
807 goto error;
808 }
809
810 r = decompress_stream(filename, fdf, fd, -1);
811 if (r < 0) {
812 log_error_errno(r, "Failed to decompress %s: %m", filename);
813 goto error;
814 }
815 #else
816 log_error("Cannot decompress file. Compiled without compression support.");
817 r = -EOPNOTSUPP;
818 goto error;
819 #endif
820 } else {
821 ssize_t sz;
822
823 /* We want full data, nothing truncated. */
824 sd_journal_set_data_threshold(j, 0);
825
826 r = sd_journal_get_data(j, "COREDUMP", (const void**) &data, &len);
827 if (r < 0)
828 return log_error_errno(r, "Failed to retrieve COREDUMP field: %m");
829
830 assert(len >= 9);
831 data += 9;
832 len -= 9;
833
834 sz = write(fd, data, len);
835 if (sz < 0) {
836 r = log_error_errno(errno, "Failed to write output: %m");
837 goto error;
838 }
839 if (sz != (ssize_t) len) {
840 log_error("Short write to output.");
841 r = -EIO;
842 goto error;
843 }
844 }
845
846 if (temp) {
847 *path = temp;
848 *unlink_temp = true;
849 }
850 return 0;
851
852 error:
853 if (temp) {
854 unlink(temp);
855 log_debug("Removed temporary file %s", temp);
856 }
857 return r;
858 }
859
860 static int dump_core(int argc, char **argv, void *userdata) {
861 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
862 int r;
863
864 if (arg_field) {
865 log_error("Option --field/-F only makes sense with list");
866 return -EINVAL;
867 }
868
869 r = acquire_journal(&j, argv + 1);
870 if (r < 0)
871 return r;
872
873 r = focus(j);
874 if (r < 0)
875 return r;
876
877 print_info(arg_output ? stdout : stderr, j, false);
878
879 r = save_core(j, arg_output, NULL, NULL);
880 if (r < 0)
881 return r;
882
883 r = sd_journal_previous(j);
884 if (r > 0 && !arg_quiet)
885 log_notice("More than one entry matches, ignoring rest.");
886
887 return 0;
888 }
889
890 static int run_debug(int argc, char **argv, void *userdata) {
891 _cleanup_(sd_journal_closep) sd_journal *j = NULL;
892 _cleanup_free_ char *exe = NULL, *path = NULL;
893 bool unlink_path = false;
894 const char *data, *fork_name;
895 size_t len;
896 pid_t pid;
897 int r;
898
899 if (!arg_debugger) {
900 char *env_debugger;
901
902 env_debugger = getenv("SYSTEMD_DEBUGGER");
903 if (env_debugger)
904 arg_debugger = env_debugger;
905 else
906 arg_debugger = "gdb";
907 }
908
909 if (arg_field) {
910 log_error("Option --field/-F only makes sense with list");
911 return -EINVAL;
912 }
913
914 r = acquire_journal(&j, argv + 1);
915 if (r < 0)
916 return r;
917
918 r = focus(j);
919 if (r < 0)
920 return r;
921
922 print_info(stdout, j, false);
923 fputs("\n", stdout);
924
925 r = sd_journal_get_data(j, "COREDUMP_EXE", (const void**) &data, &len);
926 if (r < 0)
927 return log_error_errno(r, "Failed to retrieve COREDUMP_EXE field: %m");
928
929 assert(len > STRLEN("COREDUMP_EXE="));
930 data += STRLEN("COREDUMP_EXE=");
931 len -= STRLEN("COREDUMP_EXE=");
932
933 exe = strndup(data, len);
934 if (!exe)
935 return log_oom();
936
937 if (endswith(exe, " (deleted)")) {
938 log_error("Binary already deleted.");
939 return -ENOENT;
940 }
941
942 if (!path_is_absolute(exe)) {
943 log_error("Binary is not an absolute path.");
944 return -ENOENT;
945 }
946
947 r = save_core(j, NULL, &path, &unlink_path);
948 if (r < 0)
949 return r;
950
951 /* Don't interfere with gdb and its handling of SIGINT. */
952 (void) ignore_signals(SIGINT, -1);
953
954 fork_name = strjoina("(", arg_debugger, ")");
955
956 r = safe_fork(fork_name, FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_CLOSE_ALL_FDS|FORK_LOG, &pid);
957 if (r < 0)
958 goto finish;
959 if (r == 0) {
960 execlp(arg_debugger, arg_debugger, exe, "-c", path, NULL);
961 log_open();
962 log_error_errno(errno, "Failed to invoke %s: %m", arg_debugger);
963 _exit(EXIT_FAILURE);
964 }
965
966 r = wait_for_terminate_and_check(arg_debugger, pid, WAIT_LOG_ABNORMAL);
967
968 finish:
969 (void) default_signals(SIGINT, -1);
970
971 if (unlink_path) {
972 log_debug("Removed temporary file %s", path);
973 unlink(path);
974 }
975
976 return r;
977 }
978
979 static int check_units_active(void) {
980 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
981 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
982 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
983 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
984 int c = 0, r;
985 const char *id, *state, *substate;
986
987 if (arg_quiet)
988 return false;
989
990 r = sd_bus_default_system(&bus);
991 if (r < 0)
992 return log_error_errno(r, "Failed to acquire bus: %m");
993
994 r = sd_bus_message_new_method_call(
995 bus,
996 &m,
997 "org.freedesktop.systemd1",
998 "/org/freedesktop/systemd1",
999 "org.freedesktop.systemd1.Manager",
1000 "ListUnitsByPatterns");
1001 if (r < 0)
1002 return bus_log_create_error(r);
1003
1004 r = sd_bus_message_append_strv(m, NULL);
1005 if (r < 0)
1006 return bus_log_create_error(r);
1007
1008 r = sd_bus_message_append_strv(m, STRV_MAKE("systemd-coredump@*.service"));
1009 if (r < 0)
1010 return bus_log_create_error(r);
1011
1012 r = sd_bus_call(bus, m, SHORT_BUS_CALL_TIMEOUT_USEC, &error, &reply);
1013 if (r < 0)
1014 return log_error_errno(r, "Failed to check if any systemd-coredump@.service units are running: %s",
1015 bus_error_message(&error, r));
1016
1017 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)");
1018 if (r < 0)
1019 return bus_log_parse_error(r);
1020
1021 while ((r = sd_bus_message_read(
1022 reply, "(ssssssouso)",
1023 &id, NULL, NULL, &state, &substate,
1024 NULL, NULL, NULL, NULL, NULL)) > 0) {
1025 bool found = !STR_IN_SET(state, "inactive", "dead", "failed");
1026 log_debug("Unit %s is %s/%s, %scounting it.", id, state, substate, found ? "" : "not ");
1027 c += found;
1028 }
1029 if (r < 0)
1030 return bus_log_parse_error(r);
1031
1032 r = sd_bus_message_exit_container(reply);
1033 if (r < 0)
1034 return bus_log_parse_error(r);
1035
1036 return c;
1037 }
1038
1039 static int coredumpctl_main(int argc, char *argv[]) {
1040
1041 static const Verb verbs[] = {
1042 { "list", VERB_ANY, VERB_ANY, VERB_DEFAULT, dump_list },
1043 { "info", VERB_ANY, VERB_ANY, 0, dump_list },
1044 { "dump", VERB_ANY, VERB_ANY, 0, dump_core },
1045 { "debug", VERB_ANY, VERB_ANY, 0, run_debug },
1046 { "gdb", VERB_ANY, VERB_ANY, 0, run_debug },
1047 {}
1048 };
1049
1050 return dispatch_verb(argc, argv, verbs, NULL);
1051 }
1052
1053 int main(int argc, char *argv[]) {
1054 int r, units_active;
1055
1056 setlocale(LC_ALL, "");
1057 log_parse_environment();
1058 log_open();
1059
1060 r = parse_argv(argc, argv);
1061 if (r <= 0)
1062 goto end;
1063
1064 sigbus_install();
1065
1066 units_active = check_units_active(); /* error is treated the same as 0 */
1067
1068 r = coredumpctl_main(argc, argv);
1069
1070 if (units_active > 0)
1071 printf("%s-- Notice: %d systemd-coredump@.service %s, output may be incomplete.%s\n",
1072 ansi_highlight_red(),
1073 units_active, units_active == 1 ? "unit is running" : "units are running",
1074 ansi_normal());
1075 end:
1076 pager_close();
1077
1078 safe_fclose(arg_output);
1079
1080 return r >= 0 ? r : EXIT_FAILURE;
1081 }