2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 2002 Poul-Henning Kamp
5 * Copyright (c) 2002 Networks Associates Technology, Inc.
8 * This software was developed for the FreeBSD Project by Poul-Henning Kamp
9 * and NAI Labs, the Security Research Division of Network Associates, Inc.
10 * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
11 * DARPA CHATS research program.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. The names of the authors may not be used to endorse or promote
22 * products derived from this software without specific prior written
25 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * Copyright (c) 1986, 1992, 1993
38 * The Regents of the University of California. All rights reserved.
40 * Redistribution and use in source and binary forms, with or without
41 * modification, are permitted provided that the following conditions
43 * 1. Redistributions of source code must retain the above copyright
44 * notice, this list of conditions and the following disclaimer.
45 * 2. Redistributions in binary form must reproduce the above copyright
46 * notice, this list of conditions and the following disclaimer in the
47 * documentation and/or other materials provided with the distribution.
48 * 3. Neither the name of the University nor the names of its contributors
49 * may be used to endorse or promote products derived from this software
50 * without specific prior written permission.
52 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
53 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
56 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65 #include <sys/cdefs.h>
66 __FBSDID("$FreeBSD$");
68 #include <sys/param.h>
70 #include <sys/kerneldump.h>
71 #include <sys/mount.h>
74 #include <capsicum_helpers.h>
93 #include <libcasper.h>
94 #include <casper/cap_fileargs.h>
95 #include <casper/cap_syslog.h>
99 /* The size of the buffer used for I/O. */
100 #define BUFFERSIZE (1024*1024)
103 #define STATUS_GOOD 1
104 #define STATUS_UNKNOWN 2
106 static cap_channel_t *capsyslog;
107 static fileargs_t *capfa;
108 static bool checkfor, compress, uncompress, clear, force, keep; /* flags */
110 static int nfound, nsaved, nerr; /* statistics */
113 extern FILE *zdopen(int, const char *);
115 static sig_atomic_t got_siginfo;
116 static void infohandler(int);
119 logmsg(int pri, const char *fmt, ...)
124 if (capsyslog != NULL)
125 cap_vsyslog(capsyslog, pri, fmt, ap);
127 vsyslog(pri, fmt, ap);
132 xfopenat(int dirfd, const char *path, int flags, const char *modestr, ...)
139 if ((flags & O_CREAT) == O_CREAT) {
140 va_start(ap, modestr);
141 mode = (mode_t)va_arg(ap, int);
146 fd = openat(dirfd, path, flags, mode);
149 fp = fdopen(fd, modestr);
159 printheader(xo_handle_t *xo, const struct kerneldumpheader *h,
160 const char *device, int bounds, const int status)
166 const char *stat_str;
167 const char *comp_str;
170 xo_emit_h(xo, "{Lwc:Dump header from device}{:dump_device/%s}\n",
172 xo_emit_h(xo, "{P: }{Lwc:Architecture}{:architecture/%s}\n",
175 "{P: }{Lwc:Architecture Version}{:architecture_version/%u}\n",
176 dtoh32(h->architectureversion));
177 dumplen = dtoh64(h->dumplength);
178 xo_emit_h(xo, "{P: }{Lwc:Dump Length}{:dump_length_bytes/%lld}\n",
180 xo_emit_h(xo, "{P: }{Lwc:Blocksize}{:blocksize/%d}\n",
181 dtoh32(h->blocksize));
182 switch (h->compression) {
183 case KERNELDUMP_COMP_NONE:
186 case KERNELDUMP_COMP_GZIP:
189 case KERNELDUMP_COMP_ZSTD:
196 xo_emit_h(xo, "{P: }{Lwc:Compression}{:compression/%s}\n", comp_str);
197 t = dtoh64(h->dumptime);
198 localtime_r(&t, &tm);
199 if (strftime(time_str, sizeof(time_str), "%F %T %z", &tm) == 0)
201 xo_emit_h(xo, "{P: }{Lwc:Dumptime}{:dumptime/%s}\n", time_str);
202 xo_emit_h(xo, "{P: }{Lwc:Hostname}{:hostname/%s}\n", h->hostname);
203 xo_emit_h(xo, "{P: }{Lwc:Magic}{:magic/%s}\n", h->magic);
204 xo_emit_h(xo, "{P: }{Lwc:Version String}{:version_string/%s}",
206 xo_emit_h(xo, "{P: }{Lwc:Panic String}{:panic_string/%s}\n",
208 xo_emit_h(xo, "{P: }{Lwc:Dump Parity}{:dump_parity/%u}\n", h->parity);
209 xo_emit_h(xo, "{P: }{Lwc:Bounds}{:bounds/%d}\n", bounds);
219 stat_str = "unknown";
222 xo_emit_h(xo, "{P: }{Lwc:Dump Status}{:dump_status/%s}\n", stat_str);
227 getbounds(int savedirfd)
234 * If we are just checking, then we haven't done a chdir to the dump
235 * directory and we should not try to read a bounds file.
242 if ((fp = xfopenat(savedirfd, "bounds", O_RDONLY, "r")) == NULL) {
244 printf("unable to open bounds file, using 0\n");
247 if (fgets(buf, sizeof(buf), fp) == NULL) {
249 logmsg(LOG_WARNING, "bounds file is empty, using 0");
251 logmsg(LOG_WARNING, "bounds file: %s", strerror(errno));
257 ret = (int)strtol(buf, NULL, 10);
258 if (ret == 0 && (errno == EINVAL || errno == ERANGE))
259 logmsg(LOG_WARNING, "invalid value found in bounds, using 0");
265 writebounds(int savedirfd, int bounds)
269 if ((fp = xfopenat(savedirfd, "bounds", O_WRONLY | O_CREAT | O_TRUNC,
270 "w", 0644)) == NULL) {
271 logmsg(LOG_WARNING, "unable to write to bounds file: %m");
276 printf("bounds number: %d\n", bounds);
278 fprintf(fp, "%d\n", bounds);
283 writekey(int savedirfd, const char *keyname, uint8_t *dumpkey,
284 uint32_t dumpkeysize)
288 fd = openat(savedirfd, keyname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
290 logmsg(LOG_ERR, "Unable to open %s to write the key: %m.",
295 if (write(fd, dumpkey, dumpkeysize) != (ssize_t)dumpkeysize) {
296 logmsg(LOG_ERR, "Unable to write the key to %s: %m.", keyname);
306 file_size(int savedirfd, const char *path)
310 /* Ignore all errors, this file may not exist. */
311 if (fstatat(savedirfd, path, &sb, 0) == -1)
317 saved_dump_size(int savedirfd, int bounds)
319 static char path[PATH_MAX];
324 (void)snprintf(path, sizeof(path), "info.%d", bounds);
325 dumpsize += file_size(savedirfd, path);
326 (void)snprintf(path, sizeof(path), "vmcore.%d", bounds);
327 dumpsize += file_size(savedirfd, path);
328 (void)snprintf(path, sizeof(path), "vmcore.%d.gz", bounds);
329 dumpsize += file_size(savedirfd, path);
330 (void)snprintf(path, sizeof(path), "vmcore.%d.zst", bounds);
331 dumpsize += file_size(savedirfd, path);
332 (void)snprintf(path, sizeof(path), "textdump.tar.%d", bounds);
333 dumpsize += file_size(savedirfd, path);
334 (void)snprintf(path, sizeof(path), "textdump.tar.%d.gz", bounds);
335 dumpsize += file_size(savedirfd, path);
341 saved_dump_remove(int savedirfd, int bounds)
343 static char path[PATH_MAX];
345 (void)snprintf(path, sizeof(path), "info.%d", bounds);
346 (void)unlinkat(savedirfd, path, 0);
347 (void)snprintf(path, sizeof(path), "vmcore.%d", bounds);
348 (void)unlinkat(savedirfd, path, 0);
349 (void)snprintf(path, sizeof(path), "vmcore.%d.gz", bounds);
350 (void)unlinkat(savedirfd, path, 0);
351 (void)snprintf(path, sizeof(path), "vmcore.%d.zst", bounds);
352 (void)unlinkat(savedirfd, path, 0);
353 (void)snprintf(path, sizeof(path), "textdump.tar.%d", bounds);
354 (void)unlinkat(savedirfd, path, 0);
355 (void)snprintf(path, sizeof(path), "textdump.tar.%d.gz", bounds);
356 (void)unlinkat(savedirfd, path, 0);
360 symlinks_remove(int savedirfd)
363 (void)unlinkat(savedirfd, "info.last", 0);
364 (void)unlinkat(savedirfd, "key.last", 0);
365 (void)unlinkat(savedirfd, "vmcore.last", 0);
366 (void)unlinkat(savedirfd, "vmcore.last.gz", 0);
367 (void)unlinkat(savedirfd, "vmcore.last.zst", 0);
368 (void)unlinkat(savedirfd, "vmcore_encrypted.last", 0);
369 (void)unlinkat(savedirfd, "vmcore_encrypted.last.gz", 0);
370 (void)unlinkat(savedirfd, "textdump.tar.last", 0);
371 (void)unlinkat(savedirfd, "textdump.tar.last.gz", 0);
375 * Check that sufficient space is available on the disk that holds the
379 check_space(const char *savedir, int savedirfd, off_t dumpsize, int bounds)
384 off_t available, minfree, spacefree, totfree, needed;
386 if (fstatfs(savedirfd, &fsbuf) < 0) {
387 logmsg(LOG_ERR, "%s: %m", savedir);
390 spacefree = ((off_t) fsbuf.f_bavail * fsbuf.f_bsize) / 1024;
391 totfree = ((off_t) fsbuf.f_bfree * fsbuf.f_bsize) / 1024;
393 if ((fp = xfopenat(savedirfd, "minfree", O_RDONLY, "r")) == NULL)
396 if (fgets(buf, sizeof(buf), fp) == NULL)
402 minfree = strtoll(buf, &endp, 10);
403 if (minfree == 0 && errno != 0)
406 while (*endp != '\0' && isspace(*endp))
408 if (*endp != '\0' || minfree < 0)
413 "`minfree` didn't contain a valid size "
414 "(`%s`). Defaulting to 0", buf);
419 available = minfree > 0 ? spacefree - minfree : totfree;
420 needed = dumpsize / 1024 + 2; /* 2 for info file */
421 needed -= saved_dump_size(savedirfd, bounds);
422 if (available < needed) {
424 "no dump: not enough free space on device (need at least "
425 "%jdkB for dump; %jdkB available; %jdkB reserved)",
427 (intmax_t)available + minfree,
431 if (spacefree - needed < 0)
433 "dump performed, but free space threshold crossed");
438 compare_magic(const struct kerneldumpheader *kdh, const char *magic)
441 return (strncmp(kdh->magic, magic, sizeof(kdh->magic)) == 0);
444 #define BLOCKSIZE (1<<12)
445 #define BLOCKMASK (~(BLOCKSIZE-1))
448 sparsefwrite(const char *buf, size_t nr, FILE *fp)
452 for (nw = 0; nw < nr; nw = he) {
453 /* find a contiguous block of zeroes */
454 for (hs = nw; hs < nr; hs += BLOCKSIZE) {
455 for (he = hs; he < nr && buf[he] == 0; ++he)
457 /* is the hole long enough to matter? */
458 if (he >= hs + BLOCKSIZE)
462 /* back down to a block boundary */
466 * 1) Don't go beyond the end of the buffer.
467 * 2) If the end of the buffer is less than
468 * BLOCKSIZE bytes away, we're at the end
469 * of the file, so just grab what's left.
471 if (hs + BLOCKSIZE > nr)
475 * At this point, we have a partial ordering:
476 * nw <= hs <= he <= nr
477 * If hs > nw, buf[nw..hs] contains non-zero
478 * data. If he > hs, buf[hs..he] is all zeroes.
481 if (fwrite(buf + nw, hs - nw, 1, fp) != 1)
484 if (fseeko(fp, he - hs, SEEK_CUR) == -1)
492 static size_t zbufsize;
495 GunzipWrite(z_stream *z, char *in, size_t insize, FILE *fp)
497 static bool firstblock = true; /* XXX not re-entrable/usable */
498 const size_t hdrlen = 10;
503 z->avail_in = insize;
505 * Since contrib/zlib for some reason is compiled
506 * without GUNZIP define, we need to skip the gzip
507 * header manually. Kernel puts minimal 10 byte
508 * header, see sys/kern/subr_compressor.c:gz_reset().
511 z->next_in += hdrlen;
512 z->avail_in -= hdrlen;
517 z->avail_out = zbufsize;
518 rv = inflate(z, Z_NO_FLUSH);
519 if (rv != Z_OK && rv != Z_STREAM_END) {
520 logmsg(LOG_ERR, "decompression failed: %s", z->msg);
523 w = sparsefwrite(zbuf, zbufsize - z->avail_out, fp);
524 if (w < zbufsize - z->avail_out)
527 } while (z->avail_in > 0 && rv != Z_STREAM_END);
533 ZstdWrite(ZSTD_DCtx *Zctx, char *in, size_t insize, FILE *fp)
545 Zout.size = zbufsize;
547 rv = ZSTD_decompressStream(Zctx, &Zout, &Zin);
548 if (ZSTD_isError(rv)) {
549 logmsg(LOG_ERR, "decompression failed: %s",
550 ZSTD_getErrorName(rv));
553 w = sparsefwrite(zbuf, Zout.pos, fp);
557 } while (Zin.pos < Zin.size && rv != 0);
563 DoRegularFile(int fd, off_t dumpsize, u_int sectorsize, bool sparse,
564 uint8_t compression, char *buf, const char *device,
565 const char *filename, FILE *fp)
569 off_t dmpcnt, origsize;
570 z_stream z; /* gzip */
571 ZSTD_DCtx *Zctx; /* zstd */
575 if (compression == KERNELDUMP_COMP_GZIP) {
576 memset(&z, 0, sizeof(z));
579 if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
580 logmsg(LOG_ERR, "failed to initialize zlib: %s", z.msg);
583 zbufsize = BUFFERSIZE;
584 } else if (compression == KERNELDUMP_COMP_ZSTD) {
585 if ((Zctx = ZSTD_createDCtx()) == NULL) {
586 logmsg(LOG_ERR, "failed to initialize zstd");
589 zbufsize = ZSTD_DStreamOutSize();
592 if ((zbuf = malloc(zbufsize)) == NULL) {
593 logmsg(LOG_ERR, "failed to alloc decompression buffer");
597 while (dumpsize > 0) {
599 if (wl > (size_t)dumpsize)
601 nr = read(fd, buf, roundup(wl, sectorsize));
602 if (nr != roundup(wl, sectorsize)) {
605 "WARNING: EOF on dump device");
607 logmsg(LOG_ERR, "read error on %s: %m", device);
611 if (compression == KERNELDUMP_COMP_GZIP)
612 nw = GunzipWrite(&z, buf, nr, fp);
613 else if (compression == KERNELDUMP_COMP_ZSTD)
614 nw = ZstdWrite(Zctx, buf, nr, fp);
616 nw = fwrite(buf, 1, wl, fp);
618 nw = sparsefwrite(buf, wl, fp);
619 if (nw < 0 || (compression == KERNELDUMP_COMP_NONE &&
622 "write error on %s file: %m", filename);
624 "WARNING: vmcore may be incomplete");
630 printf("%llu\r", (unsigned long long)dmpcnt);
635 printf("%s %.1lf%%\n", filename, (100.0 - (100.0 *
636 (double)dumpsize / (double)origsize)));
644 * Specialized version of dump-reading logic for use with textdumps, which
645 * are written backwards from the end of the partition, and must be reversed
646 * before being written to the file. Textdumps are small, so do a bit less
647 * work to optimize/sparsify.
650 DoTextdumpFile(int fd, off_t dumpsize, off_t lasthd, char *buf,
651 const char *device, const char *filename, FILE *fp)
654 off_t dmpcnt, totsize;
659 if ((dumpsize % wl) != 0) {
660 logmsg(LOG_ERR, "textdump uneven multiple of 512 on %s",
665 while (dumpsize > 0) {
666 nr = pread(fd, buf, wl, lasthd - (totsize - dumpsize) - wl);
670 "WARNING: EOF on dump device");
672 logmsg(LOG_ERR, "read error on %s: %m", device);
676 nw = fwrite(buf, 1, wl, fp);
679 "write error on %s file: %m", filename);
681 "WARNING: textdump may be incomplete");
687 printf("%llu\r", (unsigned long long)dmpcnt);
696 DoFile(const char *savedir, int savedirfd, const char *device)
698 xo_handle_t *xostdout, *xoinfo;
699 static char infoname[PATH_MAX], corename[PATH_MAX], linkname[PATH_MAX];
700 static char keyname[PATH_MAX];
701 static char *buf = NULL;
703 struct kerneldumpheader kdhf, kdhl;
705 off_t mediasize, dumpextent, dumplength, firsthd, lasthd;
707 int fdcore, fddev, error;
709 u_int sectorsize, xostyle;
710 uint32_t dumpkeysize;
711 bool iscompressed, isencrypted, istextdump, ret;
713 bounds = getbounds(savedirfd);
716 status = STATUS_UNKNOWN;
718 xostdout = xo_create_to_file(stdout, XO_STYLE_TEXT, 0);
719 if (xostdout == NULL) {
720 logmsg(LOG_ERR, "%s: %m", infoname);
724 if (maxdumps > 0 && bounds == maxdumps)
728 buf = malloc(BUFFERSIZE);
730 logmsg(LOG_ERR, "%m");
736 printf("checking for kernel dump on device %s\n", device);
738 fddev = fileargs_open(capfa, device);
740 logmsg(LOG_ERR, "%s: %m", device);
744 error = ioctl(fddev, DIOCGMEDIASIZE, &mediasize);
746 error = ioctl(fddev, DIOCGSECTORSIZE, §orsize);
749 "couldn't find media and/or sector size of %s: %m", device);
754 printf("mediasize = %lld bytes\n", (long long)mediasize);
755 printf("sectorsize = %u bytes\n", sectorsize);
758 if (sectorsize < sizeof(kdhl)) {
760 "Sector size is less the kernel dump header %zu",
765 lasthd = mediasize - sectorsize;
766 temp = malloc(sectorsize);
768 logmsg(LOG_ERR, "%m");
771 if (lseek(fddev, lasthd, SEEK_SET) != lasthd ||
772 read(fddev, temp, sectorsize) != (ssize_t)sectorsize) {
774 "error reading last dump header at offset %lld in %s: %m",
775 (long long)lasthd, device);
778 memcpy(&kdhl, temp, sizeof(kdhl));
779 iscompressed = istextdump = false;
780 if (compare_magic(&kdhl, TEXTDUMPMAGIC)) {
782 printf("textdump magic on last dump header on %s\n",
785 if (dtoh32(kdhl.version) != KERNELDUMP_TEXT_VERSION) {
787 "unknown version (%d) in last dump header on %s",
788 dtoh32(kdhl.version), device);
794 } else if (compare_magic(&kdhl, KERNELDUMPMAGIC)) {
795 if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
797 "unknown version (%d) in last dump header on %s",
798 dtoh32(kdhl.version), device);
804 switch (kdhl.compression) {
805 case KERNELDUMP_COMP_NONE:
808 case KERNELDUMP_COMP_GZIP:
809 case KERNELDUMP_COMP_ZSTD:
810 if (compress && verbose)
811 printf("dump is already compressed\n");
812 if (uncompress && verbose)
813 printf("dump to be uncompressed\n");
818 logmsg(LOG_ERR, "unknown compression type %d on %s",
819 kdhl.compression, device);
824 printf("magic mismatch on last dump header on %s\n",
831 if (compare_magic(&kdhl, KERNELDUMPMAGIC_CLEARED)) {
833 printf("forcing magic on %s\n", device);
834 memcpy(kdhl.magic, KERNELDUMPMAGIC, sizeof(kdhl.magic));
836 logmsg(LOG_ERR, "unable to force dump - bad magic");
839 if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
841 "unknown version (%d) in last dump header on %s",
842 dtoh32(kdhl.version), device);
854 if (kerneldump_parity(&kdhl)) {
856 "parity error on last dump header on %s", device);
862 dumpextent = dtoh64(kdhl.dumpextent);
863 dumplength = dtoh64(kdhl.dumplength);
864 dumpkeysize = dtoh32(kdhl.dumpkeysize);
865 firsthd = lasthd - dumpextent - sectorsize - dumpkeysize;
866 if (lseek(fddev, firsthd, SEEK_SET) != firsthd ||
867 read(fddev, temp, sectorsize) != (ssize_t)sectorsize) {
869 "error reading first dump header at offset %lld in %s: %m",
870 (long long)firsthd, device);
874 memcpy(&kdhf, temp, sizeof(kdhf));
877 printf("First dump headers:\n");
878 printheader(xostdout, &kdhf, device, bounds, -1);
880 printf("\nLast dump headers:\n");
881 printheader(xostdout, &kdhl, device, bounds, -1);
885 if (memcmp(&kdhl, &kdhf, sizeof(kdhl))) {
887 "first and last dump headers disagree on %s", device);
893 status = STATUS_GOOD;
897 printf("A dump exists on %s\n", device);
902 if (kdhl.panicstring[0] != '\0')
903 logmsg(LOG_ALERT, "reboot after panic: %.*s",
904 (int)sizeof(kdhl.panicstring), kdhl.panicstring);
906 logmsg(LOG_ALERT, "reboot");
909 printf("Checking for available free space\n");
911 if (!check_space(savedir, savedirfd, dumplength, bounds)) {
916 writebounds(savedirfd, bounds + 1);
918 saved_dump_remove(savedirfd, bounds);
920 snprintf(infoname, sizeof(infoname), "info.%d", bounds);
923 * Create or overwrite any existing dump header files.
925 if ((info = xfopenat(savedirfd, infoname,
926 O_WRONLY | O_CREAT | O_TRUNC, "w", 0600)) == NULL) {
927 logmsg(LOG_ERR, "open(%s): %m", infoname);
932 isencrypted = (dumpkeysize > 0);
934 snprintf(corename, sizeof(corename), "%s.%d.gz",
935 istextdump ? "textdump.tar" :
936 (isencrypted ? "vmcore_encrypted" : "vmcore"), bounds);
937 else if (iscompressed && !isencrypted && !uncompress)
938 snprintf(corename, sizeof(corename), "vmcore.%d.%s", bounds,
939 (kdhl.compression == KERNELDUMP_COMP_GZIP) ? "gz" : "zst");
941 snprintf(corename, sizeof(corename), "%s.%d",
942 istextdump ? "textdump.tar" :
943 (isencrypted ? "vmcore_encrypted" : "vmcore"), bounds);
944 fdcore = openat(savedirfd, corename, O_WRONLY | O_CREAT | O_TRUNC,
947 logmsg(LOG_ERR, "open(%s): %m", corename);
954 core = zdopen(fdcore, "w");
956 core = fdopen(fdcore, "w");
958 logmsg(LOG_ERR, "%s: %m", corename);
966 xostyle = xo_get_style(NULL);
967 xoinfo = xo_create_to_file(info, xostyle, 0);
968 if (xoinfo == NULL) {
969 logmsg(LOG_ERR, "%s: %m", infoname);
974 xo_open_container_h(xoinfo, "crashdump");
977 printheader(xostdout, &kdhl, device, bounds, status);
979 printheader(xoinfo, &kdhl, device, bounds, status);
980 xo_close_container_h(xoinfo, "crashdump");
986 dumpkey = calloc(1, dumpkeysize);
987 if (dumpkey == NULL) {
988 logmsg(LOG_ERR, "Unable to allocate kernel dump key.");
993 if (read(fddev, dumpkey, dumpkeysize) != (ssize_t)dumpkeysize) {
994 logmsg(LOG_ERR, "Unable to read kernel dump key: %m.");
999 snprintf(keyname, sizeof(keyname), "key.%d", bounds);
1000 ret = writekey(savedirfd, keyname, dumpkey, dumpkeysize);
1001 explicit_bzero(dumpkey, dumpkeysize);
1008 logmsg(LOG_NOTICE, "writing %s%score to %s/%s",
1009 isencrypted ? "encrypted " : "", compress ? "compressed " : "",
1013 if (DoTextdumpFile(fddev, dumplength, lasthd, buf, device,
1014 corename, core) < 0)
1017 if (DoRegularFile(fddev, dumplength, sectorsize,
1018 !(compress || iscompressed || isencrypted),
1019 uncompress ? kdhl.compression : KERNELDUMP_COMP_NONE,
1020 buf, device, corename, core) < 0) {
1027 if (fclose(core) < 0) {
1028 logmsg(LOG_ERR, "error on %s: %m", corename);
1033 symlinks_remove(savedirfd);
1034 if (symlinkat(infoname, savedirfd, "info.last") == -1) {
1035 logmsg(LOG_WARNING, "unable to create symlink %s/%s: %m",
1036 savedir, "info.last");
1039 if (symlinkat(keyname, savedirfd, "key.last") == -1) {
1041 "unable to create symlink %s/%s: %m", savedir,
1045 if ((iscompressed && !uncompress) || compress) {
1046 snprintf(linkname, sizeof(linkname), "%s.last.%s",
1047 istextdump ? "textdump.tar" :
1048 (isencrypted ? "vmcore_encrypted" : "vmcore"),
1049 (kdhl.compression == KERNELDUMP_COMP_ZSTD) ? "zst" : "gz");
1051 snprintf(linkname, sizeof(linkname), "%s.last",
1052 istextdump ? "textdump.tar" :
1053 (isencrypted ? "vmcore_encrypted" : "vmcore"));
1055 if (symlinkat(corename, savedirfd, linkname) == -1) {
1056 logmsg(LOG_WARNING, "unable to create symlink %s/%s: %m",
1063 printf("dump saved\n");
1068 printf("clearing dump header\n");
1069 memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof(kdhl.magic));
1070 memcpy(temp, &kdhl, sizeof(kdhl));
1071 if (lseek(fddev, lasthd, SEEK_SET) != lasthd ||
1072 write(fddev, temp, sectorsize) != (ssize_t)sectorsize)
1074 "error while clearing the dump header: %m");
1076 xo_close_container_h(xostdout, "crashdump");
1077 xo_finish_h(xostdout);
1092 /* Prepend "/dev/" to any arguments that don't already have it */
1094 devify(int argc, char **argv)
1099 devs = malloc(argc * sizeof(*argv));
1101 logmsg(LOG_ERR, "malloc(): %m");
1104 for (i = 0; i < argc; i++) {
1105 if (strncmp(argv[i], _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
1106 devs[i] = strdup(argv[i]);
1110 fullpath = malloc(PATH_MAX);
1111 if (fullpath == NULL) {
1112 logmsg(LOG_ERR, "malloc(): %m");
1115 l = snprintf(fullpath, PATH_MAX, "%s%s", _PATH_DEV,
1118 logmsg(LOG_ERR, "snprintf(): %m");
1120 } else if (l >= PATH_MAX) {
1121 logmsg(LOG_ERR, "device name too long");
1131 enum_dumpdevs(int *argcp)
1138 * We cannot use getfsent(3) in capability mode, so we must
1139 * scan /etc/fstab and build up a list of candidate devices
1140 * before proceeding.
1144 argv = malloc(n * sizeof(*argv));
1146 logmsg(LOG_ERR, "malloc(): %m");
1153 if (strcmp(fsp->fs_vfstype, "swap") != 0 &&
1154 strcmp(fsp->fs_vfstype, "dump") != 0)
1158 argv = realloc(argv, n * sizeof(*argv));
1160 logmsg(LOG_ERR, "realloc(): %m");
1164 argv[argc] = strdup(fsp->fs_spec);
1165 if (argv[argc] == NULL) {
1166 logmsg(LOG_ERR, "strdup(): %m");
1176 init_caps(int argc, char **argv)
1178 cap_rights_t rights;
1179 cap_channel_t *capcas;
1181 capcas = cap_init();
1182 if (capcas == NULL) {
1183 logmsg(LOG_ERR, "cap_init(): %m");
1187 * The fileargs capability does not currently provide a way to limit
1190 (void)cap_rights_init(&rights, CAP_PREAD, CAP_WRITE, CAP_IOCTL);
1191 capfa = fileargs_init(argc, argv, checkfor || keep ? O_RDONLY : O_RDWR,
1192 0, &rights, FA_OPEN);
1193 if (capfa == NULL) {
1194 logmsg(LOG_ERR, "fileargs_init(): %m");
1197 caph_cache_catpages();
1198 caph_cache_tzdata();
1199 if (caph_enter_casper() != 0) {
1200 logmsg(LOG_ERR, "caph_enter_casper(): %m");
1203 capsyslog = cap_service_open(capcas, "system.syslog");
1204 if (capsyslog == NULL) {
1205 logmsg(LOG_ERR, "cap_service_open(system.syslog): %m");
1214 xo_error("%s\n%s\n%s\n",
1215 "usage: savecore -c [-v] [device ...]",
1216 " savecore -C [-v] [device ...]",
1217 " savecore [-fkvz] [-m maxdumps] [directory [device ...]]");
1222 main(int argc, char **argv)
1224 cap_rights_t rights;
1225 const char *savedir;
1227 int i, ch, error, savedirfd;
1229 checkfor = compress = clear = force = keep = false;
1231 nfound = nsaved = nerr = 0;
1234 openlog("savecore", LOG_PERROR, LOG_DAEMON);
1235 signal(SIGINFO, infohandler);
1237 argc = xo_parse_args(argc, argv);
1241 while ((ch = getopt(argc, argv, "Ccfkm:uvz")) != -1)
1256 maxdumps = atoi(optarg);
1257 if (maxdumps <= 0) {
1258 logmsg(LOG_ERR, "Invalid maxdump value");
1275 if (checkfor && (clear || force || keep))
1277 if (clear && (compress || keep))
1279 if (maxdumps > 0 && (checkfor || clear))
1281 if (compress && uncompress)
1285 if (argc >= 1 && !checkfor && !clear) {
1286 error = chdir(argv[0]);
1288 logmsg(LOG_ERR, "chdir(%s): %m", argv[0]);
1296 devs = enum_dumpdevs(&argc);
1298 devs = devify(argc, argv);
1300 savedirfd = open(savedir, O_RDONLY | O_DIRECTORY);
1301 if (savedirfd < 0) {
1302 logmsg(LOG_ERR, "open(%s): %m", savedir);
1305 (void)cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL, CAP_FSTATAT,
1306 CAP_FSTATFS, CAP_PREAD, CAP_SYMLINKAT, CAP_FTRUNCATE, CAP_UNLINKAT,
1308 if (caph_rights_limit(savedirfd, &rights) < 0) {
1309 logmsg(LOG_ERR, "cap_rights_limit(): %m");
1313 /* Enter capability mode. */
1314 init_caps(argc, devs);
1316 for (i = 0; i < argc; i++)
1317 DoFile(savedir, savedirfd, devs[i]);
1319 /* Emit minimal output. */
1323 printf("No dump exists\n");
1327 logmsg(LOG_WARNING, "no dumps found");
1328 } else if (nsaved == 0) {
1332 "unsaved dumps found but not saved");
1335 logmsg(LOG_WARNING, "no unsaved dumps found");
1342 infohandler(int sig __unused)