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