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