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