]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/coredump/coredump.c
license: LGPL-2.1+ -> LGPL-2.1-or-later
[thirdparty/systemd.git] / src / coredump / coredump.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
f5e04665
LP
2
3#include <errno.h>
803a3464
LP
4#include <stdio.h>
5#include <sys/prctl.h>
cacd6403 6#include <sys/xattr.h>
4f5dd394 7#include <unistd.h>
f5e04665 8
349cc4a5 9#if HAVE_ELFUTILS
3c171f0b
LP
10#include <dwarf.h>
11#include <elfutils/libdwfl.h>
4d229b31
UTL
12#endif
13
73a99163 14#include "sd-daemon.h"
f11943c5
LP
15#include "sd-journal.h"
16#include "sd-login.h"
73a99163 17#include "sd-messages.h"
4f5dd394
LP
18
19#include "acl-util.h"
b5efdb8a 20#include "alloc-util.h"
430f0182 21#include "capability-util.h"
ba1261bc 22#include "cgroup-util.h"
4f5dd394 23#include "compress.h"
34c10968
LP
24#include "conf-parser.h"
25#include "copy.h"
f11943c5 26#include "coredump-vacuum.h"
a0956174 27#include "dirent-util.h"
4f5dd394 28#include "escape.h"
3ffd4af2 29#include "fd-util.h"
4f5dd394 30#include "fileio.h"
f4f15635 31#include "fs-util.h"
afc5dbf3 32#include "io-util.h"
b18453ed 33#include "journal-importer.h"
4f5dd394
LP
34#include "log.h"
35#include "macro.h"
5e332028 36#include "main-func.h"
0a970718 37#include "memory-util.h"
4f5dd394 38#include "mkdir.h"
6bedfcbb 39#include "parse-util.h"
0b452006 40#include "process-util.h"
d14bcb4e 41#include "signal-util.h"
3c171f0b 42#include "socket-util.h"
4f5dd394
LP
43#include "special.h"
44#include "stacktrace.h"
8b43440b 45#include "string-table.h"
07630cea 46#include "string-util.h"
4f5dd394 47#include "strv.h"
e4de7287 48#include "tmpfile-util.h"
98dcb8f4 49#include "user-record.h"
b1d4f8e1 50#include "user-util.h"
34727273 51
34c10968 52/* The maximum size up to which we process coredumps */
59f448cf 53#define PROCESS_SIZE_MAX ((uint64_t) (2LLU*1024LLU*1024LLU*1024LLU))
34c10968 54
bdfd7b2c 55/* The maximum size up to which we leave the coredump around on disk */
34c10968
LP
56#define EXTERNAL_SIZE_MAX PROCESS_SIZE_MAX
57
bdfd7b2c 58/* The maximum size up to which we store the coredump in the journal */
25cad95c 59#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
34c10968 60#define JOURNAL_SIZE_MAX ((size_t) (767LU*1024LU*1024LU))
25cad95c
YW
61#else
62/* oss-fuzz limits memory usage. */
63#define JOURNAL_SIZE_MAX ((size_t) (10LU*1024LU*1024LU))
64#endif
f5e04665 65
c4aa09b0 66/* Make sure to not make this larger than the maximum journal entry
27f931d1 67 * size. See DATA_SIZE_MAX in journal-importer.h. */
874bc134 68assert_cc(JOURNAL_SIZE_MAX <= DATA_SIZE_MAX);
f5e04665
LP
69
70enum {
f46c706b 71 /* We use these as array indexes for our process metadata cache.
ea5cc2a8 72 *
f46c706b
FB
73 * The first indices of the cache stores the same metadata as the ones passed by
74 * the kernel via argv[], ie the strings array passed by the kernel according to
75 * our pattern defined in /proc/sys/kernel/core_pattern (see man:core(5)). */
76
77 META_ARGV_PID, /* %P: as seen in the initial pid namespace */
78 META_ARGV_UID, /* %u: as seen in the initial user namespace */
79 META_ARGV_GID, /* %g: as seen in the initial user namespace */
80 META_ARGV_SIGNAL, /* %s: number of signal causing dump */
64a5384f 81 META_ARGV_TIMESTAMP, /* %t: time of dump, expressed as seconds since the Epoch (we expand this to µs granularity) */
f46c706b
FB
82 META_ARGV_RLIMIT, /* %c: core file size soft resource limit */
83 META_ARGV_HOSTNAME, /* %h: hostname */
84 _META_ARGV_MAX,
85
86 /* The following indexes are cached for a couple of special fields we use (and
87 * thereby need to be retrieved quickly) for naming coredump files, and attaching
88 * xattrs. Unlike the previous ones they are retrieved from the runtime
89 * environment. */
90
91 META_COMM = _META_ARGV_MAX,
92 _META_MANDATORY_MAX,
93
94 /* The rest are similar to the previous ones except that we won't fail if one of
95 * them is missing. */
96
97 META_EXE = _META_MANDATORY_MAX,
98 META_UNIT,
99 _META_MAX
f5e04665
LP
100};
101
f46c706b
FB
102static const char * const meta_field_names[_META_MAX] = {
103 [META_ARGV_PID] = "COREDUMP_PID=",
104 [META_ARGV_UID] = "COREDUMP_UID=",
105 [META_ARGV_GID] = "COREDUMP_GID=",
106 [META_ARGV_SIGNAL] = "COREDUMP_SIGNAL=",
107 [META_ARGV_TIMESTAMP] = "COREDUMP_TIMESTAMP=",
108 [META_ARGV_RLIMIT] = "COREDUMP_RLIMIT=",
109 [META_ARGV_HOSTNAME] = "COREDUMP_HOSTNAME=",
110 [META_COMM] = "COREDUMP_COMM=",
111 [META_EXE] = "COREDUMP_EXE=",
112 [META_UNIT] = "COREDUMP_UNIT=",
113};
114
115typedef struct Context {
116 const char *meta[_META_MAX];
117 pid_t pid;
118 bool is_pid1;
119 bool is_journald;
120} Context;
121
34c10968
LP
122typedef enum CoredumpStorage {
123 COREDUMP_STORAGE_NONE,
124 COREDUMP_STORAGE_EXTERNAL,
125 COREDUMP_STORAGE_JOURNAL,
34c10968
LP
126 _COREDUMP_STORAGE_MAX,
127 _COREDUMP_STORAGE_INVALID = -1
128} CoredumpStorage;
129
34c10968
LP
130static const char* const coredump_storage_table[_COREDUMP_STORAGE_MAX] = {
131 [COREDUMP_STORAGE_NONE] = "none",
132 [COREDUMP_STORAGE_EXTERNAL] = "external",
133 [COREDUMP_STORAGE_JOURNAL] = "journal",
34c10968
LP
134};
135
136DEFINE_PRIVATE_STRING_TABLE_LOOKUP(coredump_storage, CoredumpStorage);
8c9571d0 137static DEFINE_CONFIG_PARSE_ENUM(config_parse_coredump_storage, coredump_storage, CoredumpStorage, "Failed to parse storage setting");
34727273
ZJS
138
139static CoredumpStorage arg_storage = COREDUMP_STORAGE_EXTERNAL;
8c9571d0 140static bool arg_compress = true;
59f448cf
LP
141static uint64_t arg_process_size_max = PROCESS_SIZE_MAX;
142static uint64_t arg_external_size_max = EXTERNAL_SIZE_MAX;
6e2b4a69 143static uint64_t arg_journal_size_max = JOURNAL_SIZE_MAX;
59f448cf
LP
144static uint64_t arg_keep_free = (uint64_t) -1;
145static uint64_t arg_max_use = (uint64_t) -1;
34c10968
LP
146
147static int parse_config(void) {
34c10968 148 static const ConfigTableItem items[] = {
8c9571d0
LP
149 { "Coredump", "Storage", config_parse_coredump_storage, 0, &arg_storage },
150 { "Coredump", "Compress", config_parse_bool, 0, &arg_compress },
59f448cf
LP
151 { "Coredump", "ProcessSizeMax", config_parse_iec_uint64, 0, &arg_process_size_max },
152 { "Coredump", "ExternalSizeMax", config_parse_iec_uint64, 0, &arg_external_size_max },
8c9571d0 153 { "Coredump", "JournalSizeMax", config_parse_iec_size, 0, &arg_journal_size_max },
59f448cf
LP
154 { "Coredump", "KeepFree", config_parse_iec_uint64, 0, &arg_keep_free },
155 { "Coredump", "MaxUse", config_parse_iec_uint64, 0, &arg_max_use },
34c10968
LP
156 {}
157 };
158
4f9ff96a
LP
159 return config_parse_many_nulstr(
160 PKGSYSCONFDIR "/coredump.conf",
161 CONF_PATHS_NULSTR("systemd/coredump.conf.d"),
162 "Coredump\0",
163 config_item_table_lookup, items,
164 CONFIG_PARSE_WARN,
165 NULL,
166 NULL);
34c10968
LP
167}
168
a1e92eee 169static uint64_t storage_size_max(void) {
ee0449fd
ZJS
170 if (arg_storage == COREDUMP_STORAGE_EXTERNAL)
171 return arg_external_size_max;
172 if (arg_storage == COREDUMP_STORAGE_JOURNAL)
173 return arg_journal_size_max;
174 assert(arg_storage == COREDUMP_STORAGE_NONE);
175 return 0;
73a99163
ZJS
176}
177
34c10968
LP
178static int fix_acl(int fd, uid_t uid) {
179
349cc4a5 180#if HAVE_ACL
709f6e46 181 int r;
34c10968 182
b59233e6 183 assert(fd >= 0);
d81be4e7 184 assert(uid_is_valid(uid));
b59233e6 185
05fd2156 186 if (uid_is_system(uid) || uid_is_dynamic(uid) || uid == UID_NOBODY)
34c10968
LP
187 return 0;
188
d81be4e7 189 /* Make sure normal users can read (but not write or delete) their own coredumps */
567aeb58 190 r = fd_add_uid_acl_permission(fd, uid, ACL_READ);
709f6e46 191 if (r < 0)
567aeb58 192 return log_error_errno(r, "Failed to adjust ACL of the coredump: %m");
34c10968
LP
193#endif
194
195 return 0;
196}
197
f46c706b
FB
198static int fix_xattr(int fd, const Context *context) {
199
200 static const char * const xattrs[_META_MAX] = {
201 [META_ARGV_PID] = "user.coredump.pid",
202 [META_ARGV_UID] = "user.coredump.uid",
203 [META_ARGV_GID] = "user.coredump.gid",
204 [META_ARGV_SIGNAL] = "user.coredump.signal",
205 [META_ARGV_TIMESTAMP] = "user.coredump.timestamp",
206 [META_ARGV_RLIMIT] = "user.coredump.rlimit",
207 [META_ARGV_HOSTNAME] = "user.coredump.hostname",
208 [META_COMM] = "user.coredump.comm",
209 [META_EXE] = "user.coredump.exe",
0cd77f97
LP
210 };
211
34c10968 212 int r = 0;
0cd77f97 213 unsigned i;
34c10968 214
b59233e6
LP
215 assert(fd >= 0);
216
1eef15b1 217 /* Attach some metadata to coredumps via extended
34c10968
LP
218 * attributes. Just because we can. */
219
f46c706b 220 for (i = 0; i < _META_MAX; i++) {
1eef15b1
ZJS
221 int k;
222
f46c706b 223 if (isempty(context->meta[i]) || !xattrs[i])
0cd77f97 224 continue;
34c10968 225
f46c706b 226 k = fsetxattr(fd, xattrs[i], context->meta[i], strlen(context->meta[i]), XATTR_CREATE);
1eef15b1 227 if (k < 0 && r == 0)
34c10968 228 r = -errno;
0cd77f97 229 }
34c10968
LP
230
231 return r;
232}
233
b0b21dce 234#define filename_escape(s) xescape((s), "./ ")
34c10968 235
a1e92eee 236static const char *coredump_tmpfile_name(const char *s) {
0c773903
EV
237 return s ? s : "(unnamed temporary file)";
238}
239
b59233e6
LP
240static int fix_permissions(
241 int fd,
242 const char *filename,
243 const char *target,
f46c706b 244 const Context *context,
b59233e6
LP
245 uid_t uid) {
246
03532f0a
LP
247 int r;
248
b59233e6 249 assert(fd >= 0);
b59233e6 250 assert(target);
3c171f0b 251 assert(context);
cfd652ed
ZJS
252
253 /* Ignore errors on these */
3c171f0b
LP
254 (void) fchmod(fd, 0640);
255 (void) fix_acl(fd, uid);
256 (void) fix_xattr(fd, context);
cfd652ed 257
4a62c710 258 if (fsync(fd) < 0)
0c773903 259 return log_error_errno(errno, "Failed to sync coredump %s: %m", coredump_tmpfile_name(filename));
cfd652ed 260
8ac2f74f
LP
261 (void) fsync_directory_of_file(fd);
262
03532f0a
LP
263 r = link_tmpfile(fd, filename, target);
264 if (r < 0)
265 return log_error_errno(r, "Failed to move coredump %s into place: %m", target);
cfd652ed
ZJS
266
267 return 0;
268}
269
59f448cf 270static int maybe_remove_external_coredump(const char *filename, uint64_t size) {
cfd652ed 271
b59233e6 272 /* Returns 1 if might remove, 0 if will not remove, < 0 on error. */
cfd652ed 273
fc6cec86 274 if (arg_storage == COREDUMP_STORAGE_EXTERNAL &&
cfd652ed
ZJS
275 size <= arg_external_size_max)
276 return 0;
277
278 if (!filename)
279 return 1;
280
4a62c710
MS
281 if (unlink(filename) < 0 && errno != ENOENT)
282 return log_error_errno(errno, "Failed to unlink %s: %m", filename);
cfd652ed
ZJS
283
284 return 1;
285}
286
f46c706b 287static int make_filename(const Context *context, char **ret) {
b59233e6 288 _cleanup_free_ char *c = NULL, *u = NULL, *p = NULL, *t = NULL;
a7f7d1bd 289 sd_id128_t boot = {};
34c10968
LP
290 int r;
291
3c171f0b 292 assert(context);
34c10968 293
f46c706b 294 c = filename_escape(context->meta[META_COMM]);
34c10968 295 if (!c)
b59233e6 296 return -ENOMEM;
34c10968 297
f46c706b 298 u = filename_escape(context->meta[META_ARGV_UID]);
0dc5d23c 299 if (!u)
b59233e6 300 return -ENOMEM;
34c10968
LP
301
302 r = sd_id128_get_boot(&boot);
b59233e6 303 if (r < 0)
34c10968 304 return r;
34c10968 305
f46c706b 306 p = filename_escape(context->meta[META_ARGV_PID]);
b59233e6
LP
307 if (!p)
308 return -ENOMEM;
309
f46c706b 310 t = filename_escape(context->meta[META_ARGV_TIMESTAMP]);
b59233e6
LP
311 if (!t)
312 return -ENOMEM;
313
314 if (asprintf(ret,
64a5384f 315 "/var/lib/systemd/coredump/core.%s.%s." SD_ID128_FORMAT_STR ".%s.%s",
34c10968 316 c,
0dc5d23c 317 u,
34c10968
LP
318 SD_ID128_FORMAT_VAL(boot),
319 p,
b59233e6
LP
320 t) < 0)
321 return -ENOMEM;
322
323 return 0;
324}
325
326static int save_external_coredump(
f46c706b 327 const Context *context,
3c171f0b 328 int input_fd,
b59233e6 329 char **ret_filename,
5f3e0a74
HW
330 int *ret_node_fd,
331 int *ret_data_fd,
0cd4e913 332 uint64_t *ret_size,
cc4419ed 333 bool *ret_truncated) {
b59233e6
LP
334
335 _cleanup_free_ char *fn = NULL, *tmp = NULL;
336 _cleanup_close_ int fd = -1;
ee0449fd 337 uint64_t rlimit, process_limit, max_size;
b59233e6 338 struct stat st;
3c171f0b 339 uid_t uid;
b59233e6
LP
340 int r;
341
3c171f0b 342 assert(context);
b59233e6 343 assert(ret_filename);
5f3e0a74
HW
344 assert(ret_node_fd);
345 assert(ret_data_fd);
b59233e6
LP
346 assert(ret_size);
347
f46c706b 348 r = parse_uid(context->meta[META_ARGV_UID], &uid);
3c171f0b
LP
349 if (r < 0)
350 return log_error_errno(r, "Failed to parse UID: %m");
351
f46c706b 352 r = safe_atou64(context->meta[META_ARGV_RLIMIT], &rlimit);
bdfd7b2c 353 if (r < 0)
f46c706b
FB
354 return log_error_errno(r, "Failed to parse resource limit '%s': %m",
355 context->meta[META_ARGV_RLIMIT]);
d7a0f1f4 356 if (rlimit < page_size())
f46c706b
FB
357 /* Is coredumping disabled? Then don't bother saving/processing the
358 * coredump. Anything below PAGE_SIZE cannot give a readable coredump
359 * (the kernel uses ELF_EXEC_PAGESIZE which is not easily accessible, but
360 * is usually the same as PAGE_SIZE. */
baaa35ad
ZJS
361 return log_info_errno(SYNTHETIC_ERRNO(EBADSLT),
362 "Resource limits disable core dumping for process %s (%s).",
f46c706b 363 context->meta[META_ARGV_PID], context->meta[META_COMM]);
bdfd7b2c 364
ee0449fd 365 process_limit = MAX(arg_process_size_max, storage_size_max());
baaa35ad
ZJS
366 if (process_limit == 0)
367 return log_debug_errno(SYNTHETIC_ERRNO(EBADSLT),
368 "Limits for coredump processing and storage are both 0, not dumping core.");
ee0449fd 369
bdfd7b2c 370 /* Never store more than the process configured, or than we actually shall keep or process */
ee0449fd 371 max_size = MIN(rlimit, process_limit);
bdfd7b2c 372
3c171f0b 373 r = make_filename(context, &fn);
23bbb0de
MS
374 if (r < 0)
375 return log_error_errno(r, "Failed to determine coredump file name: %m");
34c10968 376
6e5dcce4 377 (void) mkdir_p_label("/var/lib/systemd/coredump", 0755);
803a3464 378
03532f0a 379 fd = open_tmpfile_linkable(fn, O_RDWR|O_CLOEXEC, &tmp);
4a62c710 380 if (fd < 0)
03532f0a 381 return log_error_errno(fd, "Failed to create temporary file for coredump %s: %m", fn);
803a3464 382
1c876927 383 r = copy_bytes(input_fd, fd, max_size, 0);
73a99163 384 if (r < 0) {
f46c706b
FB
385 log_error_errno(r, "Cannot store coredump of %s (%s): %m",
386 context->meta[META_ARGV_PID], context->meta[META_COMM]);
93240d3a 387 goto fail;
0cd4e913 388 }
cc4419ed
ZJS
389 *ret_truncated = r == 1;
390 if (*ret_truncated)
73a99163
ZJS
391 log_struct(LOG_INFO,
392 LOG_MESSAGE("Core file was truncated to %zu bytes.", max_size),
393 "SIZE_LIMIT=%zu", max_size,
a1230ff9 394 "MESSAGE_ID=" SD_MESSAGE_TRUNCATED_CORE_STR);
803a3464 395
34c10968 396 if (fstat(fd, &st) < 0) {
73a99163 397 log_error_errno(errno, "Failed to fstat core file %s: %m", coredump_tmpfile_name(tmp));
34c10968
LP
398 goto fail;
399 }
400
7849c2ac 401 if (lseek(fd, 0, SEEK_SET) == (off_t) -1) {
0c773903 402 log_error_errno(errno, "Failed to seek on %s: %m", coredump_tmpfile_name(tmp));
b59233e6 403 goto fail;
7849c2ac
TA
404 }
405
d80b051c 406#if HAVE_COMPRESSION
cfd652ed 407 /* If we will remove the coredump anyway, do not compress. */
6e9ef603 408 if (arg_compress && !maybe_remove_external_coredump(NULL, st.st_size)) {
cfd652ed 409
b59233e6
LP
410 _cleanup_free_ char *fn_compressed = NULL, *tmp_compressed = NULL;
411 _cleanup_close_ int fd_compressed = -1;
cfd652ed 412
b910cc72 413 fn_compressed = strjoin(fn, COMPRESSED_EXT);
b59233e6 414 if (!fn_compressed) {
d89c8fdf 415 log_oom();
cfd652ed
ZJS
416 goto uncompressed;
417 }
418
03532f0a
LP
419 fd_compressed = open_tmpfile_linkable(fn_compressed, O_RDWR|O_CLOEXEC, &tmp_compressed);
420 if (fd_compressed < 0) {
421 log_error_errno(fd_compressed, "Failed to create temporary file for coredump %s: %m", fn_compressed);
b59233e6 422 goto uncompressed;
03532f0a 423 }
cfd652ed 424
d89c8fdf 425 r = compress_stream(fd, fd_compressed, -1);
b59233e6 426 if (r < 0) {
0c773903 427 log_error_errno(r, "Failed to compress %s: %m", coredump_tmpfile_name(tmp_compressed));
b59233e6
LP
428 goto fail_compressed;
429 }
430
3c171f0b 431 r = fix_permissions(fd_compressed, tmp_compressed, fn_compressed, context, uid);
cfd652ed 432 if (r < 0)
b59233e6
LP
433 goto fail_compressed;
434
435 /* OK, this worked, we can get rid of the uncompressed version now */
0c773903
EV
436 if (tmp)
437 unlink_noerrno(tmp);
cfd652ed 438
1cc6c93a
YW
439 *ret_filename = TAKE_PTR(fn_compressed); /* compressed */
440 *ret_node_fd = TAKE_FD(fd_compressed); /* compressed */
441 *ret_data_fd = TAKE_FD(fd); /* uncompressed */
59f448cf 442 *ret_size = (uint64_t) st.st_size; /* uncompressed */
cfd652ed 443
cfd652ed
ZJS
444 return 0;
445
b59233e6 446 fail_compressed:
0c773903
EV
447 if (tmp_compressed)
448 (void) unlink(tmp_compressed);
34c10968 449 }
cfd652ed
ZJS
450
451uncompressed:
3b1a55e1 452#endif
5f3e0a74 453
3c171f0b 454 r = fix_permissions(fd, tmp, fn, context, uid);
cfd652ed
ZJS
455 if (r < 0)
456 goto fail;
34c10968 457
1cc6c93a
YW
458 *ret_filename = TAKE_PTR(fn);
459 *ret_data_fd = TAKE_FD(fd);
5f3e0a74 460 *ret_node_fd = -1;
59f448cf 461 *ret_size = (uint64_t) st.st_size;
34c10968 462
34c10968
LP
463 return 0;
464
465fail:
0c773903
EV
466 if (tmp)
467 (void) unlink(tmp);
34c10968
LP
468 return r;
469}
470
471static int allocate_journal_field(int fd, size_t size, char **ret, size_t *ret_size) {
472 _cleanup_free_ char *field = NULL;
473 ssize_t n;
474
8d4e028f 475 assert(fd >= 0);
34c10968
LP
476 assert(ret);
477 assert(ret_size);
478
4a62c710
MS
479 if (lseek(fd, 0, SEEK_SET) == (off_t) -1)
480 return log_warning_errno(errno, "Failed to seek: %m");
803a3464 481
34c10968
LP
482 field = malloc(9 + size);
483 if (!field) {
cfd652ed 484 log_warning("Failed to allocate memory for coredump, coredump will not be stored.");
34c10968
LP
485 return -ENOMEM;
486 }
487
488 memcpy(field, "COREDUMP=", 9);
489
490 n = read(fd, field + 9, size);
23bbb0de
MS
491 if (n < 0)
492 return log_error_errno((int) n, "Failed to read core data: %m");
baaa35ad
ZJS
493 if ((size_t) n < size)
494 return log_error_errno(SYNTHETIC_ERRNO(EIO),
495 "Core data too short.");
34c10968 496
1cc6c93a 497 *ret = TAKE_PTR(field);
34c10968
LP
498 *ret_size = size + 9;
499
34c10968
LP
500 return 0;
501}
803a3464 502
3f132692
JF
503/* Joins /proc/[pid]/fd/ and /proc/[pid]/fdinfo/ into the following lines:
504 * 0:/dev/pts/23
505 * pos: 0
506 * flags: 0100002
507 *
508 * 1:/dev/pts/23
509 * pos: 0
510 * flags: 0100002
511 *
512 * 2:/dev/pts/23
513 * pos: 0
514 * flags: 0100002
515 * EOF
516 */
517static int compose_open_fds(pid_t pid, char **open_fds) {
4d84bc2f
LP
518 _cleanup_closedir_ DIR *proc_fd_dir = NULL;
519 _cleanup_close_ int proc_fdinfo_fd = -1;
520 _cleanup_free_ char *buffer = NULL;
3f132692 521 _cleanup_fclose_ FILE *stream = NULL;
59059b4a 522 const char *fddelim = "", *path;
3f132692 523 struct dirent *dent = NULL;
4d84bc2f 524 size_t size = 0;
7b26ea6f 525 int r;
3f132692
JF
526
527 assert(pid >= 0);
528 assert(open_fds != NULL);
529
59059b4a 530 path = procfs_file_alloca(pid, "fd");
3f132692 531 proc_fd_dir = opendir(path);
59059b4a
ZJS
532 if (!proc_fd_dir)
533 return -errno;
3f132692 534
4d84bc2f 535 proc_fdinfo_fd = openat(dirfd(proc_fd_dir), "../fdinfo", O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC|O_PATH);
59059b4a
ZJS
536 if (proc_fdinfo_fd < 0)
537 return -errno;
3f132692 538
2fe21124 539 stream = open_memstream_unlocked(&buffer, &size);
3f132692
JF
540 if (!stream)
541 return -ENOMEM;
542
4d84bc2f 543 FOREACH_DIRENT(dent, proc_fd_dir, return -errno) {
3f132692 544 _cleanup_fclose_ FILE *fdinfo = NULL;
4d84bc2f 545 _cleanup_free_ char *fdname = NULL;
b46c3e49 546 _cleanup_close_ int fd = -1;
3f132692 547
59059b4a 548 r = readlinkat_malloc(dirfd(proc_fd_dir), dent->d_name, &fdname);
3f132692
JF
549 if (r < 0)
550 return r;
551
552 fprintf(stream, "%s%s:%s\n", fddelim, dent->d_name, fdname);
553 fddelim = "\n";
554
555 /* Use the directory entry from /proc/[pid]/fd with /proc/[pid]/fdinfo */
59059b4a
ZJS
556 fd = openat(proc_fdinfo_fd, dent->d_name, O_NOFOLLOW|O_CLOEXEC|O_RDONLY);
557 if (fd < 0)
3f132692
JF
558 continue;
559
b46c3e49
VC
560 fdinfo = take_fdopen(&fd, "r");
561 if (!fdinfo)
3f132692
JF
562 continue;
563
7b26ea6f
LP
564 for (;;) {
565 _cleanup_free_ char *line = NULL;
566
567 r = read_line(fdinfo, LONG_LINE_MAX, &line);
568 if (r < 0)
569 return r;
570 if (r == 0)
571 break;
572
0d536673 573 fputs(line, stream);
7b26ea6f 574 fputc('\n', stream);
4d84bc2f 575 }
3f132692
JF
576 }
577
4d84bc2f 578 errno = 0;
74ca738f 579 stream = safe_fclose(stream);
4d84bc2f 580
b3267152 581 if (errno > 0)
4d84bc2f
LP
582 return -errno;
583
ae2a15bc 584 *open_fds = TAKE_PTR(buffer);
4d84bc2f 585
3f132692
JF
586 return 0;
587}
588
7ed03ce6
JF
589static int get_process_ns(pid_t pid, const char *namespace, ino_t *ns) {
590 const char *p;
591 struct stat stbuf;
592 _cleanup_close_ int proc_ns_dir_fd;
593
594 p = procfs_file_alloca(pid, "ns");
595
596 proc_ns_dir_fd = open(p, O_DIRECTORY | O_CLOEXEC | O_RDONLY);
597 if (proc_ns_dir_fd < 0)
598 return -errno;
599
600 if (fstatat(proc_ns_dir_fd, namespace, &stbuf, /* flags */0) < 0)
601 return -errno;
602
603 *ns = stbuf.st_ino;
604 return 0;
605}
606
607static int get_mount_namespace_leader(pid_t pid, pid_t *container_pid) {
608 pid_t cpid = pid, ppid = 0;
609 ino_t proc_mntns;
c53aafb7 610 int r;
7ed03ce6
JF
611
612 r = get_process_ns(pid, "mnt", &proc_mntns);
613 if (r < 0)
614 return r;
615
aa7530d6 616 for (;;) {
7ed03ce6
JF
617 ino_t parent_mntns;
618
619 r = get_process_ppid(cpid, &ppid);
620 if (r < 0)
621 return r;
622
623 r = get_process_ns(ppid, "mnt", &parent_mntns);
624 if (r < 0)
625 return r;
626
627 if (proc_mntns != parent_mntns)
628 break;
629
630 if (ppid == 1)
631 return -ENOENT;
632
633 cpid = ppid;
634 }
635
636 *container_pid = ppid;
637 return 0;
638}
639
640/* Returns 1 if the parent was found.
641 * Returns 0 if there is not a process we can call the pid's
642 * container parent (the pid's process isn't 'containerized').
643 * Returns a negative number on errors.
644 */
645static int get_process_container_parent_cmdline(pid_t pid, char** cmdline) {
646 int r = 0;
647 pid_t container_pid;
648 const char *proc_root_path;
649 struct stat root_stat, proc_root_stat;
650
651 /* To compare inodes of / and /proc/[pid]/root */
652 if (stat("/", &root_stat) < 0)
653 return -errno;
654
655 proc_root_path = procfs_file_alloca(pid, "root");
656 if (stat(proc_root_path, &proc_root_stat) < 0)
657 return -errno;
658
659 /* The process uses system root. */
660 if (proc_root_stat.st_ino == root_stat.st_ino) {
661 *cmdline = NULL;
662 return 0;
663 }
664
665 r = get_mount_namespace_leader(pid, &container_pid);
666 if (r < 0)
667 return r;
668
09c1dcee 669 r = get_process_cmdline(container_pid, SIZE_MAX, 0, cmdline);
d3cba4ea
EV
670 if (r < 0)
671 return r;
672
673 return 1;
7ed03ce6
JF
674}
675
f46c706b 676static int change_uid_gid(const Context *context) {
3c171f0b
LP
677 uid_t uid;
678 gid_t gid;
679 int r;
34c10968 680
f46c706b 681 r = parse_uid(context->meta[META_ARGV_UID], &uid);
3c171f0b
LP
682 if (r < 0)
683 return r;
8c8549db 684
28add648 685 if (uid_is_system(uid)) {
888e378d
LP
686 const char *user = "systemd-coredump";
687
fafff8f1 688 r = get_user_creds(&user, &uid, &gid, NULL, NULL, 0);
888e378d
LP
689 if (r < 0) {
690 log_warning_errno(r, "Cannot resolve %s user. Proceeding to dump core as root: %m", user);
691 uid = gid = 0;
692 }
693 } else {
f46c706b 694 r = parse_gid(context->meta[META_ARGV_GID], &gid);
888e378d
LP
695 if (r < 0)
696 return r;
697 }
3c171f0b
LP
698
699 return drop_privileges(uid, gid, 0);
700}
8c8549db 701
3c171f0b 702static int submit_coredump(
f46c706b 703 Context *context,
9a435388 704 struct iovec_wrapper *iovw,
3c171f0b 705 int input_fd) {
34c10968 706
5f3e0a74 707 _cleanup_close_ int coredump_fd = -1, coredump_node_fd = -1;
9a435388 708 _cleanup_free_ char *filename = NULL, *coredump_data = NULL;
51d3783d 709 _cleanup_free_ char *stacktrace = NULL;
9a435388 710 char *core_message;
a5ca3649 711 uint64_t coredump_size = UINT64_MAX;
f46c706b 712 bool truncated = false;
3c171f0b 713 int r;
f5e04665 714
3c171f0b 715 assert(context);
9a435388 716 assert(iovw);
3c171f0b 717 assert(input_fd >= 0);
f5e04665 718
3c171f0b
LP
719 /* Vacuum before we write anything again */
720 (void) coredump_vacuum(-1, arg_keep_free, arg_max_use);
803a3464 721
3c171f0b 722 /* Always stream the coredump to disk, if that's possible */
0cd4e913
ZJS
723 r = save_external_coredump(context, input_fd,
724 &filename, &coredump_node_fd, &coredump_fd, &coredump_size, &truncated);
3c171f0b
LP
725 if (r < 0)
726 /* Skip whole core dumping part */
727 goto log;
728
51d3783d
FB
729 /* If we don't want to keep the coredump on disk, remove it now, as later on we
730 * will lack the privileges for it. However, we keep the fd to it, so that we can
731 * still process it and log it. */
3c171f0b
LP
732 r = maybe_remove_external_coredump(filename, coredump_size);
733 if (r < 0)
734 return r;
735 if (r == 0) {
2a3bebd0 736 (void) iovw_put_string_field(iovw, "COREDUMP_FILENAME=", filename);
3c171f0b 737
6e9ef603 738 } else if (arg_storage == COREDUMP_STORAGE_EXTERNAL)
5206a724 739 log_info("The core will not be stored: size %"PRIu64" is greater than %"PRIu64" (the configured maximum)",
6e9ef603 740 coredump_size, arg_external_size_max);
f5e04665 741
3c171f0b
LP
742 /* Vacuum again, but exclude the coredump we just created */
743 (void) coredump_vacuum(coredump_node_fd >= 0 ? coredump_node_fd : coredump_fd, arg_keep_free, arg_max_use);
8c9571d0 744
51d3783d
FB
745 /* Now, let's drop privileges to become the user who owns the segfaulted process
746 * and allocate the coredump memory under the user's uid. This also ensures that
747 * the credentials journald will see are the ones of the coredumping user, thus
748 * making sure the user gets access to the core dump. Let's also get rid of all
3c171f0b
LP
749 * capabilities, if we run as root, we won't need them anymore. */
750 r = change_uid_gid(context);
751 if (r < 0)
752 return log_error_errno(r, "Failed to drop privileges: %m");
34c10968 753
349cc4a5 754#if HAVE_ELFUTILS
5238e957 755 /* Try to get a stack trace if we can */
51d3783d
FB
756 if (coredump_size > arg_process_size_max) {
757 log_debug("Not generating stack trace: core size %"PRIu64" is greater "
758 "than %"PRIu64" (the configured maximum)",
6e9ef603 759 coredump_size, arg_process_size_max);
51d3783d 760 } else
f46c706b 761 coredump_make_stack_trace(coredump_fd, context->meta[META_EXE], &stacktrace);
3c171f0b 762#endif
51d3783d 763
3c171f0b 764log:
f46c706b
FB
765 core_message = strjoina("Process ", context->meta[META_ARGV_PID],
766 " (", context->meta[META_COMM], ") of user ",
767 context->meta[META_ARGV_UID], " dumped core.",
768 context->is_journald && filename ? "\nCoredump diverted to " : NULL,
769 context->is_journald && filename ? filename : NULL);
51d3783d 770
9a435388 771 core_message = strjoina(core_message, stacktrace ? "\n\n" : NULL, stacktrace);
92e92d71 772
f46c706b 773 if (context->is_journald) {
4f62556d 774 /* We cannot log to the journal, so just print the message.
92e92d71 775 * The target was set previously to something safe. */
9a435388 776 log_dispatch(LOG_ERR, 0, core_message);
92e92d71
ZJS
777 return 0;
778 }
779
2a3bebd0 780 (void) iovw_put_string_field(iovw, "MESSAGE=", core_message);
3c171f0b 781
0cd4e913 782 if (truncated)
2a3bebd0 783 (void) iovw_put_string_field(iovw, "COREDUMP_TRUNCATED=", "1");
0cd4e913 784
3c171f0b 785 /* Optionally store the entire coredump in the journal */
6e9ef603
ZJS
786 if (arg_storage == COREDUMP_STORAGE_JOURNAL) {
787 if (coredump_size <= arg_journal_size_max) {
788 size_t sz = 0;
789
790 /* Store the coredump itself in the journal */
791
792 r = allocate_journal_field(coredump_fd, (size_t) coredump_size, &coredump_data, &sz);
9a435388
FB
793 if (r >= 0) {
794 if (iovw_put(iovw, coredump_data, sz) >= 0)
795 TAKE_PTR(coredump_data);
796 } else
6e9ef603
ZJS
797 log_warning_errno(r, "Failed to attach the core to the journal entry: %m");
798 } else
5206a724 799 log_info("The core will not be stored: size %"PRIu64" is greater than %"PRIu64" (the configured maximum)",
6e9ef603 800 coredump_size, arg_journal_size_max);
f5e04665
LP
801 }
802
9a435388 803 r = sd_journal_sendv(iovw->iovec, iovw->count);
3c171f0b
LP
804 if (r < 0)
805 return log_error_errno(r, "Failed to log coredump: %m");
806
807 return 0;
808}
809
f46c706b
FB
810static int save_context(Context *context, const struct iovec_wrapper *iovw) {
811 unsigned n, i, count = 0;
812 const char *unit;
813 int r;
3c171f0b 814
3c171f0b 815 assert(context);
f46c706b
FB
816 assert(iovw);
817 assert(iovw->count >= _META_ARGV_MAX);
3c171f0b 818
f46c706b 819 /* The context does not allocate any memory on its own */
3c171f0b 820
f46c706b
FB
821 for (n = 0; n < iovw->count; n++) {
822 struct iovec *iovec = iovw->iovec + n;
92e92d71 823
f46c706b
FB
824 for (i = 0; i < ELEMENTSOF(meta_field_names); i++) {
825 char *p;
826
827 /* Note that these strings are NUL terminated, because we made sure that a
828 * trailing NUL byte is in the buffer, though not included in the iov_len
829 * count (see process_socket() and gather_pid_metadata_*()) */
830 assert(((char*) iovec->iov_base)[iovec->iov_len] == 0);
3c171f0b 831
f46c706b
FB
832 p = startswith(iovec->iov_base, meta_field_names[i]);
833 if (p) {
834 context->meta[i] = p;
835 count++;
836 break;
837 }
838 }
3c171f0b 839 }
f46c706b
FB
840
841 if (!context->meta[META_ARGV_PID])
842 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
843 "Failed to find the PID of crashing process");
844
845 r = parse_pid(context->meta[META_ARGV_PID], &context->pid);
846 if (r < 0)
847 return log_error_errno(r, "Failed to parse PID \"%s\": %m", context->meta[META_ARGV_PID]);
848
849 unit = context->meta[META_UNIT];
850 context->is_pid1 = streq(context->meta[META_ARGV_PID], "1") || streq_ptr(unit, SPECIAL_INIT_SCOPE);
851 context->is_journald = streq_ptr(unit, SPECIAL_JOURNALD_SERVICE);
852
853 return 0;
3c171f0b
LP
854}
855
856static int process_socket(int fd) {
f8540bde 857 _cleanup_close_ int input_fd = -1;
f46c706b 858 Context context = {};
9a435388
FB
859 struct iovec_wrapper iovw = {};
860 struct iovec iovec;
f46c706b 861 int i, r;
3c171f0b
LP
862
863 assert(fd >= 0);
864
6bf3c61c 865 log_setup_service();
3c171f0b 866
988e89ee
ZJS
867 log_debug("Processing coredump received on stdin...");
868
3c171f0b 869 for (;;) {
fb29cdbe 870 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control;
3c171f0b
LP
871 struct msghdr mh = {
872 .msg_control = &control,
873 .msg_controllen = sizeof(control),
874 .msg_iovlen = 1,
875 };
876 ssize_t n;
fe1ef0f8 877 ssize_t l;
3c171f0b 878
fe1ef0f8
EV
879 l = next_datagram_size_fd(fd);
880 if (l < 0) {
881 r = log_error_errno(l, "Failed to determine datagram size to read: %m");
3c171f0b
LP
882 goto finish;
883 }
884
9a435388
FB
885 iovec.iov_len = l;
886 iovec.iov_base = malloc(l + 1);
887 if (!iovec.iov_base) {
3c171f0b
LP
888 r = log_oom();
889 goto finish;
890 }
891
9a435388 892 mh.msg_iov = &iovec;
3c171f0b 893
3691bcf3 894 n = recvmsg_safe(fd, &mh, MSG_CMSG_CLOEXEC);
3c171f0b 895 if (n < 0) {
9a435388 896 free(iovec.iov_base);
3691bcf3 897 r = log_error_errno(n, "Failed to receive datagram: %m");
3c171f0b
LP
898 goto finish;
899 }
900
9a435388
FB
901 /* The final zero-length datagram carries the file descriptor and tells us
902 * that we're done. */
3c171f0b 903 if (n == 0) {
dac556fa 904 struct cmsghdr *found;
3c171f0b 905
9a435388 906 free(iovec.iov_base);
3c171f0b 907
dac556fa 908 found = cmsg_find(&mh, SOL_SOCKET, SCM_RIGHTS, CMSG_LEN(sizeof(int)));
3c171f0b 909 if (!found) {
3691bcf3
LP
910 cmsg_close_all(&mh);
911 r = log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
912 "Coredump file descriptor missing.");
3c171f0b
LP
913 goto finish;
914 }
915
f8540bde
FB
916 assert(input_fd < 0);
917 input_fd = *(int*) CMSG_DATA(found);
3c171f0b 918 break;
3691bcf3
LP
919 } else
920 cmsg_close_all(&mh);
3c171f0b
LP
921
922 /* Add trailing NUL byte, in case these are strings */
9a435388
FB
923 ((char*) iovec.iov_base)[n] = 0;
924 iovec.iov_len = (size_t) n;
3c171f0b 925
9a435388
FB
926 r = iovw_put(&iovw, iovec.iov_base, iovec.iov_len);
927 if (r < 0)
928 goto finish;
34c10968
LP
929 }
930
61233823 931 /* Make sure we got all data we really need */
f8540bde 932 assert(input_fd >= 0);
3c171f0b 933
f46c706b
FB
934 r = save_context(&context, &iovw);
935 if (r < 0)
936 goto finish;
937
938 /* Make sure we received at least all fields we need. */
939 for (i = 0; i < _META_MANDATORY_MAX; i++)
940 if (!context.meta[i]) {
941 r = log_error_errno(SYNTHETIC_ERRNO(EINVAL),
942 "A mandatory argument (%i) has not been sent, aborting.",
943 i);
944 goto finish;
945 }
80002f66 946
f46c706b 947 r = submit_coredump(&context, &iovw, input_fd);
3c171f0b
LP
948
949finish:
9a435388 950 iovw_free_contents(&iovw, true);
3c171f0b
LP
951 return r;
952}
953
9a435388 954static int send_iovec(const struct iovec_wrapper *iovw, int input_fd) {
3c171f0b
LP
955
956 static const union sockaddr_union sa = {
957 .un.sun_family = AF_UNIX,
958 .un.sun_path = "/run/systemd/coredump",
959 };
960 _cleanup_close_ int fd = -1;
961 size_t i;
962 int r;
963
9a435388 964 assert(iovw);
3c171f0b
LP
965 assert(input_fd >= 0);
966
967 fd = socket(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0);
968 if (fd < 0)
969 return log_error_errno(errno, "Failed to create coredump socket: %m");
970
fc2fffe7 971 if (connect(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0)
3c171f0b
LP
972 return log_error_errno(errno, "Failed to connect to coredump service: %m");
973
9a435388 974 for (i = 0; i < iovw->count; i++) {
fec603eb 975 struct msghdr mh = {
9a435388 976 .msg_iov = iovw->iovec + i,
fec603eb
LP
977 .msg_iovlen = 1,
978 };
979 struct iovec copy[2];
980
981 for (;;) {
982 if (sendmsg(fd, &mh, MSG_NOSIGNAL) >= 0)
983 break;
984
985 if (errno == EMSGSIZE && mh.msg_iov[0].iov_len > 0) {
f46c706b
FB
986 /* This field didn't fit? That's a pity. Given that this is
987 * just metadata, let's truncate the field at half, and try
988 * again. We append three dots, in order to show that this is
989 * truncated. */
fec603eb
LP
990
991 if (mh.msg_iov != copy) {
f46c706b
FB
992 /* We don't want to modify the caller's iovec, hence
993 * let's create our own array, consisting of two new
994 * iovecs, where the first is a (truncated) copy of
995 * what we want to send, and the second one contains
996 * the trailing dots. */
9a435388 997 copy[0] = iovw->iovec[i];
ed0cb346 998 copy[1] = IOVEC_MAKE(((char[]){'.', '.', '.'}), 3);
fec603eb
LP
999
1000 mh.msg_iov = copy;
1001 mh.msg_iovlen = 2;
1002 }
1003
1004 copy[0].iov_len /= 2; /* halve it, and try again */
1005 continue;
1006 }
3c171f0b 1007
3c171f0b 1008 return log_error_errno(errno, "Failed to send coredump datagram: %m");
fec603eb 1009 }
1eef15b1
ZJS
1010 }
1011
3c171f0b
LP
1012 r = send_one_fd(fd, input_fd, 0);
1013 if (r < 0)
1014 return log_error_errno(r, "Failed to send coredump fd: %m");
1eef15b1 1015
3c171f0b
LP
1016 return 0;
1017}
1eef15b1 1018
64a5384f
LP
1019static int gather_pid_metadata_from_argv(
1020 struct iovec_wrapper *iovw,
1021 Context *context,
1022 int argc, char **argv) {
1023
f46c706b
FB
1024 _cleanup_free_ char *free_timestamp = NULL;
1025 int i, r, signo;
3c171f0b 1026 char *t;
3c171f0b 1027
f46c706b
FB
1028 /* We gather all metadata that were passed via argv[] into an array of iovecs that
1029 * we'll forward to the socket unit */
3c171f0b 1030
f46c706b
FB
1031 if (argc < _META_ARGV_MAX)
1032 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1033 "Not enough arguments passed by the kernel (%i, expected %i).",
1034 argc, _META_ARGV_MAX);
3c171f0b 1035
f46c706b 1036 for (i = 0; i < _META_ARGV_MAX; i++) {
3c171f0b 1037
f46c706b 1038 t = argv[i];
3c171f0b 1039
f46c706b 1040 switch (i) {
64a5384f 1041
f46c706b
FB
1042 case META_ARGV_TIMESTAMP:
1043 /* The journal fields contain the timestamp padded with six
1044 * zeroes, so that the kernel-supplied 1s granularity timestamps
1045 * becomes 1µs granularity, i.e. the granularity systemd usually
1046 * operates in. */
1047 t = free_timestamp = strjoin(argv[i], "000000");
1048 if (!t)
1049 return log_oom();
1050 break;
64a5384f 1051
f46c706b
FB
1052 case META_ARGV_SIGNAL:
1053 /* For signal, record its pretty name too */
1054 if (safe_atoi(argv[i], &signo) >= 0 && SIGNAL_VALID(signo))
2a3bebd0
FB
1055 (void) iovw_put_string_field(iovw, "COREDUMP_SIGNAL_NAME=SIG",
1056 signal_to_string(signo));
f46c706b 1057 break;
64a5384f 1058
f46c706b
FB
1059 default:
1060 break;
c8091d92
LP
1061 }
1062
f46c706b
FB
1063 r = iovw_put_string_field(iovw, meta_field_names[i], t);
1064 if (r < 0)
1065 return r;
8c8549db 1066 }
803a3464 1067
f46c706b
FB
1068 /* Cache some of the process metadata we collected so far and that we'll need to
1069 * access soon */
1070 return save_context(context, iovw);
1071}
3c171f0b 1072
f46c706b
FB
1073static int gather_pid_metadata(struct iovec_wrapper *iovw, Context *context) {
1074 uid_t owner_uid;
1075 pid_t pid;
1076 char *t;
1077 const char *p;
1078 int r;
f5e04665 1079
f46c706b
FB
1080 /* Note that if we fail on oom later on, we do not roll-back changes to the iovec
1081 * structure. (It remains valid, with the first iovec fields initialized.) */
f5e04665 1082
f46c706b 1083 pid = context->pid;
f5e04665 1084
f46c706b
FB
1085 /* The following is mandatory */
1086 r = get_process_comm(pid, &t);
9a435388 1087 if (r < 0)
f46c706b 1088 return log_error_errno(r, "Failed to get COMM: %m");
f5e04665 1089
f46c706b 1090 r = iovw_put_string_field_free(iovw, "COREDUMP_COMM=", t);
9a435388
FB
1091 if (r < 0)
1092 return r;
f45b8015 1093
f46c706b 1094 /* The following are optional but we used them if present */
2a3bebd0
FB
1095 r = get_process_exe(pid, &t);
1096 if (r >= 0)
1097 r = iovw_put_string_field_free(iovw, "COREDUMP_EXE=", t);
1098 if (r < 0)
f46c706b 1099 log_warning_errno(r, "Failed to get EXE, ignoring: %m");
bdfd7b2c 1100
f46c706b 1101 if (cg_pid_get_unit(pid, &t) >= 0)
2a3bebd0 1102 (void) iovw_put_string_field_free(iovw, "COREDUMP_UNIT=", t);
f5e04665 1103
9a435388 1104 /* The next are optional */
f46c706b 1105 if (cg_pid_get_user_unit(pid, &t) >= 0)
2a3bebd0 1106 (void) iovw_put_string_field_free(iovw, "COREDUMP_USER_UNIT=", t);
f46c706b 1107
9aa82023 1108 if (sd_pid_get_session(pid, &t) >= 0)
9a435388 1109 (void) iovw_put_string_field_free(iovw, "COREDUMP_SESSION=", t);
f5e04665 1110
a035f819 1111 if (sd_pid_get_owner_uid(pid, &owner_uid) >= 0) {
9a435388 1112 r = asprintf(&t, UID_FMT, owner_uid);
7de80bfe 1113 if (r > 0)
9a435388 1114 (void) iovw_put_string_field_free(iovw, "COREDUMP_OWNER_UID=", t);
f5e04665
LP
1115 }
1116
9aa82023 1117 if (sd_pid_get_slice(pid, &t) >= 0)
2a3bebd0 1118 (void) iovw_put_string_field_free(iovw, "COREDUMP_SLICE=", t);
f5e04665 1119
09c1dcee 1120 if (get_process_cmdline(pid, SIZE_MAX, 0, &t) >= 0)
2a3bebd0 1121 (void) iovw_put_string_field_free(iovw, "COREDUMP_CMDLINE=", t);
a035f819 1122
9aa82023 1123 if (cg_pid_get_path_shifted(pid, NULL, &t) >= 0)
2a3bebd0 1124 (void) iovw_put_string_field_free(iovw, "COREDUMP_CGROUP=", t);
a035f819 1125
9aa82023 1126 if (compose_open_fds(pid, &t) >= 0)
2a3bebd0 1127 (void) iovw_put_string_field_free(iovw, "COREDUMP_OPEN_FDS=", t);
3f132692
JF
1128
1129 p = procfs_file_alloca(pid, "status");
9aa82023 1130 if (read_full_file(p, &t, NULL) >= 0)
2a3bebd0 1131 (void) iovw_put_string_field_free(iovw, "COREDUMP_PROC_STATUS=", t);
3f132692
JF
1132
1133 p = procfs_file_alloca(pid, "maps");
9aa82023 1134 if (read_full_file(p, &t, NULL) >= 0)
2a3bebd0 1135 (void) iovw_put_string_field_free(iovw, "COREDUMP_PROC_MAPS=", t);
3f132692
JF
1136
1137 p = procfs_file_alloca(pid, "limits");
9aa82023 1138 if (read_full_file(p, &t, NULL) >= 0)
2a3bebd0 1139 (void) iovw_put_string_field_free(iovw, "COREDUMP_PROC_LIMITS=", t);
3f132692
JF
1140
1141 p = procfs_file_alloca(pid, "cgroup");
9aa82023 1142 if (read_full_file(p, &t, NULL) >=0)
2a3bebd0 1143 (void) iovw_put_string_field_free(iovw, "COREDUMP_PROC_CGROUP=", t);
3f132692 1144
d7032b1f 1145 p = procfs_file_alloca(pid, "mountinfo");
9aa82023 1146 if (read_full_file(p, &t, NULL) >=0)
2a3bebd0 1147 (void) iovw_put_string_field_free(iovw, "COREDUMP_PROC_MOUNTINFO=", t);
d7032b1f 1148
9aa82023 1149 if (get_process_cwd(pid, &t) >= 0)
2a3bebd0 1150 (void) iovw_put_string_field_free(iovw, "COREDUMP_CWD=", t);
3f132692
JF
1151
1152 if (get_process_root(pid, &t) >= 0) {
9aa82023
ZJS
1153 bool proc_self_root_is_slash;
1154
1155 proc_self_root_is_slash = strcmp(t, "/") == 0;
3f132692 1156
2a3bebd0 1157 (void) iovw_put_string_field_free(iovw, "COREDUMP_ROOT=", t);
7ed03ce6
JF
1158
1159 /* If the process' root is "/", then there is a chance it has
1160 * mounted own root and hence being containerized. */
9aa82023 1161 if (proc_self_root_is_slash && get_process_container_parent_cmdline(pid, &t) > 0)
2a3bebd0 1162 (void) iovw_put_string_field_free(iovw, "COREDUMP_CONTAINER_CMDLINE=", t);
3f132692
JF
1163 }
1164
9aa82023 1165 if (get_process_environ(pid, &t) >= 0)
2a3bebd0 1166 (void) iovw_put_string_field_free(iovw, "COREDUMP_ENVIRON=", t);
9aa82023 1167
f46c706b
FB
1168 /* we successfully acquired all metadata */
1169 return save_context(context, iovw);
9aa82023 1170}
3f132692 1171
9aa82023 1172static int process_kernel(int argc, char* argv[]) {
f46c706b 1173 Context context = {};
9a435388 1174 struct iovec_wrapper *iovw;
9aa82023
ZJS
1175 int r;
1176
988e89ee
ZJS
1177 log_debug("Processing coredump received from the kernel...");
1178
9a435388
FB
1179 iovw = iovw_new();
1180 if (!iovw)
1181 return log_oom();
1182
2a3bebd0
FB
1183 (void) iovw_put_string_field(iovw, "MESSAGE_ID=", SD_MESSAGE_COREDUMP_STR);
1184 (void) iovw_put_string_field(iovw, "PRIORITY=", STRINGIFY(LOG_CRIT));
f46c706b
FB
1185
1186 /* Collect all process metadata passed by the kernel through argv[] */
1187 r = gather_pid_metadata_from_argv(iovw, &context, argc - 1, argv + 1);
92e92d71 1188 if (r < 0)
86562420 1189 goto finish;
86562420 1190
f46c706b
FB
1191 /* Collect the rest of the process metadata retrieved from the runtime */
1192 r = gather_pid_metadata(iovw, &context);
1193 if (r < 0)
1194 goto finish;
1195
1196 if (!context.is_journald) {
1197 /* OK, now we know it's not the journal, hence we can make use of it now. */
1198 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
1199 log_open();
1200 }
1201
1202 /* If this is PID 1 disable coredump collection, we'll unlikely be able to process
1203 * it later on.
1204 *
1205 * FIXME: maybe we should disable coredumps generation from the beginning and
1206 * re-enable it only when we know it's either safe (ie we're not running OOM) or
1207 * it's not pid1 ? */
1208 if (context.is_pid1) {
1209 log_notice("Due to PID 1 having crashed coredump collection will now be turned off.");
1210 disable_coredumps();
1211 }
34c10968 1212
f46c706b
FB
1213 if (context.is_journald || context.is_pid1)
1214 r = submit_coredump(&context, iovw, STDIN_FILENO);
92e92d71 1215 else
9a435388 1216 r = send_iovec(iovw, STDIN_FILENO);
9aa82023
ZJS
1217
1218 finish:
9a435388 1219 iovw = iovw_free_free(iovw);
9aa82023 1220 return r;
3c171f0b 1221}
34c10968 1222
988e89ee 1223static int process_backtrace(int argc, char *argv[]) {
f46c706b 1224 Context context = {};
9a435388
FB
1225 struct iovec_wrapper *iovw;
1226 char *message;
1227 size_t i;
988e89ee 1228 int r;
11e6d971 1229 _cleanup_(journal_importer_cleanup) JournalImporter importer = JOURNAL_IMPORTER_INIT(STDIN_FILENO);
988e89ee
ZJS
1230
1231 log_debug("Processing backtrace on stdin...");
1232
9a435388
FB
1233 iovw = iovw_new();
1234 if (!iovw)
5b45a160
ZJS
1235 return log_oom();
1236
2a3bebd0
FB
1237 (void) iovw_put_string_field(iovw, "MESSAGE_ID=", SD_MESSAGE_BACKTRACE_STR);
1238 (void) iovw_put_string_field(iovw, "PRIORITY=", STRINGIFY(LOG_CRIT));
f46c706b
FB
1239
1240 /* Collect all process metadata from argv[] by making sure to skip the
1241 * '--backtrace' option */
1242 r = gather_pid_metadata_from_argv(iovw, &context, argc - 2, argv + 2);
988e89ee
ZJS
1243 if (r < 0)
1244 goto finish;
aaeb2522 1245
f46c706b
FB
1246 /* Collect the rest of the process metadata retrieved from the runtime */
1247 r = gather_pid_metadata(iovw, &context);
1248 if (r < 0)
1249 goto finish;
988e89ee 1250
86562420 1251 for (;;) {
5b45a160
ZJS
1252 r = journal_importer_process_data(&importer);
1253 if (r < 0) {
1254 log_error_errno(r, "Failed to parse journal entry on stdin: %m");
1255 goto finish;
1256 }
d74dc4f2
ZJS
1257 if (r == 1 || /* complete entry */
1258 journal_importer_eof(&importer)) /* end of data */
5b45a160 1259 break;
988e89ee 1260 }
988e89ee 1261
5b45a160
ZJS
1262 if (journal_importer_eof(&importer)) {
1263 log_warning("Did not receive a full journal entry on stdin, ignoring message sent by reporter");
988e89ee 1264
f46c706b
FB
1265 message = strjoina("Process ", context.meta[META_ARGV_PID],
1266 " (", context.meta[META_COMM], ")"
1267 " of user ", context.meta[META_ARGV_UID],
1268 " failed with ", context.meta[META_ARGV_SIGNAL]);
9a435388
FB
1269
1270 r = iovw_put_string_field(iovw, "MESSAGE=", message);
1271 if (r < 0)
1272 return r;
5b45a160 1273 } else {
9a435388
FB
1274 /* The imported iovecs are not supposed to be freed by us so let's store
1275 * them at the end of the array so we can skip them while freeing the
1276 * rest. */
9a435388
FB
1277 for (i = 0; i < importer.iovw.count; i++) {
1278 struct iovec *iovec = importer.iovw.iovec + i;
988e89ee 1279
9a435388
FB
1280 iovw_put(iovw, iovec->iov_base, iovec->iov_len);
1281 }
1282 }
988e89ee 1283
9a435388 1284 r = sd_journal_sendv(iovw->iovec, iovw->count);
988e89ee
ZJS
1285 if (r < 0)
1286 log_error_errno(r, "Failed to log backtrace: %m");
1287
1288 finish:
9a435388
FB
1289 iovw->count -= importer.iovw.count;
1290 iovw = iovw_free_free(iovw);
988e89ee
ZJS
1291 return r;
1292}
1293
4515a95e 1294static int run(int argc, char *argv[]) {
3c171f0b 1295 int r;
fee80f69 1296
9aa82023
ZJS
1297 /* First, log to a safe place, since we don't know what crashed and it might
1298 * be journald which we'd rather not log to then. */
8d4e028f 1299
3c171f0b
LP
1300 log_set_target(LOG_TARGET_KMSG);
1301 log_open();
8d4e028f 1302
3c171f0b
LP
1303 /* Make sure we never enter a loop */
1304 (void) prctl(PR_SET_DUMPABLE, 0);
8d4e028f 1305
3c171f0b
LP
1306 /* Ignore all parse errors */
1307 (void) parse_config();
fee80f69 1308
3c171f0b
LP
1309 log_debug("Selected storage '%s'.", coredump_storage_to_string(arg_storage));
1310 log_debug("Selected compression %s.", yes_no(arg_compress));
fee80f69 1311
3c171f0b 1312 r = sd_listen_fds(false);
4515a95e
ZJS
1313 if (r < 0)
1314 return log_error_errno(r, "Failed to determine the number of file descriptors: %m");
fee80f69 1315
9aa82023
ZJS
1316 /* If we got an fd passed, we are running in coredumpd mode. Otherwise we
1317 * are invoked from the kernel as coredump handler. */
988e89ee
ZJS
1318 if (r == 0) {
1319 if (streq_ptr(argv[1], "--backtrace"))
4515a95e 1320 return process_backtrace(argc, argv);
988e89ee 1321 else
4515a95e 1322 return process_kernel(argc, argv);
988e89ee 1323 } else if (r == 1)
4515a95e 1324 return process_socket(SD_LISTEN_FDS_START);
f5e04665 1325
baaa35ad
ZJS
1326 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1327 "Received unexpected number of file descriptors.");
f5e04665 1328}
4515a95e
ZJS
1329
1330DEFINE_MAIN_FUNCTION(run);