]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/coredump/coredump.c
treewide: fix typos and remove accidental repetition of words
[thirdparty/systemd.git] / src / coredump / coredump.c
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. */
76 assert_cc(JOURNAL_SIZE_MAX <= DATA_SIZE_MAX);
77
78 enum {
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
92 typedef 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
101 static 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
108 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(coredump_storage, CoredumpStorage);
109 static DEFINE_CONFIG_PARSE_ENUM(config_parse_coredump_storage, coredump_storage, CoredumpStorage, "Failed to parse storage setting");
110
111 static CoredumpStorage arg_storage = COREDUMP_STORAGE_EXTERNAL;
112 static bool arg_compress = true;
113 static uint64_t arg_process_size_max = PROCESS_SIZE_MAX;
114 static uint64_t arg_external_size_max = EXTERNAL_SIZE_MAX;
115 static size_t arg_journal_size_max = JOURNAL_SIZE_MAX;
116 static uint64_t arg_keep_free = (uint64_t) -1;
117 static uint64_t arg_max_use = (uint64_t) -1;
118
119 static 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
138 static 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
180 static 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
216 static inline const char *coredump_tmpfile_name(const char *s) {
217 return s ? s : "(unnamed temporary file)";
218 }
219
220 static 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
248 static 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
265 static 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
304 static 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
422 uncompressed:
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
439 fail:
440 if (tmp)
441 (void) unlink(tmp);
442 return r;
443 }
444
445 static 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 */
494 static 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
563 static 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
589 static 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
654 log:
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
683 static 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
718 static 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 ssize_t l;
743
744 if (!GREEDY_REALLOC(iovec, n_iovec_allocated, n_iovec + 3)) {
745 r = log_oom();
746 goto finish;
747 }
748
749 l = next_datagram_size_fd(fd);
750 if (l < 0) {
751 r = log_error_errno(l, "Failed to determine datagram size to read: %m");
752 goto finish;
753 }
754
755 assert(l >= 0);
756
757 iovec[n_iovec].iov_len = l;
758 iovec[n_iovec].iov_base = malloc(l + 1);
759
760 if (!iovec[n_iovec].iov_base) {
761 r = log_oom();
762 goto finish;
763 }
764
765 mh.msg_iov = iovec + n_iovec;
766
767 n = recvmsg(fd, &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC);
768 if (n < 0) {
769 free(iovec[n_iovec].iov_base);
770 r = log_error_errno(errno, "Failed to receive datagram: %m");
771 goto finish;
772 }
773
774 if (n == 0) {
775 struct cmsghdr *cmsg, *found = NULL;
776 /* The final zero-length datagram carries the file descriptor and tells us that we're done. */
777
778 free(iovec[n_iovec].iov_base);
779
780 CMSG_FOREACH(cmsg, &mh) {
781 if (cmsg->cmsg_level == SOL_SOCKET &&
782 cmsg->cmsg_type == SCM_RIGHTS &&
783 cmsg->cmsg_len == CMSG_LEN(sizeof(int))) {
784 assert(!found);
785 found = cmsg;
786 }
787 }
788
789 if (!found) {
790 log_error("Coredump file descriptor missing.");
791 r = -EBADMSG;
792 goto finish;
793 }
794
795 assert(coredump_fd < 0);
796 coredump_fd = *(int*) CMSG_DATA(found);
797 break;
798 }
799
800 /* Add trailing NUL byte, in case these are strings */
801 ((char*) iovec[n_iovec].iov_base)[n] = 0;
802 iovec[n_iovec].iov_len = (size_t) n;
803
804 cmsg_close_all(&mh);
805 map_context_fields(iovec + n_iovec, context);
806 n_iovec++;
807 }
808
809 if (!GREEDY_REALLOC(iovec, n_iovec_allocated, n_iovec + 3)) {
810 r = log_oom();
811 goto finish;
812 }
813
814 /* Make sure we got all data we really need */
815 assert(context[CONTEXT_PID]);
816 assert(context[CONTEXT_UID]);
817 assert(context[CONTEXT_GID]);
818 assert(context[CONTEXT_SIGNAL]);
819 assert(context[CONTEXT_TIMESTAMP]);
820 assert(context[CONTEXT_RLIMIT]);
821 assert(context[CONTEXT_COMM]);
822 assert(coredump_fd >= 0);
823
824 r = submit_coredump(context, iovec, n_iovec_allocated, n_iovec, coredump_fd);
825
826 finish:
827 for (i = 0; i < n_iovec; i++)
828 free(iovec[i].iov_base);
829 free(iovec);
830
831 return r;
832 }
833
834 static int send_iovec(const struct iovec iovec[], size_t n_iovec, int input_fd) {
835
836 static const union sockaddr_union sa = {
837 .un.sun_family = AF_UNIX,
838 .un.sun_path = "/run/systemd/coredump",
839 };
840 _cleanup_close_ int fd = -1;
841 size_t i;
842 int r;
843
844 assert(iovec || n_iovec <= 0);
845 assert(input_fd >= 0);
846
847 fd = socket(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0);
848 if (fd < 0)
849 return log_error_errno(errno, "Failed to create coredump socket: %m");
850
851 if (connect(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0)
852 return log_error_errno(errno, "Failed to connect to coredump service: %m");
853
854 for (i = 0; i < n_iovec; i++) {
855 ssize_t n;
856 assert(iovec[i].iov_len > 0);
857
858 n = send(fd, iovec[i].iov_base, iovec[i].iov_len, MSG_NOSIGNAL);
859 if (n < 0)
860 return log_error_errno(errno, "Failed to send coredump datagram: %m");
861 }
862
863 r = send_one_fd(fd, input_fd, 0);
864 if (r < 0)
865 return log_error_errno(r, "Failed to send coredump fd: %m");
866
867 return 0;
868 }
869
870 static int process_journald_crash(const char *context[], int input_fd) {
871 _cleanup_close_ int coredump_fd = -1, coredump_node_fd = -1;
872 _cleanup_free_ char *filename = NULL;
873 uint64_t coredump_size;
874 int r;
875
876 assert(context);
877 assert(input_fd >= 0);
878
879 /* If we are journald, we cut things short, don't write to the journal, but still create a coredump. */
880
881 if (arg_storage != COREDUMP_STORAGE_NONE)
882 arg_storage = COREDUMP_STORAGE_EXTERNAL;
883
884 r = save_external_coredump(context, input_fd, &filename, &coredump_node_fd, &coredump_fd, &coredump_size);
885 if (r < 0)
886 return r;
887
888 r = maybe_remove_external_coredump(filename, coredump_size);
889 if (r < 0)
890 return r;
891
892 log_info("Detected coredump of the journal daemon itself, diverted to %s.", filename);
893 return 0;
894 }
895
896 static int process_kernel(int argc, char* argv[]) {
897
898 /* The small core field we allocate on the stack, to keep things simple */
899 char
900 *core_pid = NULL, *core_uid = NULL, *core_gid = NULL, *core_signal = NULL,
901 *core_session = NULL, *core_exe = NULL, *core_comm = NULL, *core_cmdline = NULL,
902 *core_cgroup = NULL, *core_cwd = NULL, *core_root = NULL, *core_unit = NULL,
903 *core_user_unit = NULL, *core_slice = NULL, *core_timestamp = NULL, *core_rlimit = NULL;
904
905 /* The larger ones we allocate on the heap */
906 _cleanup_free_ char
907 *core_owner_uid = NULL, *core_open_fds = NULL, *core_proc_status = NULL,
908 *core_proc_maps = NULL, *core_proc_limits = NULL, *core_proc_cgroup = NULL, *core_environ = NULL;
909
910 _cleanup_free_ char *exe = NULL, *comm = NULL;
911 const char *context[_CONTEXT_MAX];
912 struct iovec iovec[25];
913 size_t n_iovec = 0;
914 uid_t owner_uid;
915 const char *p;
916 pid_t pid;
917 char *t;
918 int r;
919
920 if (argc < CONTEXT_COMM + 1) {
921 log_error("Not enough arguments passed from kernel (%i, expected %i).", argc - 1, CONTEXT_COMM + 1 - 1);
922 return -EINVAL;
923 }
924
925 r = parse_pid(argv[CONTEXT_PID + 1], &pid);
926 if (r < 0)
927 return log_error_errno(r, "Failed to parse PID.");
928
929 r = get_process_comm(pid, &comm);
930 if (r < 0) {
931 log_warning_errno(r, "Failed to get COMM, falling back to the command line: %m");
932 comm = strv_join(argv + CONTEXT_COMM + 1, " ");
933 if (!comm)
934 return log_oom();
935 }
936
937 r = get_process_exe(pid, &exe);
938 if (r < 0)
939 log_warning_errno(r, "Failed to get EXE, ignoring: %m");
940
941 context[CONTEXT_PID] = argv[CONTEXT_PID + 1];
942 context[CONTEXT_UID] = argv[CONTEXT_UID + 1];
943 context[CONTEXT_GID] = argv[CONTEXT_GID + 1];
944 context[CONTEXT_SIGNAL] = argv[CONTEXT_SIGNAL + 1];
945 context[CONTEXT_TIMESTAMP] = argv[CONTEXT_TIMESTAMP + 1];
946 context[CONTEXT_RLIMIT] = argv[CONTEXT_RLIMIT + 1];
947 context[CONTEXT_COMM] = comm;
948 context[CONTEXT_EXE] = exe;
949
950 if (cg_pid_get_unit(pid, &t) >= 0) {
951
952 if (streq(t, SPECIAL_JOURNALD_SERVICE)) {
953 free(t);
954 return process_journald_crash(context, STDIN_FILENO);
955 }
956
957 core_unit = strjoina("COREDUMP_UNIT=", t);
958 free(t);
959
960 IOVEC_SET_STRING(iovec[n_iovec++], core_unit);
961 }
962
963 /* OK, now we know it's not the journal, hence we can make use of it now. */
964 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
965 log_open();
966
967 if (cg_pid_get_user_unit(pid, &t) >= 0) {
968 core_user_unit = strjoina("COREDUMP_USER_UNIT=", t);
969 free(t);
970
971 IOVEC_SET_STRING(iovec[n_iovec++], core_user_unit);
972 }
973
974 core_pid = strjoina("COREDUMP_PID=", context[CONTEXT_PID]);
975 IOVEC_SET_STRING(iovec[n_iovec++], core_pid);
976
977 core_uid = strjoina("COREDUMP_UID=", context[CONTEXT_UID]);
978 IOVEC_SET_STRING(iovec[n_iovec++], core_uid);
979
980 core_gid = strjoina("COREDUMP_GID=", context[CONTEXT_GID]);
981 IOVEC_SET_STRING(iovec[n_iovec++], core_gid);
982
983 core_signal = strjoina("COREDUMP_SIGNAL=", context[CONTEXT_SIGNAL]);
984 IOVEC_SET_STRING(iovec[n_iovec++], core_signal);
985
986 core_rlimit = strjoina("COREDUMP_RLIMIT=", context[CONTEXT_RLIMIT]);
987 IOVEC_SET_STRING(iovec[n_iovec++], core_rlimit);
988
989 if (sd_pid_get_session(pid, &t) >= 0) {
990 core_session = strjoina("COREDUMP_SESSION=", t);
991 free(t);
992
993 IOVEC_SET_STRING(iovec[n_iovec++], core_session);
994 }
995
996 if (sd_pid_get_owner_uid(pid, &owner_uid) >= 0) {
997 r = asprintf(&core_owner_uid, "COREDUMP_OWNER_UID=" UID_FMT, owner_uid);
998 if (r > 0)
999 IOVEC_SET_STRING(iovec[n_iovec++], core_owner_uid);
1000 }
1001
1002 if (sd_pid_get_slice(pid, &t) >= 0) {
1003 core_slice = strjoina("COREDUMP_SLICE=", t);
1004 free(t);
1005
1006 IOVEC_SET_STRING(iovec[n_iovec++], core_slice);
1007 }
1008
1009 if (comm) {
1010 core_comm = strjoina("COREDUMP_COMM=", comm);
1011 IOVEC_SET_STRING(iovec[n_iovec++], core_comm);
1012 }
1013
1014 if (exe) {
1015 core_exe = strjoina("COREDUMP_EXE=", exe);
1016 IOVEC_SET_STRING(iovec[n_iovec++], core_exe);
1017 }
1018
1019 if (get_process_cmdline(pid, 0, false, &t) >= 0) {
1020 core_cmdline = strjoina("COREDUMP_CMDLINE=", t);
1021 free(t);
1022
1023 IOVEC_SET_STRING(iovec[n_iovec++], core_cmdline);
1024 }
1025
1026 if (cg_pid_get_path_shifted(pid, NULL, &t) >= 0) {
1027 core_cgroup = strjoina("COREDUMP_CGROUP=", t);
1028 free(t);
1029
1030 IOVEC_SET_STRING(iovec[n_iovec++], core_cgroup);
1031 }
1032
1033 if (compose_open_fds(pid, &t) >= 0) {
1034 core_open_fds = strappend("COREDUMP_OPEN_FDS=", t);
1035 free(t);
1036
1037 if (core_open_fds)
1038 IOVEC_SET_STRING(iovec[n_iovec++], core_open_fds);
1039 }
1040
1041 p = procfs_file_alloca(pid, "status");
1042 if (read_full_file(p, &t, NULL) >= 0) {
1043 core_proc_status = strappend("COREDUMP_PROC_STATUS=", t);
1044 free(t);
1045
1046 if (core_proc_status)
1047 IOVEC_SET_STRING(iovec[n_iovec++], core_proc_status);
1048 }
1049
1050 p = procfs_file_alloca(pid, "maps");
1051 if (read_full_file(p, &t, NULL) >= 0) {
1052 core_proc_maps = strappend("COREDUMP_PROC_MAPS=", t);
1053 free(t);
1054
1055 if (core_proc_maps)
1056 IOVEC_SET_STRING(iovec[n_iovec++], core_proc_maps);
1057 }
1058
1059 p = procfs_file_alloca(pid, "limits");
1060 if (read_full_file(p, &t, NULL) >= 0) {
1061 core_proc_limits = strappend("COREDUMP_PROC_LIMITS=", t);
1062 free(t);
1063
1064 if (core_proc_limits)
1065 IOVEC_SET_STRING(iovec[n_iovec++], core_proc_limits);
1066 }
1067
1068 p = procfs_file_alloca(pid, "cgroup");
1069 if (read_full_file(p, &t, NULL) >=0) {
1070 core_proc_cgroup = strappend("COREDUMP_PROC_CGROUP=", t);
1071 free(t);
1072
1073 if (core_proc_cgroup)
1074 IOVEC_SET_STRING(iovec[n_iovec++], core_proc_cgroup);
1075 }
1076
1077 if (get_process_cwd(pid, &t) >= 0) {
1078 core_cwd = strjoina("COREDUMP_CWD=", t);
1079 free(t);
1080
1081 IOVEC_SET_STRING(iovec[n_iovec++], core_cwd);
1082 }
1083
1084 if (get_process_root(pid, &t) >= 0) {
1085 core_root = strjoina("COREDUMP_ROOT=", t);
1086 free(t);
1087
1088 IOVEC_SET_STRING(iovec[n_iovec++], core_root);
1089 }
1090
1091 if (get_process_environ(pid, &t) >= 0) {
1092 core_environ = strappend("COREDUMP_ENVIRON=", t);
1093 free(t);
1094
1095 if (core_environ)
1096 IOVEC_SET_STRING(iovec[n_iovec++], core_environ);
1097 }
1098
1099 core_timestamp = strjoina("COREDUMP_TIMESTAMP=", context[CONTEXT_TIMESTAMP], "000000");
1100 IOVEC_SET_STRING(iovec[n_iovec++], core_timestamp);
1101
1102 IOVEC_SET_STRING(iovec[n_iovec++], "MESSAGE_ID=fc2e22bc6ee647b6b90729ab34a250b1");
1103
1104 assert_cc(2 == LOG_CRIT);
1105 IOVEC_SET_STRING(iovec[n_iovec++], "PRIORITY=2");
1106
1107 assert(n_iovec <= ELEMENTSOF(iovec));
1108
1109 return send_iovec(iovec, n_iovec, STDIN_FILENO);
1110 }
1111
1112 int main(int argc, char *argv[]) {
1113 int r;
1114
1115 /* First, log to a safe place, since we don't know what crashed and it might be journald which we'd rather not
1116 * log to then. */
1117
1118 log_set_target(LOG_TARGET_KMSG);
1119 log_open();
1120
1121 /* Make sure we never enter a loop */
1122 (void) prctl(PR_SET_DUMPABLE, 0);
1123
1124 /* Ignore all parse errors */
1125 (void) parse_config();
1126
1127 log_debug("Selected storage '%s'.", coredump_storage_to_string(arg_storage));
1128 log_debug("Selected compression %s.", yes_no(arg_compress));
1129
1130 r = sd_listen_fds(false);
1131 if (r < 0) {
1132 log_error_errno(r, "Failed to determine number of file descriptor: %m");
1133 goto finish;
1134 }
1135
1136 /* If we got an fd passed, we are running in coredumpd mode. Otherwise we are invoked from the kernel as
1137 * coredump handler */
1138 if (r == 0)
1139 r = process_kernel(argc, argv);
1140 else if (r == 1)
1141 r = process_socket(SD_LISTEN_FDS_START);
1142 else {
1143 log_error("Received unexpected number of file descriptors.");
1144 r = -EINVAL;
1145 }
1146
1147 finish:
1148 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1149 }