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