]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/coredump/coredump.c
tree-wide: use memstream-util
[thirdparty/systemd.git] / src / coredump / coredump.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <stdio.h>
5 #include <sys/prctl.h>
6 #include <sys/statvfs.h>
7 #include <sys/auxv.h>
8 #include <sys/xattr.h>
9 #include <unistd.h>
10
11 #include "sd-daemon.h"
12 #include "sd-journal.h"
13 #include "sd-login.h"
14 #include "sd-messages.h"
15
16 #include "acl-util.h"
17 #include "alloc-util.h"
18 #include "bus-error.h"
19 #include "capability-util.h"
20 #include "cgroup-util.h"
21 #include "compress.h"
22 #include "conf-parser.h"
23 #include "copy.h"
24 #include "coredump-util.h"
25 #include "coredump-vacuum.h"
26 #include "dirent-util.h"
27 #include "elf-util.h"
28 #include "escape.h"
29 #include "fd-util.h"
30 #include "fileio.h"
31 #include "fs-util.h"
32 #include "io-util.h"
33 #include "journal-importer.h"
34 #include "journal-send.h"
35 #include "log.h"
36 #include "macro.h"
37 #include "main-func.h"
38 #include "memory-util.h"
39 #include "memstream-util.h"
40 #include "mkdir-label.h"
41 #include "parse-util.h"
42 #include "process-util.h"
43 #include "signal-util.h"
44 #include "socket-util.h"
45 #include "special.h"
46 #include "stat-util.h"
47 #include "string-table.h"
48 #include "string-util.h"
49 #include "strv.h"
50 #include "sync-util.h"
51 #include "tmpfile-util.h"
52 #include "uid-alloc-range.h"
53 #include "user-util.h"
54
55 /* The maximum size up to which we process coredumps. We use 1G on 32bit systems, and 32G on 64bit systems */
56 #if __SIZEOF_POINTER__ == 4
57 #define PROCESS_SIZE_MAX ((uint64_t) (1LLU*1024LLU*1024LLU*1024LLU))
58 #elif __SIZEOF_POINTER__ == 8
59 #define PROCESS_SIZE_MAX ((uint64_t) (32LLU*1024LLU*1024LLU*1024LLU))
60 #else
61 #error "Unexpected pointer size"
62 #endif
63
64 /* The maximum size up to which we leave the coredump around on disk */
65 #define EXTERNAL_SIZE_MAX PROCESS_SIZE_MAX
66
67 /* The maximum size up to which we store the coredump in the journal */
68 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
69 #define JOURNAL_SIZE_MAX ((size_t) (767LU*1024LU*1024LU))
70 #else
71 /* oss-fuzz limits memory usage. */
72 #define JOURNAL_SIZE_MAX ((size_t) (10LU*1024LU*1024LU))
73 #endif
74
75 /* When checking for available memory and setting lower limits, don't
76 * go below 4MB for writing core files to storage. */
77 #define PROCESS_SIZE_MIN (4U*1024U*1024U)
78
79 /* Make sure to not make this larger than the maximum journal entry
80 * size. See DATA_SIZE_MAX in journal-importer.h. */
81 assert_cc(JOURNAL_SIZE_MAX <= DATA_SIZE_MAX);
82
83 enum {
84 /* We use these as array indexes for our process metadata cache.
85 *
86 * The first indices of the cache stores the same metadata as the ones passed by
87 * the kernel via argv[], ie the strings array passed by the kernel according to
88 * our pattern defined in /proc/sys/kernel/core_pattern (see man:core(5)). */
89
90 META_ARGV_PID, /* %P: as seen in the initial pid namespace */
91 META_ARGV_UID, /* %u: as seen in the initial user namespace */
92 META_ARGV_GID, /* %g: as seen in the initial user namespace */
93 META_ARGV_SIGNAL, /* %s: number of signal causing dump */
94 META_ARGV_TIMESTAMP, /* %t: time of dump, expressed as seconds since the Epoch (we expand this to µs granularity) */
95 META_ARGV_RLIMIT, /* %c: core file size soft resource limit */
96 META_ARGV_HOSTNAME, /* %h: hostname */
97 _META_ARGV_MAX,
98
99 /* The following indexes are cached for a couple of special fields we use (and
100 * thereby need to be retrieved quickly) for naming coredump files, and attaching
101 * xattrs. Unlike the previous ones they are retrieved from the runtime
102 * environment. */
103
104 META_COMM = _META_ARGV_MAX,
105 _META_MANDATORY_MAX,
106
107 /* The rest are similar to the previous ones except that we won't fail if one of
108 * them is missing. */
109
110 META_EXE = _META_MANDATORY_MAX,
111 META_UNIT,
112 META_PROC_AUXV,
113 _META_MAX
114 };
115
116 static const char * const meta_field_names[_META_MAX] = {
117 [META_ARGV_PID] = "COREDUMP_PID=",
118 [META_ARGV_UID] = "COREDUMP_UID=",
119 [META_ARGV_GID] = "COREDUMP_GID=",
120 [META_ARGV_SIGNAL] = "COREDUMP_SIGNAL=",
121 [META_ARGV_TIMESTAMP] = "COREDUMP_TIMESTAMP=",
122 [META_ARGV_RLIMIT] = "COREDUMP_RLIMIT=",
123 [META_ARGV_HOSTNAME] = "COREDUMP_HOSTNAME=",
124 [META_COMM] = "COREDUMP_COMM=",
125 [META_EXE] = "COREDUMP_EXE=",
126 [META_UNIT] = "COREDUMP_UNIT=",
127 [META_PROC_AUXV] = "COREDUMP_PROC_AUXV=",
128 };
129
130 typedef struct Context {
131 const char *meta[_META_MAX];
132 size_t meta_size[_META_MAX];
133 pid_t pid;
134 bool is_pid1;
135 bool is_journald;
136 } Context;
137
138 typedef enum CoredumpStorage {
139 COREDUMP_STORAGE_NONE,
140 COREDUMP_STORAGE_EXTERNAL,
141 COREDUMP_STORAGE_JOURNAL,
142 _COREDUMP_STORAGE_MAX,
143 _COREDUMP_STORAGE_INVALID = -EINVAL,
144 } CoredumpStorage;
145
146 static const char* const coredump_storage_table[_COREDUMP_STORAGE_MAX] = {
147 [COREDUMP_STORAGE_NONE] = "none",
148 [COREDUMP_STORAGE_EXTERNAL] = "external",
149 [COREDUMP_STORAGE_JOURNAL] = "journal",
150 };
151
152 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(coredump_storage, CoredumpStorage);
153 static DEFINE_CONFIG_PARSE_ENUM(config_parse_coredump_storage, coredump_storage, CoredumpStorage, "Failed to parse storage setting");
154
155 static CoredumpStorage arg_storage = COREDUMP_STORAGE_EXTERNAL;
156 static bool arg_compress = true;
157 static uint64_t arg_process_size_max = PROCESS_SIZE_MAX;
158 static uint64_t arg_external_size_max = EXTERNAL_SIZE_MAX;
159 static uint64_t arg_journal_size_max = JOURNAL_SIZE_MAX;
160 static uint64_t arg_keep_free = UINT64_MAX;
161 static uint64_t arg_max_use = UINT64_MAX;
162
163 static int parse_config(void) {
164 static const ConfigTableItem items[] = {
165 { "Coredump", "Storage", config_parse_coredump_storage, 0, &arg_storage },
166 { "Coredump", "Compress", config_parse_bool, 0, &arg_compress },
167 { "Coredump", "ProcessSizeMax", config_parse_iec_uint64, 0, &arg_process_size_max },
168 { "Coredump", "ExternalSizeMax", config_parse_iec_uint64_infinity, 0, &arg_external_size_max },
169 { "Coredump", "JournalSizeMax", config_parse_iec_size, 0, &arg_journal_size_max },
170 { "Coredump", "KeepFree", config_parse_iec_uint64, 0, &arg_keep_free },
171 { "Coredump", "MaxUse", config_parse_iec_uint64, 0, &arg_max_use },
172 {}
173 };
174
175 return config_parse_config_file("coredump.conf", "Coredump\0",
176 config_item_table_lookup, items,
177 CONFIG_PARSE_WARN, NULL);
178 }
179
180 static uint64_t storage_size_max(void) {
181 if (arg_storage == COREDUMP_STORAGE_EXTERNAL)
182 return arg_external_size_max;
183 if (arg_storage == COREDUMP_STORAGE_JOURNAL)
184 return arg_journal_size_max;
185 assert(arg_storage == COREDUMP_STORAGE_NONE);
186 return 0;
187 }
188
189 static int fix_acl(int fd, uid_t uid, bool allow_user) {
190 assert(fd >= 0);
191 assert(uid_is_valid(uid));
192
193 #if HAVE_ACL
194 int r;
195
196 /* We don't allow users to read coredumps if the uid or capabilities were changed. */
197 if (!allow_user)
198 return 0;
199
200 if (uid_is_system(uid) || uid_is_dynamic(uid) || uid == UID_NOBODY)
201 return 0;
202
203 /* Make sure normal users can read (but not write or delete) their own coredumps */
204 r = fd_add_uid_acl_permission(fd, uid, ACL_READ);
205 if (r < 0)
206 return log_error_errno(r, "Failed to adjust ACL of the coredump: %m");
207 #endif
208
209 return 0;
210 }
211
212 static int fix_xattr(int fd, const Context *context) {
213
214 static const char * const xattrs[_META_MAX] = {
215 [META_ARGV_PID] = "user.coredump.pid",
216 [META_ARGV_UID] = "user.coredump.uid",
217 [META_ARGV_GID] = "user.coredump.gid",
218 [META_ARGV_SIGNAL] = "user.coredump.signal",
219 [META_ARGV_TIMESTAMP] = "user.coredump.timestamp",
220 [META_ARGV_RLIMIT] = "user.coredump.rlimit",
221 [META_ARGV_HOSTNAME] = "user.coredump.hostname",
222 [META_COMM] = "user.coredump.comm",
223 [META_EXE] = "user.coredump.exe",
224 };
225
226 int r = 0;
227
228 assert(fd >= 0);
229
230 /* Attach some metadata to coredumps via extended
231 * attributes. Just because we can. */
232
233 for (unsigned i = 0; i < _META_MAX; i++) {
234 int k;
235
236 if (isempty(context->meta[i]) || !xattrs[i])
237 continue;
238
239 k = fsetxattr(fd, xattrs[i], context->meta[i], strlen(context->meta[i]), XATTR_CREATE);
240 if (k < 0 && r == 0)
241 r = -errno;
242 }
243
244 return r;
245 }
246
247 #define filename_escape(s) xescape((s), "./ ")
248
249 static const char *coredump_tmpfile_name(const char *s) {
250 return s ?: "(unnamed temporary file)";
251 }
252
253 static int fix_permissions(
254 int fd,
255 const char *filename,
256 const char *target,
257 const Context *context,
258 uid_t uid,
259 bool allow_user) {
260
261 int r;
262
263 assert(fd >= 0);
264 assert(target);
265 assert(context);
266
267 /* Ignore errors on these */
268 (void) fchmod(fd, 0640);
269 (void) fix_acl(fd, uid, allow_user);
270 (void) fix_xattr(fd, context);
271
272 r = fsync_full(fd);
273 if (r < 0)
274 return log_error_errno(r, "Failed to sync coredump %s: %m", coredump_tmpfile_name(filename));
275
276 r = link_tmpfile(fd, filename, target, /* replace= */ false);
277 if (r < 0)
278 return log_error_errno(r, "Failed to move coredump %s into place: %m", target);
279
280 return 0;
281 }
282
283 static int maybe_remove_external_coredump(const char *filename, uint64_t size) {
284
285 /* Returns 1 if might remove, 0 if will not remove, < 0 on error. */
286
287 if (arg_storage == COREDUMP_STORAGE_EXTERNAL &&
288 size <= arg_external_size_max)
289 return 0;
290
291 if (!filename)
292 return 1;
293
294 if (unlink(filename) < 0 && errno != ENOENT)
295 return log_error_errno(errno, "Failed to unlink %s: %m", filename);
296
297 return 1;
298 }
299
300 static int make_filename(const Context *context, char **ret) {
301 _cleanup_free_ char *c = NULL, *u = NULL, *p = NULL, *t = NULL;
302 sd_id128_t boot = {};
303 int r;
304
305 assert(context);
306
307 c = filename_escape(context->meta[META_COMM]);
308 if (!c)
309 return -ENOMEM;
310
311 u = filename_escape(context->meta[META_ARGV_UID]);
312 if (!u)
313 return -ENOMEM;
314
315 r = sd_id128_get_boot(&boot);
316 if (r < 0)
317 return r;
318
319 p = filename_escape(context->meta[META_ARGV_PID]);
320 if (!p)
321 return -ENOMEM;
322
323 t = filename_escape(context->meta[META_ARGV_TIMESTAMP]);
324 if (!t)
325 return -ENOMEM;
326
327 if (asprintf(ret,
328 "/var/lib/systemd/coredump/core.%s.%s." SD_ID128_FORMAT_STR ".%s.%s",
329 c,
330 u,
331 SD_ID128_FORMAT_VAL(boot),
332 p,
333 t) < 0)
334 return -ENOMEM;
335
336 return 0;
337 }
338
339 static int grant_user_access(int core_fd, const Context *context) {
340 int at_secure = -1;
341 uid_t uid = UID_INVALID, euid = UID_INVALID;
342 uid_t gid = GID_INVALID, egid = GID_INVALID;
343 int r;
344
345 assert(core_fd >= 0);
346 assert(context);
347
348 if (!context->meta[META_PROC_AUXV])
349 return log_warning_errno(SYNTHETIC_ERRNO(ENODATA), "No auxv data, not adjusting permissions.");
350
351 uint8_t elf[EI_NIDENT];
352 errno = 0;
353 if (pread(core_fd, &elf, sizeof(elf), 0) != sizeof(elf))
354 return log_warning_errno(errno_or_else(EIO),
355 "Failed to pread from coredump fd: %s", STRERROR_OR_EOF(errno));
356
357 if (elf[EI_MAG0] != ELFMAG0 ||
358 elf[EI_MAG1] != ELFMAG1 ||
359 elf[EI_MAG2] != ELFMAG2 ||
360 elf[EI_MAG3] != ELFMAG3 ||
361 elf[EI_VERSION] != EV_CURRENT)
362 return log_info_errno(SYNTHETIC_ERRNO(EUCLEAN),
363 "Core file does not have ELF header, not adjusting permissions.");
364 if (!IN_SET(elf[EI_CLASS], ELFCLASS32, ELFCLASS64) ||
365 !IN_SET(elf[EI_DATA], ELFDATA2LSB, ELFDATA2MSB))
366 return log_info_errno(SYNTHETIC_ERRNO(EUCLEAN),
367 "Core file has strange ELF class, not adjusting permissions.");
368
369 if ((elf[EI_DATA] == ELFDATA2LSB) != (__BYTE_ORDER == __LITTLE_ENDIAN))
370 return log_info_errno(SYNTHETIC_ERRNO(EUCLEAN),
371 "Core file has non-native endianness, not adjusting permissions.");
372
373 r = parse_auxv(LOG_WARNING,
374 /* elf_class= */ elf[EI_CLASS],
375 context->meta[META_PROC_AUXV],
376 context->meta_size[META_PROC_AUXV],
377 &at_secure, &uid, &euid, &gid, &egid);
378 if (r < 0)
379 return r;
380
381 /* We allow access if we got all the data and at_secure is not set and
382 * the uid/gid matches euid/egid. */
383 bool ret =
384 at_secure == 0 &&
385 uid != UID_INVALID && euid != UID_INVALID && uid == euid &&
386 gid != GID_INVALID && egid != GID_INVALID && gid == egid;
387 log_debug("Will %s access (uid="UID_FMT " euid="UID_FMT " gid="GID_FMT " egid="GID_FMT " at_secure=%s)",
388 ret ? "permit" : "restrict",
389 uid, euid, gid, egid, yes_no(at_secure));
390 return ret;
391 }
392
393 static int save_external_coredump(
394 const Context *context,
395 int input_fd,
396 char **ret_filename,
397 int *ret_node_fd,
398 int *ret_data_fd,
399 uint64_t *ret_size,
400 uint64_t *ret_compressed_size,
401 bool *ret_truncated) {
402
403 _cleanup_(unlink_and_freep) char *tmp = NULL;
404 _cleanup_free_ char *fn = NULL;
405 _cleanup_close_ int fd = -EBADF;
406 uint64_t rlimit, process_limit, max_size;
407 bool truncated, storage_on_tmpfs;
408 struct stat st;
409 uid_t uid;
410 int r;
411
412 assert(context);
413 assert(ret_filename);
414 assert(ret_node_fd);
415 assert(ret_data_fd);
416 assert(ret_size);
417 assert(ret_compressed_size);
418 assert(ret_truncated);
419
420 r = parse_uid(context->meta[META_ARGV_UID], &uid);
421 if (r < 0)
422 return log_error_errno(r, "Failed to parse UID: %m");
423
424 r = safe_atou64(context->meta[META_ARGV_RLIMIT], &rlimit);
425 if (r < 0)
426 return log_error_errno(r, "Failed to parse resource limit '%s': %m",
427 context->meta[META_ARGV_RLIMIT]);
428 if (rlimit < page_size())
429 /* Is coredumping disabled? Then don't bother saving/processing the
430 * coredump. Anything below PAGE_SIZE cannot give a readable coredump
431 * (the kernel uses ELF_EXEC_PAGESIZE which is not easily accessible, but
432 * is usually the same as PAGE_SIZE. */
433 return log_info_errno(SYNTHETIC_ERRNO(EBADSLT),
434 "Resource limits disable core dumping for process %s (%s).",
435 context->meta[META_ARGV_PID], context->meta[META_COMM]);
436
437 process_limit = MAX(arg_process_size_max, storage_size_max());
438 if (process_limit == 0)
439 return log_debug_errno(SYNTHETIC_ERRNO(EBADSLT),
440 "Limits for coredump processing and storage are both 0, not dumping core.");
441
442 /* Never store more than the process configured, or than we actually shall keep or process */
443 max_size = MIN(rlimit, process_limit);
444
445 r = make_filename(context, &fn);
446 if (r < 0)
447 return log_error_errno(r, "Failed to determine coredump file name: %m");
448
449 (void) mkdir_parents_label(fn, 0755);
450
451 fd = open_tmpfile_linkable(fn, O_RDWR|O_CLOEXEC, &tmp);
452 if (fd < 0)
453 return log_error_errno(fd, "Failed to create temporary file for coredump %s: %m", fn);
454
455 /* If storage is on tmpfs, the kernel oomd might kill us if there's MemoryMax set on
456 * the service or the slice it belongs to. This is common on low-resources systems,
457 * to avoid crashing processes to take away too many system resources.
458 * Check the cgroup settings, and set max_size to a bit less than half of the
459 * available memory left to the process.
460 * Then, attempt to write the core file uncompressed first - if the write gets
461 * interrupted, we know we won't be able to write it all, so instead compress what
462 * was written so far, delete the uncompressed truncated core, and then continue
463 * compressing from STDIN. Given the compressed core cannot be larger than the
464 * uncompressed one, and 1KB for metadata is accounted for in the calculation, we
465 * should be able to at least store the full compressed core file. */
466
467 storage_on_tmpfs = fd_is_temporary_fs(fd) > 0;
468 if (storage_on_tmpfs && arg_compress) {
469 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
470 uint64_t cgroup_limit = UINT64_MAX;
471 struct statvfs sv;
472
473 /* If we can't get the cgroup limit, just ignore it, but don't fail,
474 * try anyway with the config settings. */
475 r = sd_bus_default_system(&bus);
476 if (r < 0)
477 log_info_errno(r, "Failed to connect to system bus, skipping MemoryAvailable check: %m");
478 else {
479 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
480
481 r = sd_bus_get_property_trivial(
482 bus,
483 "org.freedesktop.systemd1",
484 "/org/freedesktop/systemd1/unit/self",
485 "org.freedesktop.systemd1.Service",
486 "MemoryAvailable",
487 &error,
488 't', &cgroup_limit);
489 if (r < 0)
490 log_warning_errno(r,
491 "Failed to query MemoryAvailable for current unit, "
492 "falling back to static config settings: %s",
493 bus_error_message(&error, r));
494 }
495
496 max_size = MIN(cgroup_limit, max_size);
497 max_size = LESS_BY(max_size, 1024U) / 2; /* Account for 1KB metadata overhead for compressing */
498 max_size = MAX(PROCESS_SIZE_MIN, max_size); /* Impose a lower minimum */
499
500 /* tmpfs might get full quickly, so check the available space too.
501 * But don't worry about errors here, failing to access the storage
502 * location will be better logged when writing to it. */
503 if (fstatvfs(fd, &sv) >= 0)
504 max_size = MIN((uint64_t)sv.f_frsize * (uint64_t)sv.f_bfree, max_size);
505
506 log_debug("Limiting core file size to %" PRIu64 " bytes due to cgroup memory limits.", max_size);
507 }
508
509 r = copy_bytes(input_fd, fd, max_size, 0);
510 if (r < 0)
511 return log_error_errno(r, "Cannot store coredump of %s (%s): %m",
512 context->meta[META_ARGV_PID], context->meta[META_COMM]);
513 truncated = r == 1;
514
515 bool allow_user = grant_user_access(fd, context) > 0;
516
517 #if HAVE_COMPRESSION
518 if (arg_compress) {
519 _cleanup_(unlink_and_freep) char *tmp_compressed = NULL;
520 _cleanup_free_ char *fn_compressed = NULL;
521 _cleanup_close_ int fd_compressed = -EBADF;
522 uint64_t uncompressed_size = 0;
523
524 if (lseek(fd, 0, SEEK_SET) == (off_t) -1)
525 return log_error_errno(errno, "Failed to seek on coredump %s: %m", fn);
526
527 fn_compressed = strjoin(fn, default_compression_extension());
528 if (!fn_compressed)
529 return log_oom();
530
531 fd_compressed = open_tmpfile_linkable(fn_compressed, O_RDWR|O_CLOEXEC, &tmp_compressed);
532 if (fd_compressed < 0)
533 return log_error_errno(fd_compressed, "Failed to create temporary file for coredump %s: %m", fn_compressed);
534
535 r = compress_stream(fd, fd_compressed, max_size, &uncompressed_size);
536 if (r < 0)
537 return log_error_errno(r, "Failed to compress %s: %m", coredump_tmpfile_name(tmp_compressed));
538
539 if (truncated && storage_on_tmpfs) {
540 uint64_t partial_uncompressed_size = 0;
541
542 /* Uncompressed write was truncated and we are writing to tmpfs: delete
543 * the uncompressed core, and compress the remaining part from STDIN. */
544
545 tmp = unlink_and_free(tmp);
546 fd = safe_close(fd);
547
548 r = compress_stream(input_fd, fd_compressed, max_size, &partial_uncompressed_size);
549 if (r < 0)
550 return log_error_errno(r, "Failed to compress %s: %m", coredump_tmpfile_name(tmp_compressed));
551 uncompressed_size += partial_uncompressed_size;
552 }
553
554 r = fix_permissions(fd_compressed, tmp_compressed, fn_compressed, context, uid, allow_user);
555 if (r < 0)
556 return r;
557
558 if (fstat(fd_compressed, &st) < 0)
559 return log_error_errno(errno,
560 "Failed to fstat core file %s: %m",
561 coredump_tmpfile_name(tmp_compressed));
562
563 *ret_filename = TAKE_PTR(fn_compressed); /* compressed */
564 *ret_node_fd = TAKE_FD(fd_compressed); /* compressed */
565 *ret_compressed_size = (uint64_t) st.st_size; /* compressed */
566 *ret_data_fd = TAKE_FD(fd);
567 *ret_size = uncompressed_size;
568 *ret_truncated = truncated;
569 tmp_compressed = mfree(tmp_compressed);
570
571 return 0;
572 }
573 #endif
574
575 if (truncated)
576 log_struct(LOG_INFO,
577 LOG_MESSAGE("Core file was truncated to %"PRIu64" bytes.", max_size),
578 "SIZE_LIMIT=%"PRIu64, max_size,
579 "MESSAGE_ID=" SD_MESSAGE_TRUNCATED_CORE_STR);
580
581 r = fix_permissions(fd, tmp, fn, context, uid, allow_user);
582 if (r < 0)
583 return log_error_errno(r, "Failed to fix permissions and finalize coredump %s into %s: %m", coredump_tmpfile_name(tmp), fn);
584
585 if (fstat(fd, &st) < 0)
586 return log_error_errno(errno, "Failed to fstat core file %s: %m", coredump_tmpfile_name(tmp));
587
588 if (lseek(fd, 0, SEEK_SET) == (off_t) -1)
589 return log_error_errno(errno, "Failed to seek on coredump %s: %m", fn);
590
591 *ret_filename = TAKE_PTR(fn);
592 *ret_data_fd = TAKE_FD(fd);
593 *ret_size = (uint64_t) st.st_size;
594 *ret_truncated = truncated;
595
596 return 0;
597 }
598
599 static int allocate_journal_field(int fd, size_t size, char **ret, size_t *ret_size) {
600 _cleanup_free_ char *field = NULL;
601 ssize_t n;
602
603 assert(fd >= 0);
604 assert(ret);
605 assert(ret_size);
606
607 if (lseek(fd, 0, SEEK_SET) == (off_t) -1)
608 return log_warning_errno(errno, "Failed to seek: %m");
609
610 field = malloc(9 + size);
611 if (!field) {
612 log_warning("Failed to allocate memory for coredump, coredump will not be stored.");
613 return -ENOMEM;
614 }
615
616 memcpy(field, "COREDUMP=", 9);
617
618 n = read(fd, field + 9, size);
619 if (n < 0)
620 return log_error_errno((int) n, "Failed to read core data: %m");
621 if ((size_t) n < size)
622 return log_error_errno(SYNTHETIC_ERRNO(EIO),
623 "Core data too short.");
624
625 *ret = TAKE_PTR(field);
626 *ret_size = size + 9;
627
628 return 0;
629 }
630
631 /* Joins /proc/[pid]/fd/ and /proc/[pid]/fdinfo/ into the following lines:
632 * 0:/dev/pts/23
633 * pos: 0
634 * flags: 0100002
635 *
636 * 1:/dev/pts/23
637 * pos: 0
638 * flags: 0100002
639 *
640 * 2:/dev/pts/23
641 * pos: 0
642 * flags: 0100002
643 * EOF
644 */
645 static int compose_open_fds(pid_t pid, char **ret) {
646 _cleanup_(memstream_done) MemStream m = {};
647 _cleanup_closedir_ DIR *proc_fd_dir = NULL;
648 _cleanup_close_ int proc_fdinfo_fd = -EBADF;
649 const char *fddelim = "", *path;
650 FILE *stream;
651 int r;
652
653 assert(pid >= 0);
654 assert(ret);
655
656 path = procfs_file_alloca(pid, "fd");
657 proc_fd_dir = opendir(path);
658 if (!proc_fd_dir)
659 return -errno;
660
661 proc_fdinfo_fd = openat(dirfd(proc_fd_dir), "../fdinfo", O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC|O_PATH);
662 if (proc_fdinfo_fd < 0)
663 return -errno;
664
665 stream = memstream_init(&m);
666 if (!stream)
667 return -ENOMEM;
668
669 FOREACH_DIRENT(de, proc_fd_dir, return -errno) {
670 _cleanup_fclose_ FILE *fdinfo = NULL;
671 _cleanup_free_ char *fdname = NULL;
672 _cleanup_close_ int fd = -EBADF;
673
674 r = readlinkat_malloc(dirfd(proc_fd_dir), de->d_name, &fdname);
675 if (r < 0)
676 return r;
677
678 fprintf(stream, "%s%s:%s\n", fddelim, de->d_name, fdname);
679 fddelim = "\n";
680
681 /* Use the directory entry from /proc/[pid]/fd with /proc/[pid]/fdinfo */
682 fd = openat(proc_fdinfo_fd, de->d_name, O_NOFOLLOW|O_CLOEXEC|O_RDONLY);
683 if (fd < 0)
684 continue;
685
686 fdinfo = take_fdopen(&fd, "r");
687 if (!fdinfo)
688 continue;
689
690 for (;;) {
691 _cleanup_free_ char *line = NULL;
692
693 r = read_line(fdinfo, LONG_LINE_MAX, &line);
694 if (r < 0)
695 return r;
696 if (r == 0)
697 break;
698
699 fputs(line, stream);
700 fputc('\n', stream);
701 }
702 }
703
704 return memstream_finalize(&m, ret, NULL);
705 }
706
707 static int get_process_ns(pid_t pid, const char *namespace, ino_t *ns) {
708 const char *p;
709 struct stat stbuf;
710 _cleanup_close_ int proc_ns_dir_fd = -EBADF;
711
712 p = procfs_file_alloca(pid, "ns");
713
714 proc_ns_dir_fd = open(p, O_DIRECTORY | O_CLOEXEC | O_RDONLY);
715 if (proc_ns_dir_fd < 0)
716 return -errno;
717
718 if (fstatat(proc_ns_dir_fd, namespace, &stbuf, /* flags */0) < 0)
719 return -errno;
720
721 *ns = stbuf.st_ino;
722 return 0;
723 }
724
725 static int get_mount_namespace_leader(pid_t pid, pid_t *ret) {
726 ino_t proc_mntns;
727 int r;
728
729 r = get_process_ns(pid, "mnt", &proc_mntns);
730 if (r < 0)
731 return r;
732
733 for (;;) {
734 ino_t parent_mntns;
735 pid_t ppid;
736
737 r = get_process_ppid(pid, &ppid);
738 if (r == -EADDRNOTAVAIL) /* Reached the top (i.e. typically PID 1, but could also be a process
739 * whose parent is not in our pidns) */
740 return -ENOENT;
741 if (r < 0)
742 return r;
743
744 r = get_process_ns(ppid, "mnt", &parent_mntns);
745 if (r < 0)
746 return r;
747
748 if (proc_mntns != parent_mntns) {
749 *ret = ppid;
750 return 0;
751 }
752
753 pid = ppid;
754 }
755 }
756
757 /* Returns 1 if the parent was found.
758 * Returns 0 if there is not a process we can call the pid's
759 * container parent (the pid's process isn't 'containerized').
760 * Returns a negative number on errors.
761 */
762 static int get_process_container_parent_cmdline(pid_t pid, char** cmdline) {
763 pid_t container_pid;
764 const char *proc_root_path;
765 struct stat root_stat, proc_root_stat;
766 int r;
767
768 /* To compare inodes of / and /proc/[pid]/root */
769 if (stat("/", &root_stat) < 0)
770 return -errno;
771
772 proc_root_path = procfs_file_alloca(pid, "root");
773 if (stat(proc_root_path, &proc_root_stat) < 0)
774 return -errno;
775
776 /* The process uses system root. */
777 if (stat_inode_same(&proc_root_stat, &root_stat)) {
778 *cmdline = NULL;
779 return 0;
780 }
781
782 r = get_mount_namespace_leader(pid, &container_pid);
783 if (r < 0)
784 return r;
785
786 r = get_process_cmdline(container_pid, SIZE_MAX, PROCESS_CMDLINE_QUOTE_POSIX, cmdline);
787 if (r < 0)
788 return r;
789
790 return 1;
791 }
792
793 static int change_uid_gid(const Context *context) {
794 uid_t uid;
795 gid_t gid;
796 int r;
797
798 r = parse_uid(context->meta[META_ARGV_UID], &uid);
799 if (r < 0)
800 return r;
801
802 if (uid_is_system(uid)) {
803 const char *user = "systemd-coredump";
804
805 r = get_user_creds(&user, &uid, &gid, NULL, NULL, 0);
806 if (r < 0) {
807 log_warning_errno(r, "Cannot resolve %s user. Proceeding to dump core as root: %m", user);
808 uid = gid = 0;
809 }
810 } else {
811 r = parse_gid(context->meta[META_ARGV_GID], &gid);
812 if (r < 0)
813 return r;
814 }
815
816 return drop_privileges(uid, gid, 0);
817 }
818
819 static int submit_coredump(
820 const Context *context,
821 struct iovec_wrapper *iovw,
822 int input_fd) {
823
824 _cleanup_(json_variant_unrefp) JsonVariant *json_metadata = NULL;
825 _cleanup_close_ int coredump_fd = -EBADF, coredump_node_fd = -EBADF;
826 _cleanup_free_ char *filename = NULL, *coredump_data = NULL;
827 _cleanup_free_ char *stacktrace = NULL;
828 char *core_message;
829 const char *module_name;
830 uint64_t coredump_size = UINT64_MAX, coredump_compressed_size = UINT64_MAX;
831 bool truncated = false;
832 JsonVariant *module_json;
833 int r;
834
835 assert(context);
836 assert(iovw);
837 assert(input_fd >= 0);
838
839 /* Vacuum before we write anything again */
840 (void) coredump_vacuum(-1, arg_keep_free, arg_max_use);
841
842 /* Always stream the coredump to disk, if that's possible */
843 r = save_external_coredump(context, input_fd,
844 &filename, &coredump_node_fd, &coredump_fd,
845 &coredump_size, &coredump_compressed_size, &truncated);
846 if (r < 0)
847 /* Skip whole core dumping part */
848 goto log;
849
850 /* If we don't want to keep the coredump on disk, remove it now, as later on we
851 * will lack the privileges for it. However, we keep the fd to it, so that we can
852 * still process it and log it. */
853 r = maybe_remove_external_coredump(filename, coredump_node_fd >= 0 ? coredump_compressed_size : coredump_size);
854 if (r < 0)
855 return r;
856 if (r == 0)
857 (void) iovw_put_string_field(iovw, "COREDUMP_FILENAME=", filename);
858 else if (arg_storage == COREDUMP_STORAGE_EXTERNAL)
859 log_info("The core will not be stored: size %"PRIu64" is greater than %"PRIu64" (the configured maximum)",
860 coredump_node_fd >= 0 ? coredump_compressed_size : coredump_size, arg_external_size_max);
861
862 /* Vacuum again, but exclude the coredump we just created */
863 (void) coredump_vacuum(coredump_node_fd >= 0 ? coredump_node_fd : coredump_fd, arg_keep_free, arg_max_use);
864
865 /* Now, let's drop privileges to become the user who owns the segfaulted process
866 * and allocate the coredump memory under the user's uid. This also ensures that
867 * the credentials journald will see are the ones of the coredumping user, thus
868 * making sure the user gets access to the core dump. Let's also get rid of all
869 * capabilities, if we run as root, we won't need them anymore. */
870 r = change_uid_gid(context);
871 if (r < 0)
872 return log_error_errno(r, "Failed to drop privileges: %m");
873
874 /* Try to get a stack trace if we can */
875 if (coredump_size > arg_process_size_max)
876 log_debug("Not generating stack trace: core size %"PRIu64" is greater "
877 "than %"PRIu64" (the configured maximum)",
878 coredump_size, arg_process_size_max);
879 else if (coredump_fd >= 0) {
880 bool skip = startswith(context->meta[META_COMM], "systemd-coredum"); /* COMM is 16 bytes usually */
881
882 (void) parse_elf_object(coredump_fd,
883 context->meta[META_EXE],
884 /* fork_disable_dump= */ skip, /* avoid loops */
885 &stacktrace,
886 &json_metadata);
887 }
888
889 log:
890 core_message = strjoina("Process ", context->meta[META_ARGV_PID],
891 " (", context->meta[META_COMM], ") of user ",
892 context->meta[META_ARGV_UID], " dumped core.",
893 context->is_journald && filename ? "\nCoredump diverted to " : NULL,
894 context->is_journald && filename ? filename : NULL);
895
896 core_message = strjoina(core_message, stacktrace ? "\n\n" : NULL, stacktrace);
897
898 if (context->is_journald)
899 /* We might not be able to log to the journal, so let's always print the message to another
900 * log target. The target was set previously to something safe. */
901 log_dispatch(LOG_ERR, 0, core_message);
902
903 (void) iovw_put_string_field(iovw, "MESSAGE=", core_message);
904
905 if (truncated)
906 (void) iovw_put_string_field(iovw, "COREDUMP_TRUNCATED=", "1");
907
908 /* If we managed to parse any ELF metadata (build-id, ELF package meta),
909 * attach it as journal metadata. */
910 if (json_metadata) {
911 _cleanup_free_ char *formatted_json = NULL;
912
913 r = json_variant_format(json_metadata, 0, &formatted_json);
914 if (r < 0)
915 return log_error_errno(r, "Failed to format JSON package metadata: %m");
916
917 (void) iovw_put_string_field(iovw, "COREDUMP_PACKAGE_JSON=", formatted_json);
918 }
919
920 /* In the unlikely scenario that context->meta[META_EXE] is not available,
921 * let's avoid guessing the module name and skip the loop. */
922 if (context->meta[META_EXE])
923 JSON_VARIANT_OBJECT_FOREACH(module_name, module_json, json_metadata) {
924 JsonVariant *t;
925
926 /* We only add structured fields for the 'main' ELF module, and only if we can identify it. */
927 if (!path_equal_filename(module_name, context->meta[META_EXE]))
928 continue;
929
930 t = json_variant_by_key(module_json, "name");
931 if (t)
932 (void) iovw_put_string_field(iovw, "COREDUMP_PACKAGE_NAME=", json_variant_string(t));
933
934 t = json_variant_by_key(module_json, "version");
935 if (t)
936 (void) iovw_put_string_field(iovw, "COREDUMP_PACKAGE_VERSION=", json_variant_string(t));
937 }
938
939 /* Optionally store the entire coredump in the journal */
940 if (arg_storage == COREDUMP_STORAGE_JOURNAL && coredump_fd >= 0) {
941 if (coredump_size <= arg_journal_size_max) {
942 size_t sz = 0;
943
944 /* Store the coredump itself in the journal */
945
946 r = allocate_journal_field(coredump_fd, (size_t) coredump_size, &coredump_data, &sz);
947 if (r >= 0) {
948 if (iovw_put(iovw, coredump_data, sz) >= 0)
949 TAKE_PTR(coredump_data);
950 } else
951 log_warning_errno(r, "Failed to attach the core to the journal entry: %m");
952 } else
953 log_info("The core will not be stored: size %"PRIu64" is greater than %"PRIu64" (the configured maximum)",
954 coredump_size, arg_journal_size_max);
955 }
956
957 /* If journald is coredumping, we have to be careful that we don't deadlock when trying to write the
958 * coredump to the journal, so we put the journal socket in nonblocking mode before trying to write
959 * the coredump to the socket. */
960
961 if (context->is_journald) {
962 r = journal_fd_nonblock(true);
963 if (r < 0)
964 return log_error_errno(r, "Failed to make journal socket non-blocking: %m");
965 }
966
967 r = sd_journal_sendv(iovw->iovec, iovw->count);
968
969 if (context->is_journald) {
970 int k;
971
972 k = journal_fd_nonblock(false);
973 if (k < 0)
974 return log_error_errno(k, "Failed to make journal socket blocking: %m");
975 }
976
977 if (r == -EAGAIN && context->is_journald)
978 log_warning_errno(r, "Failed to log journal coredump, ignoring: %m");
979 else if (r < 0)
980 return log_error_errno(r, "Failed to log coredump: %m");
981
982 return 0;
983 }
984
985 static int save_context(Context *context, const struct iovec_wrapper *iovw) {
986 const char *unit;
987 int r;
988
989 assert(context);
990 assert(iovw);
991 assert(iovw->count >= _META_ARGV_MAX);
992
993 /* The context does not allocate any memory on its own */
994
995 for (size_t n = 0; n < iovw->count; n++) {
996 struct iovec *iovec = iovw->iovec + n;
997
998 for (size_t i = 0; i < ELEMENTSOF(meta_field_names); i++) {
999 /* Note that these strings are NUL terminated, because we made sure that a
1000 * trailing NUL byte is in the buffer, though not included in the iov_len
1001 * count (see process_socket() and gather_pid_metadata_*()) */
1002 assert(((char*) iovec->iov_base)[iovec->iov_len] == 0);
1003
1004 const char *p = startswith(iovec->iov_base, meta_field_names[i]);
1005 if (p) {
1006 context->meta[i] = p;
1007 context->meta_size[i] = iovec->iov_len - strlen(meta_field_names[i]);
1008 break;
1009 }
1010 }
1011 }
1012
1013 if (!context->meta[META_ARGV_PID])
1014 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1015 "Failed to find the PID of crashing process");
1016
1017 r = parse_pid(context->meta[META_ARGV_PID], &context->pid);
1018 if (r < 0)
1019 return log_error_errno(r, "Failed to parse PID \"%s\": %m", context->meta[META_ARGV_PID]);
1020
1021 unit = context->meta[META_UNIT];
1022 context->is_pid1 = streq(context->meta[META_ARGV_PID], "1") || streq_ptr(unit, SPECIAL_INIT_SCOPE);
1023 context->is_journald = streq_ptr(unit, SPECIAL_JOURNALD_SERVICE);
1024
1025 return 0;
1026 }
1027
1028 static int process_socket(int fd) {
1029 _cleanup_close_ int input_fd = -EBADF;
1030 Context context = {};
1031 struct iovec_wrapper iovw = {};
1032 struct iovec iovec;
1033 int r;
1034
1035 assert(fd >= 0);
1036
1037 log_setup();
1038
1039 log_debug("Processing coredump received on stdin...");
1040
1041 for (;;) {
1042 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control;
1043 struct msghdr mh = {
1044 .msg_control = &control,
1045 .msg_controllen = sizeof(control),
1046 .msg_iovlen = 1,
1047 };
1048 ssize_t n;
1049 ssize_t l;
1050
1051 l = next_datagram_size_fd(fd);
1052 if (l < 0) {
1053 r = log_error_errno(l, "Failed to determine datagram size to read: %m");
1054 goto finish;
1055 }
1056
1057 iovec.iov_len = l;
1058 iovec.iov_base = malloc(l + 1);
1059 if (!iovec.iov_base) {
1060 r = log_oom();
1061 goto finish;
1062 }
1063
1064 mh.msg_iov = &iovec;
1065
1066 n = recvmsg_safe(fd, &mh, MSG_CMSG_CLOEXEC);
1067 if (n < 0) {
1068 free(iovec.iov_base);
1069 r = log_error_errno(n, "Failed to receive datagram: %m");
1070 goto finish;
1071 }
1072
1073 /* The final zero-length datagram carries the file descriptor and tells us
1074 * that we're done. */
1075 if (n == 0) {
1076 struct cmsghdr *found;
1077
1078 free(iovec.iov_base);
1079
1080 found = cmsg_find(&mh, SOL_SOCKET, SCM_RIGHTS, CMSG_LEN(sizeof(int)));
1081 if (!found) {
1082 cmsg_close_all(&mh);
1083 r = log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
1084 "Coredump file descriptor missing.");
1085 goto finish;
1086 }
1087
1088 assert(input_fd < 0);
1089 input_fd = *CMSG_TYPED_DATA(found, int);
1090 break;
1091 } else
1092 cmsg_close_all(&mh);
1093
1094 /* Add trailing NUL byte, in case these are strings */
1095 ((char*) iovec.iov_base)[n] = 0;
1096 iovec.iov_len = (size_t) n;
1097
1098 r = iovw_put(&iovw, iovec.iov_base, iovec.iov_len);
1099 if (r < 0)
1100 goto finish;
1101 }
1102
1103 /* Make sure we got all data we really need */
1104 assert(input_fd >= 0);
1105
1106 r = save_context(&context, &iovw);
1107 if (r < 0)
1108 goto finish;
1109
1110 /* Make sure we received at least all fields we need. */
1111 for (int i = 0; i < _META_MANDATORY_MAX; i++)
1112 if (!context.meta[i]) {
1113 r = log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1114 "A mandatory argument (%i) has not been sent, aborting.",
1115 i);
1116 goto finish;
1117 }
1118
1119 r = submit_coredump(&context, &iovw, input_fd);
1120
1121 finish:
1122 iovw_free_contents(&iovw, true);
1123 return r;
1124 }
1125
1126 static int send_iovec(const struct iovec_wrapper *iovw, int input_fd) {
1127 _cleanup_close_ int fd = -EBADF;
1128 int r;
1129
1130 assert(iovw);
1131 assert(input_fd >= 0);
1132
1133 fd = socket(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0);
1134 if (fd < 0)
1135 return log_error_errno(errno, "Failed to create coredump socket: %m");
1136
1137 r = connect_unix_path(fd, AT_FDCWD, "/run/systemd/coredump");
1138 if (r < 0)
1139 return log_error_errno(r, "Failed to connect to coredump service: %m");
1140
1141 for (size_t i = 0; i < iovw->count; i++) {
1142 struct msghdr mh = {
1143 .msg_iov = iovw->iovec + i,
1144 .msg_iovlen = 1,
1145 };
1146 struct iovec copy[2];
1147
1148 for (;;) {
1149 if (sendmsg(fd, &mh, MSG_NOSIGNAL) >= 0)
1150 break;
1151
1152 if (errno == EMSGSIZE && mh.msg_iov[0].iov_len > 0) {
1153 /* This field didn't fit? That's a pity. Given that this is
1154 * just metadata, let's truncate the field at half, and try
1155 * again. We append three dots, in order to show that this is
1156 * truncated. */
1157
1158 if (mh.msg_iov != copy) {
1159 /* We don't want to modify the caller's iovec, hence
1160 * let's create our own array, consisting of two new
1161 * iovecs, where the first is a (truncated) copy of
1162 * what we want to send, and the second one contains
1163 * the trailing dots. */
1164 copy[0] = iovw->iovec[i];
1165 copy[1] = IOVEC_MAKE(((char[]){'.', '.', '.'}), 3);
1166
1167 mh.msg_iov = copy;
1168 mh.msg_iovlen = 2;
1169 }
1170
1171 copy[0].iov_len /= 2; /* halve it, and try again */
1172 continue;
1173 }
1174
1175 return log_error_errno(errno, "Failed to send coredump datagram: %m");
1176 }
1177 }
1178
1179 r = send_one_fd(fd, input_fd, 0);
1180 if (r < 0)
1181 return log_error_errno(r, "Failed to send coredump fd: %m");
1182
1183 return 0;
1184 }
1185
1186 static int gather_pid_metadata_from_argv(
1187 struct iovec_wrapper *iovw,
1188 Context *context,
1189 int argc, char **argv) {
1190
1191 _cleanup_free_ char *free_timestamp = NULL;
1192 int r, signo;
1193 char *t;
1194
1195 /* We gather all metadata that were passed via argv[] into an array of iovecs that
1196 * we'll forward to the socket unit */
1197
1198 if (argc < _META_ARGV_MAX)
1199 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1200 "Not enough arguments passed by the kernel (%i, expected %i).",
1201 argc, _META_ARGV_MAX);
1202
1203 for (int i = 0; i < _META_ARGV_MAX; i++) {
1204
1205 t = argv[i];
1206
1207 switch (i) {
1208
1209 case META_ARGV_TIMESTAMP:
1210 /* The journal fields contain the timestamp padded with six
1211 * zeroes, so that the kernel-supplied 1s granularity timestamps
1212 * becomes 1µs granularity, i.e. the granularity systemd usually
1213 * operates in. */
1214 t = free_timestamp = strjoin(argv[i], "000000");
1215 if (!t)
1216 return log_oom();
1217 break;
1218
1219 case META_ARGV_SIGNAL:
1220 /* For signal, record its pretty name too */
1221 if (safe_atoi(argv[i], &signo) >= 0 && SIGNAL_VALID(signo))
1222 (void) iovw_put_string_field(iovw, "COREDUMP_SIGNAL_NAME=SIG",
1223 signal_to_string(signo));
1224 break;
1225
1226 default:
1227 break;
1228 }
1229
1230 r = iovw_put_string_field(iovw, meta_field_names[i], t);
1231 if (r < 0)
1232 return r;
1233 }
1234
1235 /* Cache some of the process metadata we collected so far and that we'll need to
1236 * access soon */
1237 return save_context(context, iovw);
1238 }
1239
1240 static int gather_pid_metadata(struct iovec_wrapper *iovw, Context *context) {
1241 uid_t owner_uid;
1242 pid_t pid;
1243 char *t;
1244 size_t size;
1245 const char *p;
1246 int r;
1247
1248 /* Note that if we fail on oom later on, we do not roll-back changes to the iovec
1249 * structure. (It remains valid, with the first iovec fields initialized.) */
1250
1251 pid = context->pid;
1252
1253 /* The following is mandatory */
1254 r = get_process_comm(pid, &t);
1255 if (r < 0)
1256 return log_error_errno(r, "Failed to get COMM: %m");
1257
1258 r = iovw_put_string_field_free(iovw, "COREDUMP_COMM=", t);
1259 if (r < 0)
1260 return r;
1261
1262 /* The following are optional, but we use them if present. */
1263 r = get_process_exe(pid, &t);
1264 if (r >= 0)
1265 r = iovw_put_string_field_free(iovw, "COREDUMP_EXE=", t);
1266 if (r < 0)
1267 log_warning_errno(r, "Failed to get EXE, ignoring: %m");
1268
1269 if (cg_pid_get_unit(pid, &t) >= 0)
1270 (void) iovw_put_string_field_free(iovw, "COREDUMP_UNIT=", t);
1271
1272 if (cg_pid_get_user_unit(pid, &t) >= 0)
1273 (void) iovw_put_string_field_free(iovw, "COREDUMP_USER_UNIT=", t);
1274
1275 if (sd_pid_get_session(pid, &t) >= 0)
1276 (void) iovw_put_string_field_free(iovw, "COREDUMP_SESSION=", t);
1277
1278 if (sd_pid_get_owner_uid(pid, &owner_uid) >= 0) {
1279 r = asprintf(&t, UID_FMT, owner_uid);
1280 if (r > 0)
1281 (void) iovw_put_string_field_free(iovw, "COREDUMP_OWNER_UID=", t);
1282 }
1283
1284 if (sd_pid_get_slice(pid, &t) >= 0)
1285 (void) iovw_put_string_field_free(iovw, "COREDUMP_SLICE=", t);
1286
1287 if (get_process_cmdline(pid, SIZE_MAX, PROCESS_CMDLINE_QUOTE_POSIX, &t) >= 0)
1288 (void) iovw_put_string_field_free(iovw, "COREDUMP_CMDLINE=", t);
1289
1290 if (cg_pid_get_path_shifted(pid, NULL, &t) >= 0)
1291 (void) iovw_put_string_field_free(iovw, "COREDUMP_CGROUP=", t);
1292
1293 if (compose_open_fds(pid, &t) >= 0)
1294 (void) iovw_put_string_field_free(iovw, "COREDUMP_OPEN_FDS=", t);
1295
1296 p = procfs_file_alloca(pid, "status");
1297 if (read_full_virtual_file(p, &t, NULL) >= 0)
1298 (void) iovw_put_string_field_free(iovw, "COREDUMP_PROC_STATUS=", t);
1299
1300 p = procfs_file_alloca(pid, "maps");
1301 if (read_full_virtual_file(p, &t, NULL) >= 0)
1302 (void) iovw_put_string_field_free(iovw, "COREDUMP_PROC_MAPS=", t);
1303
1304 p = procfs_file_alloca(pid, "limits");
1305 if (read_full_virtual_file(p, &t, NULL) >= 0)
1306 (void) iovw_put_string_field_free(iovw, "COREDUMP_PROC_LIMITS=", t);
1307
1308 p = procfs_file_alloca(pid, "cgroup");
1309 if (read_full_virtual_file(p, &t, NULL) >= 0)
1310 (void) iovw_put_string_field_free(iovw, "COREDUMP_PROC_CGROUP=", t);
1311
1312 p = procfs_file_alloca(pid, "mountinfo");
1313 if (read_full_virtual_file(p, &t, NULL) >= 0)
1314 (void) iovw_put_string_field_free(iovw, "COREDUMP_PROC_MOUNTINFO=", t);
1315
1316 /* We attach /proc/auxv here. ELF coredumps also contain a note for this (NT_AUXV), see elf(5). */
1317 p = procfs_file_alloca(pid, "auxv");
1318 if (read_full_virtual_file(p, &t, &size) >= 0) {
1319 char *buf = malloc(strlen("COREDUMP_PROC_AUXV=") + size + 1);
1320 if (buf) {
1321 /* Add a dummy terminator to make save_context() happy. */
1322 *((uint8_t*) mempcpy(stpcpy(buf, "COREDUMP_PROC_AUXV="), t, size)) = '\0';
1323 (void) iovw_consume(iovw, buf, size + strlen("COREDUMP_PROC_AUXV="));
1324 }
1325
1326 free(t);
1327 }
1328
1329 if (get_process_cwd(pid, &t) >= 0)
1330 (void) iovw_put_string_field_free(iovw, "COREDUMP_CWD=", t);
1331
1332 if (get_process_root(pid, &t) >= 0) {
1333 bool proc_self_root_is_slash;
1334
1335 proc_self_root_is_slash = strcmp(t, "/") == 0;
1336
1337 (void) iovw_put_string_field_free(iovw, "COREDUMP_ROOT=", t);
1338
1339 /* If the process' root is "/", then there is a chance it has
1340 * mounted own root and hence being containerized. */
1341 if (proc_self_root_is_slash && get_process_container_parent_cmdline(pid, &t) > 0)
1342 (void) iovw_put_string_field_free(iovw, "COREDUMP_CONTAINER_CMDLINE=", t);
1343 }
1344
1345 if (get_process_environ(pid, &t) >= 0)
1346 (void) iovw_put_string_field_free(iovw, "COREDUMP_ENVIRON=", t);
1347
1348 /* we successfully acquired all metadata */
1349 return save_context(context, iovw);
1350 }
1351
1352 static int process_kernel(int argc, char* argv[]) {
1353 Context context = {};
1354 struct iovec_wrapper *iovw;
1355 int r;
1356
1357 /* When we're invoked by the kernel, stdout/stderr are closed which is dangerous because the fds
1358 * could get reallocated. To avoid hard to debug issues, let's instead bind stdout/stderr to
1359 * /dev/null. */
1360 r = rearrange_stdio(STDIN_FILENO, -EBADF, -EBADF);
1361 if (r < 0)
1362 return log_error_errno(r, "Failed to connect stdout/stderr to /dev/null: %m");
1363
1364 log_debug("Processing coredump received from the kernel...");
1365
1366 iovw = iovw_new();
1367 if (!iovw)
1368 return log_oom();
1369
1370 (void) iovw_put_string_field(iovw, "MESSAGE_ID=", SD_MESSAGE_COREDUMP_STR);
1371 (void) iovw_put_string_field(iovw, "PRIORITY=", STRINGIFY(LOG_CRIT));
1372
1373 /* Collect all process metadata passed by the kernel through argv[] */
1374 r = gather_pid_metadata_from_argv(iovw, &context, argc - 1, argv + 1);
1375 if (r < 0)
1376 goto finish;
1377
1378 /* Collect the rest of the process metadata retrieved from the runtime */
1379 r = gather_pid_metadata(iovw, &context);
1380 if (r < 0)
1381 goto finish;
1382
1383 if (!context.is_journald)
1384 /* OK, now we know it's not the journal, hence we can make use of it now. */
1385 log_set_target_and_open(LOG_TARGET_JOURNAL_OR_KMSG);
1386
1387 /* If this is PID 1 disable coredump collection, we'll unlikely be able to process
1388 * it later on.
1389 *
1390 * FIXME: maybe we should disable coredumps generation from the beginning and
1391 * re-enable it only when we know it's either safe (ie we're not running OOM) or
1392 * it's not pid1 ? */
1393 if (context.is_pid1) {
1394 log_notice("Due to PID 1 having crashed coredump collection will now be turned off.");
1395 disable_coredumps();
1396 }
1397
1398 if (context.is_journald || context.is_pid1)
1399 r = submit_coredump(&context, iovw, STDIN_FILENO);
1400 else
1401 r = send_iovec(iovw, STDIN_FILENO);
1402
1403 finish:
1404 iovw = iovw_free_free(iovw);
1405 return r;
1406 }
1407
1408 static int process_backtrace(int argc, char *argv[]) {
1409 Context context = {};
1410 struct iovec_wrapper *iovw;
1411 char *message;
1412 int r;
1413 _cleanup_(journal_importer_cleanup) JournalImporter importer = JOURNAL_IMPORTER_INIT(STDIN_FILENO);
1414
1415 log_debug("Processing backtrace on stdin...");
1416
1417 iovw = iovw_new();
1418 if (!iovw)
1419 return log_oom();
1420
1421 (void) iovw_put_string_field(iovw, "MESSAGE_ID=", SD_MESSAGE_BACKTRACE_STR);
1422 (void) iovw_put_string_field(iovw, "PRIORITY=", STRINGIFY(LOG_CRIT));
1423
1424 /* Collect all process metadata from argv[] by making sure to skip the
1425 * '--backtrace' option */
1426 r = gather_pid_metadata_from_argv(iovw, &context, argc - 2, argv + 2);
1427 if (r < 0)
1428 goto finish;
1429
1430 /* Collect the rest of the process metadata retrieved from the runtime */
1431 r = gather_pid_metadata(iovw, &context);
1432 if (r < 0)
1433 goto finish;
1434
1435 for (;;) {
1436 r = journal_importer_process_data(&importer);
1437 if (r < 0) {
1438 log_error_errno(r, "Failed to parse journal entry on stdin: %m");
1439 goto finish;
1440 }
1441 if (r == 1 || /* complete entry */
1442 journal_importer_eof(&importer)) /* end of data */
1443 break;
1444 }
1445
1446 if (journal_importer_eof(&importer)) {
1447 log_warning("Did not receive a full journal entry on stdin, ignoring message sent by reporter");
1448
1449 message = strjoina("Process ", context.meta[META_ARGV_PID],
1450 " (", context.meta[META_COMM], ")"
1451 " of user ", context.meta[META_ARGV_UID],
1452 " failed with ", context.meta[META_ARGV_SIGNAL]);
1453
1454 r = iovw_put_string_field(iovw, "MESSAGE=", message);
1455 if (r < 0)
1456 return r;
1457 } else {
1458 /* The imported iovecs are not supposed to be freed by us so let's store
1459 * them at the end of the array so we can skip them while freeing the
1460 * rest. */
1461 for (size_t i = 0; i < importer.iovw.count; i++) {
1462 struct iovec *iovec = importer.iovw.iovec + i;
1463
1464 iovw_put(iovw, iovec->iov_base, iovec->iov_len);
1465 }
1466 }
1467
1468 r = sd_journal_sendv(iovw->iovec, iovw->count);
1469 if (r < 0)
1470 log_error_errno(r, "Failed to log backtrace: %m");
1471
1472 finish:
1473 iovw->count -= importer.iovw.count;
1474 iovw = iovw_free_free(iovw);
1475 return r;
1476 }
1477
1478 static int run(int argc, char *argv[]) {
1479 int r;
1480
1481 /* First, log to a safe place, since we don't know what crashed and it might
1482 * be journald which we'd rather not log to then. */
1483
1484 log_set_target_and_open(LOG_TARGET_KMSG);
1485
1486 /* Make sure we never enter a loop */
1487 (void) prctl(PR_SET_DUMPABLE, 0);
1488
1489 /* Ignore all parse errors */
1490 (void) parse_config();
1491
1492 log_debug("Selected storage '%s'.", coredump_storage_to_string(arg_storage));
1493 log_debug("Selected compression %s.", yes_no(arg_compress));
1494
1495 r = sd_listen_fds(false);
1496 if (r < 0)
1497 return log_error_errno(r, "Failed to determine the number of file descriptors: %m");
1498
1499 /* If we got an fd passed, we are running in coredumpd mode. Otherwise we
1500 * are invoked from the kernel as coredump handler. */
1501 if (r == 0) {
1502 if (streq_ptr(argv[1], "--backtrace"))
1503 return process_backtrace(argc, argv);
1504 else
1505 return process_kernel(argc, argv);
1506 } else if (r == 1)
1507 return process_socket(SD_LISTEN_FDS_START);
1508
1509 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1510 "Received unexpected number of file descriptors.");
1511 }
1512
1513 DEFINE_MAIN_FUNCTION(run);