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