]> git.ipfire.org Git - thirdparty/systemd.git/blame_incremental - src/coredump/coredump.c
core: use an AF_UNIX/SOCK_DGRAM socket for cgroup agent notification
[thirdparty/systemd.git] / src / coredump / coredump.c
... / ...
CommitLineData
1/***
2 This file is part of systemd.
3
4 Copyright 2012 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18***/
19
20#include <errno.h>
21#include <stdio.h>
22#include <sys/prctl.h>
23#include <sys/xattr.h>
24#include <unistd.h>
25
26#ifdef HAVE_ELFUTILS
27#include <dwarf.h>
28#include <elfutils/libdwfl.h>
29#endif
30
31#include "sd-journal.h"
32#include "sd-login.h"
33#include "sd-daemon.h"
34
35#include "acl-util.h"
36#include "alloc-util.h"
37#include "capability-util.h"
38#include "cgroup-util.h"
39#include "compress.h"
40#include "conf-parser.h"
41#include "copy.h"
42#include "coredump-vacuum.h"
43#include "dirent-util.h"
44#include "escape.h"
45#include "fd-util.h"
46#include "fileio.h"
47#include "fs-util.h"
48#include "io-util.h"
49#include "journald-native.h"
50#include "log.h"
51#include "macro.h"
52#include "missing.h"
53#include "mkdir.h"
54#include "parse-util.h"
55#include "process-util.h"
56#include "socket-util.h"
57#include "special.h"
58#include "stacktrace.h"
59#include "string-table.h"
60#include "string-util.h"
61#include "strv.h"
62#include "user-util.h"
63#include "util.h"
64
65/* The maximum size up to which we process coredumps */
66#define PROCESS_SIZE_MAX ((uint64_t) (2LLU*1024LLU*1024LLU*1024LLU))
67
68/* The maximum size up to which we leave the coredump around on disk */
69#define EXTERNAL_SIZE_MAX PROCESS_SIZE_MAX
70
71/* The maximum size up to which we store the coredump in the journal */
72#define JOURNAL_SIZE_MAX ((size_t) (767LU*1024LU*1024LU))
73
74/* Make sure to not make this larger than the maximum journal entry
75 * size. See DATA_SIZE_MAX in journald-native.c. */
76assert_cc(JOURNAL_SIZE_MAX <= DATA_SIZE_MAX);
77
78enum {
79 /* We use this as array indexes for a couple of special fields we use for naming coredumping files, and
80 * attaching xattrs */
81 CONTEXT_PID,
82 CONTEXT_UID,
83 CONTEXT_GID,
84 CONTEXT_SIGNAL,
85 CONTEXT_TIMESTAMP,
86 CONTEXT_RLIMIT,
87 CONTEXT_COMM,
88 CONTEXT_EXE,
89 _CONTEXT_MAX
90};
91
92typedef enum CoredumpStorage {
93 COREDUMP_STORAGE_NONE,
94 COREDUMP_STORAGE_EXTERNAL,
95 COREDUMP_STORAGE_JOURNAL,
96 COREDUMP_STORAGE_BOTH,
97 _COREDUMP_STORAGE_MAX,
98 _COREDUMP_STORAGE_INVALID = -1
99} CoredumpStorage;
100
101static const char* const coredump_storage_table[_COREDUMP_STORAGE_MAX] = {
102 [COREDUMP_STORAGE_NONE] = "none",
103 [COREDUMP_STORAGE_EXTERNAL] = "external",
104 [COREDUMP_STORAGE_JOURNAL] = "journal",
105 [COREDUMP_STORAGE_BOTH] = "both",
106};
107
108DEFINE_PRIVATE_STRING_TABLE_LOOKUP(coredump_storage, CoredumpStorage);
109static DEFINE_CONFIG_PARSE_ENUM(config_parse_coredump_storage, coredump_storage, CoredumpStorage, "Failed to parse storage setting");
110
111static CoredumpStorage arg_storage = COREDUMP_STORAGE_EXTERNAL;
112static bool arg_compress = true;
113static uint64_t arg_process_size_max = PROCESS_SIZE_MAX;
114static uint64_t arg_external_size_max = EXTERNAL_SIZE_MAX;
115static size_t arg_journal_size_max = JOURNAL_SIZE_MAX;
116static uint64_t arg_keep_free = (uint64_t) -1;
117static uint64_t arg_max_use = (uint64_t) -1;
118
119static int parse_config(void) {
120 static const ConfigTableItem items[] = {
121 { "Coredump", "Storage", config_parse_coredump_storage, 0, &arg_storage },
122 { "Coredump", "Compress", config_parse_bool, 0, &arg_compress },
123 { "Coredump", "ProcessSizeMax", config_parse_iec_uint64, 0, &arg_process_size_max },
124 { "Coredump", "ExternalSizeMax", config_parse_iec_uint64, 0, &arg_external_size_max },
125 { "Coredump", "JournalSizeMax", config_parse_iec_size, 0, &arg_journal_size_max },
126 { "Coredump", "KeepFree", config_parse_iec_uint64, 0, &arg_keep_free },
127 { "Coredump", "MaxUse", config_parse_iec_uint64, 0, &arg_max_use },
128 {}
129 };
130
131 return config_parse_many(PKGSYSCONFDIR "/coredump.conf",
132 CONF_PATHS_NULSTR("systemd/coredump.conf.d"),
133 "Coredump\0",
134 config_item_table_lookup, items,
135 false, NULL);
136}
137
138static int fix_acl(int fd, uid_t uid) {
139
140#ifdef HAVE_ACL
141 _cleanup_(acl_freep) acl_t acl = NULL;
142 acl_entry_t entry;
143 acl_permset_t permset;
144 int r;
145
146 assert(fd >= 0);
147
148 if (uid <= SYSTEM_UID_MAX)
149 return 0;
150
151 /* Make sure normal users can read (but not write or delete)
152 * their own coredumps */
153
154 acl = acl_get_fd(fd);
155 if (!acl)
156 return log_error_errno(errno, "Failed to get ACL: %m");
157
158 if (acl_create_entry(&acl, &entry) < 0 ||
159 acl_set_tag_type(entry, ACL_USER) < 0 ||
160 acl_set_qualifier(entry, &uid) < 0) {
161 log_error_errno(errno, "Failed to patch ACL: %m");
162 return -errno;
163 }
164
165 if (acl_get_permset(entry, &permset) < 0 ||
166 acl_add_perm(permset, ACL_READ) < 0)
167 return log_warning_errno(errno, "Failed to patch ACL: %m");
168
169 r = calc_acl_mask_if_needed(&acl);
170 if (r < 0)
171 return log_warning_errno(r, "Failed to patch ACL: %m");
172
173 if (acl_set_fd(fd, acl) < 0)
174 return log_error_errno(errno, "Failed to apply ACL: %m");
175#endif
176
177 return 0;
178}
179
180static int fix_xattr(int fd, const char *context[_CONTEXT_MAX]) {
181
182 static const char * const xattrs[_CONTEXT_MAX] = {
183 [CONTEXT_PID] = "user.coredump.pid",
184 [CONTEXT_UID] = "user.coredump.uid",
185 [CONTEXT_GID] = "user.coredump.gid",
186 [CONTEXT_SIGNAL] = "user.coredump.signal",
187 [CONTEXT_TIMESTAMP] = "user.coredump.timestamp",
188 [CONTEXT_COMM] = "user.coredump.comm",
189 [CONTEXT_EXE] = "user.coredump.exe",
190 };
191
192 int r = 0;
193 unsigned i;
194
195 assert(fd >= 0);
196
197 /* Attach some metadata to coredumps via extended
198 * attributes. Just because we can. */
199
200 for (i = 0; i < _CONTEXT_MAX; i++) {
201 int k;
202
203 if (isempty(context[i]) || !xattrs[i])
204 continue;
205
206 k = fsetxattr(fd, xattrs[i], context[i], strlen(context[i]), XATTR_CREATE);
207 if (k < 0 && r == 0)
208 r = -errno;
209 }
210
211 return r;
212}
213
214#define filename_escape(s) xescape((s), "./ ")
215
216static inline const char *coredump_tmpfile_name(const char *s) {
217 return s ? s : "(unnamed temporary file)";
218}
219
220static int fix_permissions(
221 int fd,
222 const char *filename,
223 const char *target,
224 const char *context[_CONTEXT_MAX],
225 uid_t uid) {
226
227 int r;
228
229 assert(fd >= 0);
230 assert(target);
231 assert(context);
232
233 /* Ignore errors on these */
234 (void) fchmod(fd, 0640);
235 (void) fix_acl(fd, uid);
236 (void) fix_xattr(fd, context);
237
238 if (fsync(fd) < 0)
239 return log_error_errno(errno, "Failed to sync coredump %s: %m", coredump_tmpfile_name(filename));
240
241 r = link_tmpfile(fd, filename, target);
242 if (r < 0)
243 return log_error_errno(r, "Failed to move coredump %s into place: %m", target);
244
245 return 0;
246}
247
248static int maybe_remove_external_coredump(const char *filename, uint64_t size) {
249
250 /* Returns 1 if might remove, 0 if will not remove, < 0 on error. */
251
252 if (IN_SET(arg_storage, COREDUMP_STORAGE_EXTERNAL, COREDUMP_STORAGE_BOTH) &&
253 size <= arg_external_size_max)
254 return 0;
255
256 if (!filename)
257 return 1;
258
259 if (unlink(filename) < 0 && errno != ENOENT)
260 return log_error_errno(errno, "Failed to unlink %s: %m", filename);
261
262 return 1;
263}
264
265static int make_filename(const char *context[_CONTEXT_MAX], char **ret) {
266 _cleanup_free_ char *c = NULL, *u = NULL, *p = NULL, *t = NULL;
267 sd_id128_t boot = {};
268 int r;
269
270 assert(context);
271
272 c = filename_escape(context[CONTEXT_COMM]);
273 if (!c)
274 return -ENOMEM;
275
276 u = filename_escape(context[CONTEXT_UID]);
277 if (!u)
278 return -ENOMEM;
279
280 r = sd_id128_get_boot(&boot);
281 if (r < 0)
282 return r;
283
284 p = filename_escape(context[CONTEXT_PID]);
285 if (!p)
286 return -ENOMEM;
287
288 t = filename_escape(context[CONTEXT_TIMESTAMP]);
289 if (!t)
290 return -ENOMEM;
291
292 if (asprintf(ret,
293 "/var/lib/systemd/coredump/core.%s.%s." SD_ID128_FORMAT_STR ".%s.%s000000",
294 c,
295 u,
296 SD_ID128_FORMAT_VAL(boot),
297 p,
298 t) < 0)
299 return -ENOMEM;
300
301 return 0;
302}
303
304static int save_external_coredump(
305 const char *context[_CONTEXT_MAX],
306 int input_fd,
307 char **ret_filename,
308 int *ret_node_fd,
309 int *ret_data_fd,
310 uint64_t *ret_size) {
311
312 _cleanup_free_ char *fn = NULL, *tmp = NULL;
313 _cleanup_close_ int fd = -1;
314 uint64_t rlimit, max_size;
315 struct stat st;
316 uid_t uid;
317 int r;
318
319 assert(context);
320 assert(ret_filename);
321 assert(ret_node_fd);
322 assert(ret_data_fd);
323 assert(ret_size);
324
325 r = parse_uid(context[CONTEXT_UID], &uid);
326 if (r < 0)
327 return log_error_errno(r, "Failed to parse UID: %m");
328
329 r = safe_atou64(context[CONTEXT_RLIMIT], &rlimit);
330 if (r < 0)
331 return log_error_errno(r, "Failed to parse resource limit: %s", context[CONTEXT_RLIMIT]);
332 if (rlimit <= 0) {
333 /* Is coredumping disabled? Then don't bother saving/processing the coredump */
334 log_info("Core Dumping has been disabled for process %s (%s).", context[CONTEXT_PID], context[CONTEXT_COMM]);
335 return -EBADSLT;
336 }
337
338 /* Never store more than the process configured, or than we actually shall keep or process */
339 max_size = MIN(rlimit, MAX(arg_process_size_max, arg_external_size_max));
340
341 r = make_filename(context, &fn);
342 if (r < 0)
343 return log_error_errno(r, "Failed to determine coredump file name: %m");
344
345 mkdir_p_label("/var/lib/systemd/coredump", 0755);
346
347 fd = open_tmpfile_linkable(fn, O_RDWR|O_CLOEXEC, &tmp);
348 if (fd < 0)
349 return log_error_errno(fd, "Failed to create temporary file for coredump %s: %m", fn);
350
351 r = copy_bytes(input_fd, fd, max_size, false);
352 if (r == -EFBIG) {
353 log_error("Coredump of %s (%s) is larger than configured processing limit, refusing.", context[CONTEXT_PID], context[CONTEXT_COMM]);
354 goto fail;
355 } else if (IN_SET(r, -EDQUOT, -ENOSPC)) {
356 log_error("Not enough disk space for coredump of %s (%s), refusing.", context[CONTEXT_PID], context[CONTEXT_COMM]);
357 goto fail;
358 } else if (r < 0) {
359 log_error_errno(r, "Failed to dump coredump to file: %m");
360 goto fail;
361 }
362
363 if (fstat(fd, &st) < 0) {
364 log_error_errno(errno, "Failed to fstat coredump %s: %m", coredump_tmpfile_name(tmp));
365 goto fail;
366 }
367
368 if (lseek(fd, 0, SEEK_SET) == (off_t) -1) {
369 log_error_errno(errno, "Failed to seek on %s: %m", coredump_tmpfile_name(tmp));
370 goto fail;
371 }
372
373#if defined(HAVE_XZ) || defined(HAVE_LZ4)
374 /* If we will remove the coredump anyway, do not compress. */
375 if (maybe_remove_external_coredump(NULL, st.st_size) == 0
376 && arg_compress) {
377
378 _cleanup_free_ char *fn_compressed = NULL, *tmp_compressed = NULL;
379 _cleanup_close_ int fd_compressed = -1;
380
381 fn_compressed = strappend(fn, COMPRESSED_EXT);
382 if (!fn_compressed) {
383 log_oom();
384 goto uncompressed;
385 }
386
387 fd_compressed = open_tmpfile_linkable(fn_compressed, O_RDWR|O_CLOEXEC, &tmp_compressed);
388 if (fd_compressed < 0) {
389 log_error_errno(fd_compressed, "Failed to create temporary file for coredump %s: %m", fn_compressed);
390 goto uncompressed;
391 }
392
393 r = compress_stream(fd, fd_compressed, -1);
394 if (r < 0) {
395 log_error_errno(r, "Failed to compress %s: %m", coredump_tmpfile_name(tmp_compressed));
396 goto fail_compressed;
397 }
398
399 r = fix_permissions(fd_compressed, tmp_compressed, fn_compressed, context, uid);
400 if (r < 0)
401 goto fail_compressed;
402
403 /* OK, this worked, we can get rid of the uncompressed version now */
404 if (tmp)
405 unlink_noerrno(tmp);
406
407 *ret_filename = fn_compressed; /* compressed */
408 *ret_node_fd = fd_compressed; /* compressed */
409 *ret_data_fd = fd; /* uncompressed */
410 *ret_size = (uint64_t) st.st_size; /* uncompressed */
411
412 fn_compressed = NULL;
413 fd = fd_compressed = -1;
414
415 return 0;
416
417 fail_compressed:
418 if (tmp_compressed)
419 (void) unlink(tmp_compressed);
420 }
421
422uncompressed:
423#endif
424
425 r = fix_permissions(fd, tmp, fn, context, uid);
426 if (r < 0)
427 goto fail;
428
429 *ret_filename = fn;
430 *ret_data_fd = fd;
431 *ret_node_fd = -1;
432 *ret_size = (uint64_t) st.st_size;
433
434 fn = NULL;
435 fd = -1;
436
437 return 0;
438
439fail:
440 if (tmp)
441 (void) unlink(tmp);
442 return r;
443}
444
445static int allocate_journal_field(int fd, size_t size, char **ret, size_t *ret_size) {
446 _cleanup_free_ char *field = NULL;
447 ssize_t n;
448
449 assert(fd >= 0);
450 assert(ret);
451 assert(ret_size);
452
453 if (lseek(fd, 0, SEEK_SET) == (off_t) -1)
454 return log_warning_errno(errno, "Failed to seek: %m");
455
456 field = malloc(9 + size);
457 if (!field) {
458 log_warning("Failed to allocate memory for coredump, coredump will not be stored.");
459 return -ENOMEM;
460 }
461
462 memcpy(field, "COREDUMP=", 9);
463
464 n = read(fd, field + 9, size);
465 if (n < 0)
466 return log_error_errno((int) n, "Failed to read core data: %m");
467 if ((size_t) n < size) {
468 log_error("Core data too short.");
469 return -EIO;
470 }
471
472 *ret = field;
473 *ret_size = size + 9;
474
475 field = NULL;
476
477 return 0;
478}
479
480/* Joins /proc/[pid]/fd/ and /proc/[pid]/fdinfo/ into the following lines:
481 * 0:/dev/pts/23
482 * pos: 0
483 * flags: 0100002
484 *
485 * 1:/dev/pts/23
486 * pos: 0
487 * flags: 0100002
488 *
489 * 2:/dev/pts/23
490 * pos: 0
491 * flags: 0100002
492 * EOF
493 */
494static int compose_open_fds(pid_t pid, char **open_fds) {
495 _cleanup_closedir_ DIR *proc_fd_dir = NULL;
496 _cleanup_close_ int proc_fdinfo_fd = -1;
497 _cleanup_free_ char *buffer = NULL;
498 _cleanup_fclose_ FILE *stream = NULL;
499 const char *fddelim = "", *path;
500 struct dirent *dent = NULL;
501 size_t size = 0;
502 int r = 0;
503
504 assert(pid >= 0);
505 assert(open_fds != NULL);
506
507 path = procfs_file_alloca(pid, "fd");
508 proc_fd_dir = opendir(path);
509 if (!proc_fd_dir)
510 return -errno;
511
512 proc_fdinfo_fd = openat(dirfd(proc_fd_dir), "../fdinfo", O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC|O_PATH);
513 if (proc_fdinfo_fd < 0)
514 return -errno;
515
516 stream = open_memstream(&buffer, &size);
517 if (!stream)
518 return -ENOMEM;
519
520 FOREACH_DIRENT(dent, proc_fd_dir, return -errno) {
521 _cleanup_fclose_ FILE *fdinfo = NULL;
522 _cleanup_free_ char *fdname = NULL;
523 char line[LINE_MAX];
524 int fd;
525
526 r = readlinkat_malloc(dirfd(proc_fd_dir), dent->d_name, &fdname);
527 if (r < 0)
528 return r;
529
530 fprintf(stream, "%s%s:%s\n", fddelim, dent->d_name, fdname);
531 fddelim = "\n";
532
533 /* Use the directory entry from /proc/[pid]/fd with /proc/[pid]/fdinfo */
534 fd = openat(proc_fdinfo_fd, dent->d_name, O_NOFOLLOW|O_CLOEXEC|O_RDONLY);
535 if (fd < 0)
536 continue;
537
538 fdinfo = fdopen(fd, "re");
539 if (fdinfo == NULL) {
540 close(fd);
541 continue;
542 }
543
544 FOREACH_LINE(line, fdinfo, break) {
545 fputs(line, stream);
546 if (!endswith(line, "\n"))
547 fputc('\n', stream);
548 }
549 }
550
551 errno = 0;
552 stream = safe_fclose(stream);
553
554 if (errno > 0)
555 return -errno;
556
557 *open_fds = buffer;
558 buffer = NULL;
559
560 return 0;
561}
562
563static int change_uid_gid(const char *context[]) {
564 uid_t uid;
565 gid_t gid;
566 int r;
567
568 r = parse_uid(context[CONTEXT_UID], &uid);
569 if (r < 0)
570 return r;
571
572 if (uid <= SYSTEM_UID_MAX) {
573 const char *user = "systemd-coredump";
574
575 r = get_user_creds(&user, &uid, &gid, NULL, NULL);
576 if (r < 0) {
577 log_warning_errno(r, "Cannot resolve %s user. Proceeding to dump core as root: %m", user);
578 uid = gid = 0;
579 }
580 } else {
581 r = parse_gid(context[CONTEXT_GID], &gid);
582 if (r < 0)
583 return r;
584 }
585
586 return drop_privileges(uid, gid, 0);
587}
588
589static int submit_coredump(
590 const char *context[_CONTEXT_MAX],
591 struct iovec *iovec,
592 size_t n_iovec_allocated,
593 size_t n_iovec,
594 int input_fd) {
595
596 _cleanup_close_ int coredump_fd = -1, coredump_node_fd = -1;
597 _cleanup_free_ char *core_message = NULL, *filename = NULL, *coredump_data = NULL;
598 uint64_t coredump_size;
599 int r;
600
601 assert(context);
602 assert(iovec);
603 assert(n_iovec_allocated >= n_iovec + 3);
604 assert(input_fd >= 0);
605
606 /* Vacuum before we write anything again */
607 (void) coredump_vacuum(-1, arg_keep_free, arg_max_use);
608
609 /* Always stream the coredump to disk, if that's possible */
610 r = save_external_coredump(context, input_fd, &filename, &coredump_node_fd, &coredump_fd, &coredump_size);
611 if (r < 0)
612 /* Skip whole core dumping part */
613 goto log;
614
615 /* If we don't want to keep the coredump on disk, remove it now, as later on we will lack the privileges for
616 * it. However, we keep the fd to it, so that we can still process it and log it. */
617 r = maybe_remove_external_coredump(filename, coredump_size);
618 if (r < 0)
619 return r;
620 if (r == 0) {
621 const char *coredump_filename;
622
623 coredump_filename = strjoina("COREDUMP_FILENAME=", filename);
624 IOVEC_SET_STRING(iovec[n_iovec++], coredump_filename);
625 }
626
627 /* Vacuum again, but exclude the coredump we just created */
628 (void) coredump_vacuum(coredump_node_fd >= 0 ? coredump_node_fd : coredump_fd, arg_keep_free, arg_max_use);
629
630 /* Now, let's drop privileges to become the user who owns the segfaulted process and allocate the coredump
631 * memory under the user's uid. This also ensures that the credentials journald will see are the ones of the
632 * coredumping user, thus making sure the user gets access to the core dump. Let's also get rid of all
633 * capabilities, if we run as root, we won't need them anymore. */
634 r = change_uid_gid(context);
635 if (r < 0)
636 return log_error_errno(r, "Failed to drop privileges: %m");
637
638#ifdef HAVE_ELFUTILS
639 /* Try to get a strack trace if we can */
640 if (coredump_size <= arg_process_size_max) {
641 _cleanup_free_ char *stacktrace = NULL;
642
643 r = coredump_make_stack_trace(coredump_fd, context[CONTEXT_EXE], &stacktrace);
644 if (r >= 0)
645 core_message = strjoin("MESSAGE=Process ", context[CONTEXT_PID], " (", context[CONTEXT_COMM], ") of user ", context[CONTEXT_UID], " dumped core.\n\n", stacktrace, NULL);
646 else if (r == -EINVAL)
647 log_warning("Failed to generate stack trace: %s", dwfl_errmsg(dwfl_errno()));
648 else
649 log_warning_errno(r, "Failed to generate stack trace: %m");
650 }
651
652 if (!core_message)
653#endif
654log:
655 core_message = strjoin("MESSAGE=Process ", context[CONTEXT_PID], " (", context[CONTEXT_COMM], ") of user ", context[CONTEXT_UID], " dumped core.", NULL);
656 if (core_message)
657 IOVEC_SET_STRING(iovec[n_iovec++], core_message);
658
659 /* Optionally store the entire coredump in the journal */
660 if (IN_SET(arg_storage, COREDUMP_STORAGE_JOURNAL, COREDUMP_STORAGE_BOTH) &&
661 coredump_size <= arg_journal_size_max) {
662 size_t sz = 0;
663
664 /* Store the coredump itself in the journal */
665
666 r = allocate_journal_field(coredump_fd, (size_t) coredump_size, &coredump_data, &sz);
667 if (r >= 0) {
668 iovec[n_iovec].iov_base = coredump_data;
669 iovec[n_iovec].iov_len = sz;
670 n_iovec++;
671 }
672 }
673
674 assert(n_iovec <= n_iovec_allocated);
675
676 r = sd_journal_sendv(iovec, n_iovec);
677 if (r < 0)
678 return log_error_errno(r, "Failed to log coredump: %m");
679
680 return 0;
681}
682
683static void map_context_fields(const struct iovec *iovec, const char *context[]) {
684
685 static const char * const context_field_names[_CONTEXT_MAX] = {
686 [CONTEXT_PID] = "COREDUMP_PID=",
687 [CONTEXT_UID] = "COREDUMP_UID=",
688 [CONTEXT_GID] = "COREDUMP_GID=",
689 [CONTEXT_SIGNAL] = "COREDUMP_SIGNAL=",
690 [CONTEXT_TIMESTAMP] = "COREDUMP_TIMESTAMP=",
691 [CONTEXT_COMM] = "COREDUMP_COMM=",
692 [CONTEXT_EXE] = "COREDUMP_EXE=",
693 [CONTEXT_RLIMIT] = "COREDUMP_RLIMIT=",
694 };
695
696 unsigned i;
697
698 assert(iovec);
699 assert(context);
700
701 for (i = 0; i < _CONTEXT_MAX; i++) {
702 size_t l;
703
704 l = strlen(context_field_names[i]);
705 if (iovec->iov_len < l)
706 continue;
707
708 if (memcmp(iovec->iov_base, context_field_names[i], l) != 0)
709 continue;
710
711 /* Note that these strings are NUL terminated, because we made sure that a trailing NUL byte is in the
712 * buffer, though not included in the iov_len count. (see below) */
713 context[i] = (char*) iovec->iov_base + l;
714 break;
715 }
716}
717
718static int process_socket(int fd) {
719 _cleanup_close_ int coredump_fd = -1;
720 struct iovec *iovec = NULL;
721 size_t n_iovec = 0, n_iovec_allocated = 0, i;
722 const char *context[_CONTEXT_MAX] = {};
723 int r;
724
725 assert(fd >= 0);
726
727 log_set_target(LOG_TARGET_AUTO);
728 log_parse_environment();
729 log_open();
730
731 for (;;) {
732 union {
733 struct cmsghdr cmsghdr;
734 uint8_t buf[CMSG_SPACE(sizeof(int))];
735 } control = {};
736 struct msghdr mh = {
737 .msg_control = &control,
738 .msg_controllen = sizeof(control),
739 .msg_iovlen = 1,
740 };
741 ssize_t n;
742 int l;
743
744 if (!GREEDY_REALLOC(iovec, n_iovec_allocated, n_iovec + 3)) {
745 r = log_oom();
746 goto finish;
747 }
748
749 if (ioctl(fd, FIONREAD, &l) < 0) {
750 r = log_error_errno(errno, "FIONREAD failed: %m");
751 goto finish;
752 }
753
754 assert(l >= 0);
755
756 iovec[n_iovec].iov_len = l;
757 iovec[n_iovec].iov_base = malloc(l + 1);
758
759 if (!iovec[n_iovec].iov_base) {
760 r = log_oom();
761 goto finish;
762 }
763
764 mh.msg_iov = iovec + n_iovec;
765
766 n = recvmsg(fd, &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
767 if (n < 0) {
768 free(iovec[n_iovec].iov_base);
769 r = log_error_errno(errno, "Failed to receive datagram: %m");
770 goto finish;
771 }
772
773 if (n == 0) {
774 struct cmsghdr *cmsg, *found = NULL;
775 /* The final zero-length datagram carries the file descriptor and tells us that we're done. */
776
777 free(iovec[n_iovec].iov_base);
778
779 CMSG_FOREACH(cmsg, &mh) {
780 if (cmsg->cmsg_level == SOL_SOCKET &&
781 cmsg->cmsg_type == SCM_RIGHTS &&
782 cmsg->cmsg_len == CMSG_LEN(sizeof(int))) {
783 assert(!found);
784 found = cmsg;
785 }
786 }
787
788 if (!found) {
789 log_error("Coredump file descriptor missing.");
790 r = -EBADMSG;
791 goto finish;
792 }
793
794 assert(coredump_fd < 0);
795 coredump_fd = *(int*) CMSG_DATA(found);
796 break;
797 }
798
799 /* Add trailing NUL byte, in case these are strings */
800 ((char*) iovec[n_iovec].iov_base)[n] = 0;
801 iovec[n_iovec].iov_len = (size_t) n;
802
803 cmsg_close_all(&mh);
804 map_context_fields(iovec + n_iovec, context);
805 n_iovec++;
806 }
807
808 if (!GREEDY_REALLOC(iovec, n_iovec_allocated, n_iovec + 3)) {
809 r = log_oom();
810 goto finish;
811 }
812
813 /* Make sure we we got all data we really need */
814 assert(context[CONTEXT_PID]);
815 assert(context[CONTEXT_UID]);
816 assert(context[CONTEXT_GID]);
817 assert(context[CONTEXT_SIGNAL]);
818 assert(context[CONTEXT_TIMESTAMP]);
819 assert(context[CONTEXT_RLIMIT]);
820 assert(context[CONTEXT_COMM]);
821 assert(coredump_fd >= 0);
822
823 r = submit_coredump(context, iovec, n_iovec_allocated, n_iovec, coredump_fd);
824
825finish:
826 for (i = 0; i < n_iovec; i++)
827 free(iovec[i].iov_base);
828 free(iovec);
829
830 return r;
831}
832
833static int send_iovec(const struct iovec iovec[], size_t n_iovec, int input_fd) {
834
835 static const union sockaddr_union sa = {
836 .un.sun_family = AF_UNIX,
837 .un.sun_path = "/run/systemd/coredump",
838 };
839 _cleanup_close_ int fd = -1;
840 size_t i;
841 int r;
842
843 assert(iovec || n_iovec <= 0);
844 assert(input_fd >= 0);
845
846 fd = socket(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0);
847 if (fd < 0)
848 return log_error_errno(errno, "Failed to create coredump socket: %m");
849
850 if (connect(fd, &sa.sa, offsetof(union sockaddr_union, un.sun_path) + strlen(sa.un.sun_path)) < 0)
851 return log_error_errno(errno, "Failed to connect to coredump service: %m");
852
853 for (i = 0; i < n_iovec; i++) {
854 ssize_t n;
855 assert(iovec[i].iov_len > 0);
856
857 n = send(fd, iovec[i].iov_base, iovec[i].iov_len, MSG_NOSIGNAL);
858 if (n < 0)
859 return log_error_errno(errno, "Failed to send coredump datagram: %m");
860 }
861
862 r = send_one_fd(fd, input_fd, 0);
863 if (r < 0)
864 return log_error_errno(r, "Failed to send coredump fd: %m");
865
866 return 0;
867}
868
869static int process_journald_crash(const char *context[], int input_fd) {
870 _cleanup_close_ int coredump_fd = -1, coredump_node_fd = -1;
871 _cleanup_free_ char *filename = NULL;
872 uint64_t coredump_size;
873 int r;
874
875 assert(context);
876 assert(input_fd >= 0);
877
878 /* If we are journald, we cut things short, don't write to the journal, but still create a coredump. */
879
880 if (arg_storage != COREDUMP_STORAGE_NONE)
881 arg_storage = COREDUMP_STORAGE_EXTERNAL;
882
883 r = save_external_coredump(context, input_fd, &filename, &coredump_node_fd, &coredump_fd, &coredump_size);
884 if (r < 0)
885 return r;
886
887 r = maybe_remove_external_coredump(filename, coredump_size);
888 if (r < 0)
889 return r;
890
891 log_info("Detected coredump of the journal daemon itself, diverted to %s.", filename);
892 return 0;
893}
894
895static int process_kernel(int argc, char* argv[]) {
896
897 /* The small core field we allocate on the stack, to keep things simple */
898 char
899 *core_pid = NULL, *core_uid = NULL, *core_gid = NULL, *core_signal = NULL,
900 *core_session = NULL, *core_exe = NULL, *core_comm = NULL, *core_cmdline = NULL,
901 *core_cgroup = NULL, *core_cwd = NULL, *core_root = NULL, *core_unit = NULL,
902 *core_user_unit = NULL, *core_slice = NULL, *core_timestamp = NULL, *core_rlimit = NULL;
903
904 /* The larger ones we allocate on the heap */
905 _cleanup_free_ char
906 *core_owner_uid = NULL, *core_open_fds = NULL, *core_proc_status = NULL,
907 *core_proc_maps = NULL, *core_proc_limits = NULL, *core_proc_cgroup = NULL, *core_environ = NULL;
908
909 _cleanup_free_ char *exe = NULL, *comm = NULL;
910 const char *context[_CONTEXT_MAX];
911 struct iovec iovec[25];
912 size_t n_iovec = 0;
913 uid_t owner_uid;
914 const char *p;
915 pid_t pid;
916 char *t;
917 int r;
918
919 if (argc < CONTEXT_COMM + 1) {
920 log_error("Not enough arguments passed from kernel (%i, expected %i).", argc - 1, CONTEXT_COMM + 1 - 1);
921 return -EINVAL;
922 }
923
924 r = parse_pid(argv[CONTEXT_PID + 1], &pid);
925 if (r < 0)
926 return log_error_errno(r, "Failed to parse PID.");
927
928 r = get_process_comm(pid, &comm);
929 if (r < 0) {
930 log_warning_errno(r, "Failed to get COMM, falling back to the command line: %m");
931 comm = strv_join(argv + CONTEXT_COMM + 1, " ");
932 if (!comm)
933 return log_oom();
934 }
935
936 r = get_process_exe(pid, &exe);
937 if (r < 0)
938 log_warning_errno(r, "Failed to get EXE, ignoring: %m");
939
940 context[CONTEXT_PID] = argv[CONTEXT_PID + 1];
941 context[CONTEXT_UID] = argv[CONTEXT_UID + 1];
942 context[CONTEXT_GID] = argv[CONTEXT_GID + 1];
943 context[CONTEXT_SIGNAL] = argv[CONTEXT_SIGNAL + 1];
944 context[CONTEXT_TIMESTAMP] = argv[CONTEXT_TIMESTAMP + 1];
945 context[CONTEXT_RLIMIT] = argv[CONTEXT_RLIMIT + 1];
946 context[CONTEXT_COMM] = comm;
947 context[CONTEXT_EXE] = exe;
948
949 if (cg_pid_get_unit(pid, &t) >= 0) {
950
951 if (streq(t, SPECIAL_JOURNALD_SERVICE)) {
952 free(t);
953 return process_journald_crash(context, STDIN_FILENO);
954 }
955
956 core_unit = strjoina("COREDUMP_UNIT=", t);
957 free(t);
958
959 IOVEC_SET_STRING(iovec[n_iovec++], core_unit);
960 }
961
962 /* OK, now we know it's not the journal, hence we can make use of it now. */
963 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
964 log_open();
965
966 if (cg_pid_get_user_unit(pid, &t) >= 0) {
967 core_user_unit = strjoina("COREDUMP_USER_UNIT=", t);
968 free(t);
969
970 IOVEC_SET_STRING(iovec[n_iovec++], core_user_unit);
971 }
972
973 core_pid = strjoina("COREDUMP_PID=", context[CONTEXT_PID]);
974 IOVEC_SET_STRING(iovec[n_iovec++], core_pid);
975
976 core_uid = strjoina("COREDUMP_UID=", context[CONTEXT_UID]);
977 IOVEC_SET_STRING(iovec[n_iovec++], core_uid);
978
979 core_gid = strjoina("COREDUMP_GID=", context[CONTEXT_GID]);
980 IOVEC_SET_STRING(iovec[n_iovec++], core_gid);
981
982 core_signal = strjoina("COREDUMP_SIGNAL=", context[CONTEXT_SIGNAL]);
983 IOVEC_SET_STRING(iovec[n_iovec++], core_signal);
984
985 core_rlimit = strjoina("COREDUMP_RLIMIT=", context[CONTEXT_RLIMIT]);
986 IOVEC_SET_STRING(iovec[n_iovec++], core_rlimit);
987
988 if (sd_pid_get_session(pid, &t) >= 0) {
989 core_session = strjoina("COREDUMP_SESSION=", t);
990 free(t);
991
992 IOVEC_SET_STRING(iovec[n_iovec++], core_session);
993 }
994
995 if (sd_pid_get_owner_uid(pid, &owner_uid) >= 0) {
996 r = asprintf(&core_owner_uid, "COREDUMP_OWNER_UID=" UID_FMT, owner_uid);
997 if (r > 0)
998 IOVEC_SET_STRING(iovec[n_iovec++], core_owner_uid);
999 }
1000
1001 if (sd_pid_get_slice(pid, &t) >= 0) {
1002 core_slice = strjoina("COREDUMP_SLICE=", t);
1003 free(t);
1004
1005 IOVEC_SET_STRING(iovec[n_iovec++], core_slice);
1006 }
1007
1008 if (comm) {
1009 core_comm = strjoina("COREDUMP_COMM=", comm);
1010 IOVEC_SET_STRING(iovec[n_iovec++], core_comm);
1011 }
1012
1013 if (exe) {
1014 core_exe = strjoina("COREDUMP_EXE=", exe);
1015 IOVEC_SET_STRING(iovec[n_iovec++], core_exe);
1016 }
1017
1018 if (get_process_cmdline(pid, 0, false, &t) >= 0) {
1019 core_cmdline = strjoina("COREDUMP_CMDLINE=", t);
1020 free(t);
1021
1022 IOVEC_SET_STRING(iovec[n_iovec++], core_cmdline);
1023 }
1024
1025 if (cg_pid_get_path_shifted(pid, NULL, &t) >= 0) {
1026 core_cgroup = strjoina("COREDUMP_CGROUP=", t);
1027 free(t);
1028
1029 IOVEC_SET_STRING(iovec[n_iovec++], core_cgroup);
1030 }
1031
1032 if (compose_open_fds(pid, &t) >= 0) {
1033 core_open_fds = strappend("COREDUMP_OPEN_FDS=", t);
1034 free(t);
1035
1036 if (core_open_fds)
1037 IOVEC_SET_STRING(iovec[n_iovec++], core_open_fds);
1038 }
1039
1040 p = procfs_file_alloca(pid, "status");
1041 if (read_full_file(p, &t, NULL) >= 0) {
1042 core_proc_status = strappend("COREDUMP_PROC_STATUS=", t);
1043 free(t);
1044
1045 if (core_proc_status)
1046 IOVEC_SET_STRING(iovec[n_iovec++], core_proc_status);
1047 }
1048
1049 p = procfs_file_alloca(pid, "maps");
1050 if (read_full_file(p, &t, NULL) >= 0) {
1051 core_proc_maps = strappend("COREDUMP_PROC_MAPS=", t);
1052 free(t);
1053
1054 if (core_proc_maps)
1055 IOVEC_SET_STRING(iovec[n_iovec++], core_proc_maps);
1056 }
1057
1058 p = procfs_file_alloca(pid, "limits");
1059 if (read_full_file(p, &t, NULL) >= 0) {
1060 core_proc_limits = strappend("COREDUMP_PROC_LIMITS=", t);
1061 free(t);
1062
1063 if (core_proc_limits)
1064 IOVEC_SET_STRING(iovec[n_iovec++], core_proc_limits);
1065 }
1066
1067 p = procfs_file_alloca(pid, "cgroup");
1068 if (read_full_file(p, &t, NULL) >=0) {
1069 core_proc_cgroup = strappend("COREDUMP_PROC_CGROUP=", t);
1070 free(t);
1071
1072 if (core_proc_cgroup)
1073 IOVEC_SET_STRING(iovec[n_iovec++], core_proc_cgroup);
1074 }
1075
1076 if (get_process_cwd(pid, &t) >= 0) {
1077 core_cwd = strjoina("COREDUMP_CWD=", t);
1078 free(t);
1079
1080 IOVEC_SET_STRING(iovec[n_iovec++], core_cwd);
1081 }
1082
1083 if (get_process_root(pid, &t) >= 0) {
1084 core_root = strjoina("COREDUMP_ROOT=", t);
1085 free(t);
1086
1087 IOVEC_SET_STRING(iovec[n_iovec++], core_root);
1088 }
1089
1090 if (get_process_environ(pid, &t) >= 0) {
1091 core_environ = strappend("COREDUMP_ENVIRON=", t);
1092 free(t);
1093
1094 if (core_environ)
1095 IOVEC_SET_STRING(iovec[n_iovec++], core_environ);
1096 }
1097
1098 core_timestamp = strjoina("COREDUMP_TIMESTAMP=", context[CONTEXT_TIMESTAMP], "000000");
1099 IOVEC_SET_STRING(iovec[n_iovec++], core_timestamp);
1100
1101 IOVEC_SET_STRING(iovec[n_iovec++], "MESSAGE_ID=fc2e22bc6ee647b6b90729ab34a250b1");
1102
1103 assert_cc(2 == LOG_CRIT);
1104 IOVEC_SET_STRING(iovec[n_iovec++], "PRIORITY=2");
1105
1106 assert(n_iovec <= ELEMENTSOF(iovec));
1107
1108 return send_iovec(iovec, n_iovec, STDIN_FILENO);
1109}
1110
1111int main(int argc, char *argv[]) {
1112 int r;
1113
1114 /* First, log to a safe place, since we don't know what crashed and it might be journald which we'd rather not
1115 * log to then. */
1116
1117 log_set_target(LOG_TARGET_KMSG);
1118 log_open();
1119
1120 /* Make sure we never enter a loop */
1121 (void) prctl(PR_SET_DUMPABLE, 0);
1122
1123 /* Ignore all parse errors */
1124 (void) parse_config();
1125
1126 log_debug("Selected storage '%s'.", coredump_storage_to_string(arg_storage));
1127 log_debug("Selected compression %s.", yes_no(arg_compress));
1128
1129 r = sd_listen_fds(false);
1130 if (r < 0) {
1131 log_error_errno(r, "Failed to determine number of file descriptor: %m");
1132 goto finish;
1133 }
1134
1135 /* If we got an fd passed, we are running in coredumpd mode. Otherwise we are invoked from the kernel as
1136 * coredump handler */
1137 if (r == 0)
1138 r = process_kernel(argc, argv);
1139 else if (r == 1)
1140 r = process_socket(SD_LISTEN_FDS_START);
1141 else {
1142 log_error("Received unexpected number of file descriptors.");
1143 r = -EINVAL;
1144 }
1145
1146finish:
1147 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1148}