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