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