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