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