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