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