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