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 nw += sparsefwrite(zbuf, zbufsize - z->avail_out, fp);
524 } while (z->avail_in > 0 && rv != Z_STREAM_END);
530 ZstdWrite(ZSTD_DCtx *Zctx, char *in, size_t insize, FILE *fp)
542 Zout.size = zbufsize;
544 rv = ZSTD_decompressStream(Zctx, &Zout, &Zin);
545 if (ZSTD_isError(rv)) {
546 logmsg(LOG_ERR, "decompression failed: %s",
547 ZSTD_getErrorName(rv));
550 nw += sparsefwrite(zbuf, Zout.pos, fp);
551 } while (Zin.pos < Zin.size && rv != 0);
557 DoRegularFile(int fd, off_t dumpsize, u_int sectorsize, bool sparse,
558 uint8_t compression, char *buf, const char *device,
559 const char *filename, FILE *fp)
562 off_t dmpcnt, origsize;
563 z_stream z; /* gzip */
564 ZSTD_DCtx *Zctx; /* zstd */
568 if (compression == KERNELDUMP_COMP_GZIP) {
569 memset(&z, 0, sizeof(z));
572 if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
573 logmsg(LOG_ERR, "failed to initialize zlib: %s", z.msg);
576 zbufsize = BUFFERSIZE;
577 } else if (compression == KERNELDUMP_COMP_ZSTD) {
578 if ((Zctx = ZSTD_createDCtx()) == NULL) {
579 logmsg(LOG_ERR, "failed to initialize zstd");
582 zbufsize = ZSTD_DStreamOutSize();
585 if ((zbuf = malloc(zbufsize)) == NULL) {
586 logmsg(LOG_ERR, "failed to alloc decompression buffer");
590 while (dumpsize > 0) {
592 if (wl > (size_t)dumpsize)
594 nr = read(fd, buf, roundup(wl, sectorsize));
595 if (nr != roundup(wl, sectorsize)) {
598 "WARNING: EOF on dump device");
600 logmsg(LOG_ERR, "read error on %s: %m", device);
604 if (compression == KERNELDUMP_COMP_GZIP)
605 nw = GunzipWrite(&z, buf, nr, fp);
606 else if (compression == KERNELDUMP_COMP_ZSTD)
607 nw = ZstdWrite(Zctx, buf, nr, fp);
609 nw = fwrite(buf, 1, wl, fp);
611 nw = sparsefwrite(buf, wl, fp);
612 if ((compression == KERNELDUMP_COMP_NONE && nw != wl) ||
613 (compression != KERNELDUMP_COMP_NONE && nw < 0)) {
615 "write error on %s file: %m", filename);
617 "WARNING: vmcore may be incomplete");
623 printf("%llu\r", (unsigned long long)dmpcnt);
628 printf("%s %.1lf%%\n", filename, (100.0 - (100.0 *
629 (double)dumpsize / (double)origsize)));
637 * Specialized version of dump-reading logic for use with textdumps, which
638 * are written backwards from the end of the partition, and must be reversed
639 * before being written to the file. Textdumps are small, so do a bit less
640 * work to optimize/sparsify.
643 DoTextdumpFile(int fd, off_t dumpsize, off_t lasthd, char *buf,
644 const char *device, const char *filename, FILE *fp)
647 off_t dmpcnt, totsize;
652 if ((dumpsize % wl) != 0) {
653 logmsg(LOG_ERR, "textdump uneven multiple of 512 on %s",
658 while (dumpsize > 0) {
659 nr = pread(fd, buf, wl, lasthd - (totsize - dumpsize) - wl);
663 "WARNING: EOF on dump device");
665 logmsg(LOG_ERR, "read error on %s: %m", device);
669 nw = fwrite(buf, 1, wl, fp);
672 "write error on %s file: %m", filename);
674 "WARNING: textdump may be incomplete");
680 printf("%llu\r", (unsigned long long)dmpcnt);
689 DoFile(const char *savedir, int savedirfd, const char *device)
691 xo_handle_t *xostdout, *xoinfo;
692 static char infoname[PATH_MAX], corename[PATH_MAX], linkname[PATH_MAX];
693 static char keyname[PATH_MAX];
694 static char *buf = NULL;
696 struct kerneldumpheader kdhf, kdhl;
698 off_t mediasize, dumpextent, dumplength, firsthd, lasthd;
700 int fdcore, fddev, error;
702 u_int sectorsize, xostyle;
703 uint32_t dumpkeysize;
704 bool iscompressed, isencrypted, istextdump, ret;
706 bounds = getbounds(savedirfd);
709 status = STATUS_UNKNOWN;
711 xostdout = xo_create_to_file(stdout, XO_STYLE_TEXT, 0);
712 if (xostdout == NULL) {
713 logmsg(LOG_ERR, "%s: %m", infoname);
717 if (maxdumps > 0 && bounds == maxdumps)
721 buf = malloc(BUFFERSIZE);
723 logmsg(LOG_ERR, "%m");
729 printf("checking for kernel dump on device %s\n", device);
731 fddev = fileargs_open(capfa, device);
733 logmsg(LOG_ERR, "%s: %m", device);
737 error = ioctl(fddev, DIOCGMEDIASIZE, &mediasize);
739 error = ioctl(fddev, DIOCGSECTORSIZE, §orsize);
742 "couldn't find media and/or sector size of %s: %m", device);
747 printf("mediasize = %lld bytes\n", (long long)mediasize);
748 printf("sectorsize = %u bytes\n", sectorsize);
751 if (sectorsize < sizeof(kdhl)) {
753 "Sector size is less the kernel dump header %zu",
758 lasthd = mediasize - sectorsize;
759 temp = malloc(sectorsize);
761 logmsg(LOG_ERR, "%m");
764 if (lseek(fddev, lasthd, SEEK_SET) != lasthd ||
765 read(fddev, temp, sectorsize) != (ssize_t)sectorsize) {
767 "error reading last dump header at offset %lld in %s: %m",
768 (long long)lasthd, device);
771 memcpy(&kdhl, temp, sizeof(kdhl));
772 iscompressed = istextdump = false;
773 if (compare_magic(&kdhl, TEXTDUMPMAGIC)) {
775 printf("textdump magic on last dump header on %s\n",
778 if (dtoh32(kdhl.version) != KERNELDUMP_TEXT_VERSION) {
780 "unknown version (%d) in last dump header on %s",
781 dtoh32(kdhl.version), device);
787 } else if (compare_magic(&kdhl, KERNELDUMPMAGIC)) {
788 if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
790 "unknown version (%d) in last dump header on %s",
791 dtoh32(kdhl.version), device);
797 switch (kdhl.compression) {
798 case KERNELDUMP_COMP_NONE:
801 case KERNELDUMP_COMP_GZIP:
802 case KERNELDUMP_COMP_ZSTD:
803 if (compress && verbose)
804 printf("dump is already compressed\n");
805 if (uncompress && verbose)
806 printf("dump to be uncompressed\n");
811 logmsg(LOG_ERR, "unknown compression type %d on %s",
812 kdhl.compression, device);
817 printf("magic mismatch on last dump header on %s\n",
824 if (compare_magic(&kdhl, KERNELDUMPMAGIC_CLEARED)) {
826 printf("forcing magic on %s\n", device);
827 memcpy(kdhl.magic, KERNELDUMPMAGIC, sizeof(kdhl.magic));
829 logmsg(LOG_ERR, "unable to force dump - bad magic");
832 if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
834 "unknown version (%d) in last dump header on %s",
835 dtoh32(kdhl.version), device);
847 if (kerneldump_parity(&kdhl)) {
849 "parity error on last dump header on %s", device);
855 dumpextent = dtoh64(kdhl.dumpextent);
856 dumplength = dtoh64(kdhl.dumplength);
857 dumpkeysize = dtoh32(kdhl.dumpkeysize);
858 firsthd = lasthd - dumpextent - sectorsize - dumpkeysize;
859 if (lseek(fddev, firsthd, SEEK_SET) != firsthd ||
860 read(fddev, temp, sectorsize) != (ssize_t)sectorsize) {
862 "error reading first dump header at offset %lld in %s: %m",
863 (long long)firsthd, device);
867 memcpy(&kdhf, temp, sizeof(kdhf));
870 printf("First dump headers:\n");
871 printheader(xostdout, &kdhf, device, bounds, -1);
873 printf("\nLast dump headers:\n");
874 printheader(xostdout, &kdhl, device, bounds, -1);
878 if (memcmp(&kdhl, &kdhf, sizeof(kdhl))) {
880 "first and last dump headers disagree on %s", device);
886 status = STATUS_GOOD;
890 printf("A dump exists on %s\n", device);
895 if (kdhl.panicstring[0] != '\0')
896 logmsg(LOG_ALERT, "reboot after panic: %.*s",
897 (int)sizeof(kdhl.panicstring), kdhl.panicstring);
899 logmsg(LOG_ALERT, "reboot");
902 printf("Checking for available free space\n");
904 if (!check_space(savedir, savedirfd, dumplength, bounds)) {
909 writebounds(savedirfd, bounds + 1);
911 saved_dump_remove(savedirfd, bounds);
913 snprintf(infoname, sizeof(infoname), "info.%d", bounds);
916 * Create or overwrite any existing dump header files.
918 if ((info = xfopenat(savedirfd, infoname,
919 O_WRONLY | O_CREAT | O_TRUNC, "w", 0600)) == NULL) {
920 logmsg(LOG_ERR, "open(%s): %m", infoname);
925 isencrypted = (dumpkeysize > 0);
927 snprintf(corename, sizeof(corename), "%s.%d.gz",
928 istextdump ? "textdump.tar" :
929 (isencrypted ? "vmcore_encrypted" : "vmcore"), bounds);
930 else if (iscompressed && !isencrypted && !uncompress)
931 snprintf(corename, sizeof(corename), "vmcore.%d.%s", bounds,
932 (kdhl.compression == KERNELDUMP_COMP_GZIP) ? "gz" : "zst");
934 snprintf(corename, sizeof(corename), "%s.%d",
935 istextdump ? "textdump.tar" :
936 (isencrypted ? "vmcore_encrypted" : "vmcore"), bounds);
937 fdcore = openat(savedirfd, corename, O_WRONLY | O_CREAT | O_TRUNC,
940 logmsg(LOG_ERR, "open(%s): %m", corename);
947 core = zdopen(fdcore, "w");
949 core = fdopen(fdcore, "w");
951 logmsg(LOG_ERR, "%s: %m", corename);
959 xostyle = xo_get_style(NULL);
960 xoinfo = xo_create_to_file(info, xostyle, 0);
961 if (xoinfo == NULL) {
962 logmsg(LOG_ERR, "%s: %m", infoname);
967 xo_open_container_h(xoinfo, "crashdump");
970 printheader(xostdout, &kdhl, device, bounds, status);
972 printheader(xoinfo, &kdhl, device, bounds, status);
973 xo_close_container_h(xoinfo, "crashdump");
979 dumpkey = calloc(1, dumpkeysize);
980 if (dumpkey == NULL) {
981 logmsg(LOG_ERR, "Unable to allocate kernel dump key.");
986 if (read(fddev, dumpkey, dumpkeysize) != (ssize_t)dumpkeysize) {
987 logmsg(LOG_ERR, "Unable to read kernel dump key: %m.");
992 snprintf(keyname, sizeof(keyname), "key.%d", bounds);
993 ret = writekey(savedirfd, keyname, dumpkey, dumpkeysize);
994 explicit_bzero(dumpkey, dumpkeysize);
1001 logmsg(LOG_NOTICE, "writing %s%score to %s/%s",
1002 isencrypted ? "encrypted " : "", compress ? "compressed " : "",
1006 if (DoTextdumpFile(fddev, dumplength, lasthd, buf, device,
1007 corename, core) < 0)
1010 if (DoRegularFile(fddev, dumplength, sectorsize,
1011 !(compress || iscompressed || isencrypted),
1012 uncompress ? kdhl.compression : KERNELDUMP_COMP_NONE,
1013 buf, device, corename, core) < 0) {
1020 if (fclose(core) < 0) {
1021 logmsg(LOG_ERR, "error on %s: %m", corename);
1026 symlinks_remove(savedirfd);
1027 if (symlinkat(infoname, savedirfd, "info.last") == -1) {
1028 logmsg(LOG_WARNING, "unable to create symlink %s/%s: %m",
1029 savedir, "info.last");
1032 if (symlinkat(keyname, savedirfd, "key.last") == -1) {
1034 "unable to create symlink %s/%s: %m", savedir,
1038 if ((iscompressed && !uncompress) || compress) {
1039 snprintf(linkname, sizeof(linkname), "%s.last.%s",
1040 istextdump ? "textdump.tar" :
1041 (isencrypted ? "vmcore_encrypted" : "vmcore"),
1042 (kdhl.compression == KERNELDUMP_COMP_ZSTD) ? "zst" : "gz");
1044 snprintf(linkname, sizeof(linkname), "%s.last",
1045 istextdump ? "textdump.tar" :
1046 (isencrypted ? "vmcore_encrypted" : "vmcore"));
1048 if (symlinkat(corename, savedirfd, linkname) == -1) {
1049 logmsg(LOG_WARNING, "unable to create symlink %s/%s: %m",
1056 printf("dump saved\n");
1061 printf("clearing dump header\n");
1062 memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof(kdhl.magic));
1063 memcpy(temp, &kdhl, sizeof(kdhl));
1064 if (lseek(fddev, lasthd, SEEK_SET) != lasthd ||
1065 write(fddev, temp, sectorsize) != (ssize_t)sectorsize)
1067 "error while clearing the dump header: %m");
1069 xo_close_container_h(xostdout, "crashdump");
1070 xo_finish_h(xostdout);
1085 /* Prepend "/dev/" to any arguments that don't already have it */
1087 devify(int argc, char **argv)
1092 devs = malloc(argc * sizeof(*argv));
1094 logmsg(LOG_ERR, "malloc(): %m");
1097 for (i = 0; i < argc; i++) {
1098 if (strncmp(argv[i], _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
1099 devs[i] = strdup(argv[i]);
1103 fullpath = malloc(PATH_MAX);
1104 if (fullpath == NULL) {
1105 logmsg(LOG_ERR, "malloc(): %m");
1108 l = snprintf(fullpath, PATH_MAX, "%s%s", _PATH_DEV,
1111 logmsg(LOG_ERR, "snprintf(): %m");
1113 } else if (l >= PATH_MAX) {
1114 logmsg(LOG_ERR, "device name too long");
1124 enum_dumpdevs(int *argcp)
1131 * We cannot use getfsent(3) in capability mode, so we must
1132 * scan /etc/fstab and build up a list of candidate devices
1133 * before proceeding.
1137 argv = malloc(n * sizeof(*argv));
1139 logmsg(LOG_ERR, "malloc(): %m");
1146 if (strcmp(fsp->fs_vfstype, "swap") != 0 &&
1147 strcmp(fsp->fs_vfstype, "dump") != 0)
1151 argv = realloc(argv, n * sizeof(*argv));
1153 logmsg(LOG_ERR, "realloc(): %m");
1157 argv[argc] = strdup(fsp->fs_spec);
1158 if (argv[argc] == NULL) {
1159 logmsg(LOG_ERR, "strdup(): %m");
1169 init_caps(int argc, char **argv)
1171 cap_rights_t rights;
1172 cap_channel_t *capcas;
1174 capcas = cap_init();
1175 if (capcas == NULL) {
1176 logmsg(LOG_ERR, "cap_init(): %m");
1180 * The fileargs capability does not currently provide a way to limit
1183 (void)cap_rights_init(&rights, CAP_PREAD, CAP_WRITE, CAP_IOCTL);
1184 capfa = fileargs_init(argc, argv, checkfor || keep ? O_RDONLY : O_RDWR,
1185 0, &rights, FA_OPEN);
1186 if (capfa == NULL) {
1187 logmsg(LOG_ERR, "fileargs_init(): %m");
1190 caph_cache_catpages();
1191 caph_cache_tzdata();
1192 if (caph_enter_casper() != 0) {
1193 logmsg(LOG_ERR, "caph_enter_casper(): %m");
1196 capsyslog = cap_service_open(capcas, "system.syslog");
1197 if (capsyslog == NULL) {
1198 logmsg(LOG_ERR, "cap_service_open(system.syslog): %m");
1207 xo_error("%s\n%s\n%s\n",
1208 "usage: savecore -c [-v] [device ...]",
1209 " savecore -C [-v] [device ...]",
1210 " savecore [-fkvz] [-m maxdumps] [directory [device ...]]");
1215 main(int argc, char **argv)
1217 cap_rights_t rights;
1218 const char *savedir;
1220 int i, ch, error, savedirfd;
1222 checkfor = compress = clear = force = keep = false;
1224 nfound = nsaved = nerr = 0;
1227 openlog("savecore", LOG_PERROR, LOG_DAEMON);
1228 signal(SIGINFO, infohandler);
1230 argc = xo_parse_args(argc, argv);
1234 while ((ch = getopt(argc, argv, "Ccfkm:uvz")) != -1)
1249 maxdumps = atoi(optarg);
1250 if (maxdumps <= 0) {
1251 logmsg(LOG_ERR, "Invalid maxdump value");
1268 if (checkfor && (clear || force || keep))
1270 if (clear && (compress || keep))
1272 if (maxdumps > 0 && (checkfor || clear))
1274 if (compress && uncompress)
1278 if (argc >= 1 && !checkfor && !clear) {
1279 error = chdir(argv[0]);
1281 logmsg(LOG_ERR, "chdir(%s): %m", argv[0]);
1289 devs = enum_dumpdevs(&argc);
1291 devs = devify(argc, argv);
1293 savedirfd = open(savedir, O_RDONLY | O_DIRECTORY);
1294 if (savedirfd < 0) {
1295 logmsg(LOG_ERR, "open(%s): %m", savedir);
1298 (void)cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL, CAP_FSTATAT,
1299 CAP_FSTATFS, CAP_PREAD, CAP_SYMLINKAT, CAP_FTRUNCATE, CAP_UNLINKAT,
1301 if (caph_rights_limit(savedirfd, &rights) < 0) {
1302 logmsg(LOG_ERR, "cap_rights_limit(): %m");
1306 /* Enter capability mode. */
1307 init_caps(argc, devs);
1309 for (i = 0; i < argc; i++)
1310 DoFile(savedir, savedirfd, devs[i]);
1312 /* Emit minimal output. */
1316 printf("No dump exists\n");
1320 logmsg(LOG_WARNING, "no dumps found");
1321 } else if (nsaved == 0) {
1325 "unsaved dumps found but not saved");
1328 logmsg(LOG_WARNING, "no unsaved dumps found");
1335 infohandler(int sig __unused)