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