xref: /freebsd/sbin/savecore/savecore.c (revision ca987d4641cdcd7f27e153db17c5bf064934faf5)
1 /*-
2  * Copyright (c) 2002 Poul-Henning Kamp
3  * Copyright (c) 2002 Networks Associates Technology, Inc.
4  * All rights reserved.
5  *
6  * This software was developed for the FreeBSD Project by Poul-Henning Kamp
7  * and NAI Labs, the Security Research Division of Network Associates, Inc.
8  * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
9  * DARPA CHATS research program.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. The names of the authors may not be used to endorse or promote
20  *    products derived from this software without specific prior written
21  *    permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  * Copyright (c) 1986, 1992, 1993
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  */
62 
63 #include <sys/cdefs.h>
64 __FBSDID("$FreeBSD$");
65 
66 #include <sys/param.h>
67 #include <sys/disk.h>
68 #include <sys/kerneldump.h>
69 #include <sys/mount.h>
70 #include <sys/stat.h>
71 #include <ctype.h>
72 #include <errno.h>
73 #include <fcntl.h>
74 #include <fstab.h>
75 #include <paths.h>
76 #include <signal.h>
77 #include <stdarg.h>
78 #include <stdbool.h>
79 #include <stdio.h>
80 #include <stdlib.h>
81 #include <string.h>
82 #include <syslog.h>
83 #include <time.h>
84 #include <unistd.h>
85 #include <libxo/xo.h>
86 
87 /* The size of the buffer used for I/O. */
88 #define	BUFFERSIZE	(1024*1024)
89 
90 #define	STATUS_BAD	0
91 #define	STATUS_GOOD	1
92 #define	STATUS_UNKNOWN	2
93 
94 static int checkfor, compress, clear, force, keep, verbose;	/* flags */
95 static int nfound, nsaved, nerr;			/* statistics */
96 static int maxdumps;
97 
98 extern FILE *zopen(const char *, const char *);
99 
100 static sig_atomic_t got_siginfo;
101 static void infohandler(int);
102 
103 static void
104 printheader(xo_handle_t *xo, const struct kerneldumpheader *h,
105     const char *device, int bounds, const int status)
106 {
107 	uint64_t dumplen;
108 	time_t t;
109 	const char *stat_str;
110 
111 	xo_flush_h(xo);
112 	xo_emit_h(xo, "{Lwc:Dump header from device}{:dump_device/%s}\n",
113 	    device);
114 	xo_emit_h(xo, "{P:  }{Lwc:Architecture}{:architecture/%s}\n",
115 	    h->architecture);
116 	xo_emit_h(xo,
117 	    "{P:  }{Lwc:Architecture Version}{:architecture_version/%u}\n",
118 	    dtoh32(h->architectureversion));
119 	dumplen = dtoh64(h->dumplength);
120 	xo_emit_h(xo, "{P:  }{Lwc:Dump Length}{:dump_length_bytes/%lld}\n",
121 	    (long long)dumplen);
122 	xo_emit_h(xo, "{P:  }{Lwc:Blocksize}{:blocksize/%d}\n",
123 	    dtoh32(h->blocksize));
124 	xo_emit_h(xo, "{P:  }{Lwc:Compression}{:compression/%s}\n",
125 	    h->compression == KERNELDUMP_COMP_GZIP ?
126 	    "gzip" : "none");
127 
128 	t = dtoh64(h->dumptime);
129 	xo_emit_h(xo, "{P:  }{Lwc:Dumptime}{:dumptime/%s}", ctime(&t));
130 	xo_emit_h(xo, "{P:  }{Lwc:Hostname}{:hostname/%s}\n", h->hostname);
131 	xo_emit_h(xo, "{P:  }{Lwc:Magic}{:magic/%s}\n", h->magic);
132 	xo_emit_h(xo, "{P:  }{Lwc:Version String}{:version_string/%s}",
133 	    h->versionstring);
134 	xo_emit_h(xo, "{P:  }{Lwc:Panic String}{:panic_string/%s}\n",
135 	    h->panicstring);
136 	xo_emit_h(xo, "{P:  }{Lwc:Dump Parity}{:dump_parity/%u}\n", h->parity);
137 	xo_emit_h(xo, "{P:  }{Lwc:Bounds}{:bounds/%d}\n", bounds);
138 
139 	switch (status) {
140 	case STATUS_BAD:
141 		stat_str = "bad";
142 		break;
143 	case STATUS_GOOD:
144 		stat_str = "good";
145 		break;
146 	default:
147 		stat_str = "unknown";
148 		break;
149 	}
150 	xo_emit_h(xo, "{P:  }{Lwc:Dump Status}{:dump_status/%s}\n", stat_str);
151 	xo_flush_h(xo);
152 }
153 
154 static int
155 getbounds(void)
156 {
157 	FILE *fp;
158 	char buf[6];
159 	int ret;
160 
161 	ret = 0;
162 
163 	if ((fp = fopen("bounds", "r")) == NULL) {
164 		if (verbose)
165 			printf("unable to open bounds file, using 0\n");
166 		return (ret);
167 	}
168 
169 	if (fgets(buf, sizeof buf, fp) == NULL) {
170 		if (feof(fp))
171 			syslog(LOG_WARNING, "bounds file is empty, using 0");
172 		else
173 			syslog(LOG_WARNING, "bounds file: %s", strerror(errno));
174 		fclose(fp);
175 		return (ret);
176 	}
177 
178 	errno = 0;
179 	ret = (int)strtol(buf, NULL, 10);
180 	if (ret == 0 && (errno == EINVAL || errno == ERANGE))
181 		syslog(LOG_WARNING, "invalid value found in bounds, using 0");
182 	fclose(fp);
183 	return (ret);
184 }
185 
186 static void
187 writebounds(int bounds)
188 {
189 	FILE *fp;
190 
191 	if ((fp = fopen("bounds", "w")) == NULL) {
192 		syslog(LOG_WARNING, "unable to write to bounds file: %m");
193 		return;
194 	}
195 
196 	if (verbose)
197 		printf("bounds number: %d\n", bounds);
198 
199 	fprintf(fp, "%d\n", bounds);
200 	fclose(fp);
201 }
202 
203 static bool
204 writekey(const char *keyname, uint8_t *dumpkey, uint32_t dumpkeysize)
205 {
206 	int fd;
207 
208 	fd = open(keyname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
209 	if (fd == -1) {
210 		syslog(LOG_ERR, "Unable to open %s to write the key: %m.",
211 		    keyname);
212 		return (false);
213 	}
214 
215 	if (write(fd, dumpkey, dumpkeysize) != (ssize_t)dumpkeysize) {
216 		syslog(LOG_ERR, "Unable to write the key to %s: %m.", keyname);
217 		close(fd);
218 		return (false);
219 	}
220 
221 	close(fd);
222 	return (true);
223 }
224 
225 static off_t
226 file_size(const char *path)
227 {
228 	struct stat sb;
229 
230 	/* Ignore all errors, those file may not exists. */
231 	if (stat(path, &sb) == -1)
232 		return (0);
233 	return (sb.st_size);
234 }
235 
236 static off_t
237 saved_dump_size(int bounds)
238 {
239 	static char path[PATH_MAX];
240 	off_t dumpsize;
241 
242 	dumpsize = 0;
243 
244 	(void)snprintf(path, sizeof(path), "info.%d", bounds);
245 	dumpsize += file_size(path);
246 	(void)snprintf(path, sizeof(path), "vmcore.%d", bounds);
247 	dumpsize += file_size(path);
248 	(void)snprintf(path, sizeof(path), "vmcore.%d.gz", bounds);
249 	dumpsize += file_size(path);
250 	(void)snprintf(path, sizeof(path), "textdump.tar.%d", bounds);
251 	dumpsize += file_size(path);
252 	(void)snprintf(path, sizeof(path), "textdump.tar.%d.gz", bounds);
253 	dumpsize += file_size(path);
254 
255 	return (dumpsize);
256 }
257 
258 static void
259 saved_dump_remove(int bounds)
260 {
261 	static char path[PATH_MAX];
262 
263 	(void)snprintf(path, sizeof(path), "info.%d", bounds);
264 	(void)unlink(path);
265 	(void)snprintf(path, sizeof(path), "vmcore.%d", bounds);
266 	(void)unlink(path);
267 	(void)snprintf(path, sizeof(path), "vmcore.%d.gz", bounds);
268 	(void)unlink(path);
269 	(void)snprintf(path, sizeof(path), "textdump.tar.%d", bounds);
270 	(void)unlink(path);
271 	(void)snprintf(path, sizeof(path), "textdump.tar.%d.gz", bounds);
272 	(void)unlink(path);
273 }
274 
275 static void
276 symlinks_remove(void)
277 {
278 
279 	(void)unlink("info.last");
280 	(void)unlink("key.last");
281 	(void)unlink("vmcore.last");
282 	(void)unlink("vmcore.last.gz");
283 	(void)unlink("vmcore_encrypted.last");
284 	(void)unlink("vmcore_encrypted.last.gz");
285 	(void)unlink("textdump.tar.last");
286 	(void)unlink("textdump.tar.last.gz");
287 }
288 
289 /*
290  * Check that sufficient space is available on the disk that holds the
291  * save directory.
292  */
293 static int
294 check_space(const char *savedir, off_t dumpsize, int bounds)
295 {
296 	FILE *fp;
297 	off_t available, minfree, spacefree, totfree, needed;
298 	struct statfs fsbuf;
299 	char buf[100];
300 
301 	if (statfs(".", &fsbuf) < 0) {
302 		syslog(LOG_ERR, "%s: %m", savedir);
303 		exit(1);
304 	}
305 	spacefree = ((off_t) fsbuf.f_bavail * fsbuf.f_bsize) / 1024;
306 	totfree = ((off_t) fsbuf.f_bfree * fsbuf.f_bsize) / 1024;
307 
308 	if ((fp = fopen("minfree", "r")) == NULL)
309 		minfree = 0;
310 	else {
311 		if (fgets(buf, sizeof(buf), fp) == NULL)
312 			minfree = 0;
313 		else {
314 			char *endp;
315 
316 			errno = 0;
317 			minfree = strtoll(buf, &endp, 10);
318 			if (minfree == 0 && errno != 0)
319 				minfree = -1;
320 			else {
321 				while (*endp != '\0' && isspace(*endp))
322 					endp++;
323 				if (*endp != '\0' || minfree < 0)
324 					minfree = -1;
325 			}
326 			if (minfree < 0)
327 				syslog(LOG_WARNING,
328 				    "`minfree` didn't contain a valid size "
329 				    "(`%s`). Defaulting to 0", buf);
330 		}
331 		(void)fclose(fp);
332 	}
333 
334 	available = minfree > 0 ? spacefree - minfree : totfree;
335 	needed = dumpsize / 1024 + 2;	/* 2 for info file */
336 	needed -= saved_dump_size(bounds);
337 	if (available < needed) {
338 		syslog(LOG_WARNING,
339 		    "no dump: not enough free space on device (need at least "
340 		    "%jdkB for dump; %jdkB available; %jdkB reserved)",
341 		    (intmax_t)needed,
342 		    (intmax_t)available + minfree,
343 		    (intmax_t)minfree);
344 		return (0);
345 	}
346 	if (spacefree - needed < 0)
347 		syslog(LOG_WARNING,
348 		    "dump performed, but free space threshold crossed");
349 	return (1);
350 }
351 
352 static bool
353 compare_magic(const struct kerneldumpheader *kdh, const char *magic)
354 {
355 
356 	return (strncmp(kdh->magic, magic, sizeof(kdh->magic)) == 0);
357 }
358 
359 #define BLOCKSIZE (1<<12)
360 #define BLOCKMASK (~(BLOCKSIZE-1))
361 
362 static int
363 DoRegularFile(int fd, off_t dumpsize, u_int sectorsize, bool sparse, char *buf,
364     const char *device, const char *filename, FILE *fp)
365 {
366 	int he, hs, nr, nw, wl;
367 	off_t dmpcnt, origsize;
368 
369 	dmpcnt = 0;
370 	origsize = dumpsize;
371 	he = 0;
372 	while (dumpsize > 0) {
373 		wl = BUFFERSIZE;
374 		if (wl > dumpsize)
375 			wl = dumpsize;
376 		nr = read(fd, buf, roundup(wl, sectorsize));
377 		if (nr != (int)roundup(wl, sectorsize)) {
378 			if (nr == 0)
379 				syslog(LOG_WARNING,
380 				    "WARNING: EOF on dump device");
381 			else
382 				syslog(LOG_ERR, "read error on %s: %m", device);
383 			nerr++;
384 			return (-1);
385 		}
386 		if (!sparse) {
387 			nw = fwrite(buf, 1, wl, fp);
388 		} else {
389 			for (nw = 0; nw < nr; nw = he) {
390 				/* find a contiguous block of zeroes */
391 				for (hs = nw; hs < nr; hs += BLOCKSIZE) {
392 					for (he = hs; he < nr && buf[he] == 0;
393 					    ++he)
394 						/* nothing */ ;
395 					/* is the hole long enough to matter? */
396 					if (he >= hs + BLOCKSIZE)
397 						break;
398 				}
399 
400 				/* back down to a block boundary */
401 				he &= BLOCKMASK;
402 
403 				/*
404 				 * 1) Don't go beyond the end of the buffer.
405 				 * 2) If the end of the buffer is less than
406 				 *    BLOCKSIZE bytes away, we're at the end
407 				 *    of the file, so just grab what's left.
408 				 */
409 				if (hs + BLOCKSIZE > nr)
410 					hs = he = nr;
411 
412 				/*
413 				 * At this point, we have a partial ordering:
414 				 *     nw <= hs <= he <= nr
415 				 * If hs > nw, buf[nw..hs] contains non-zero
416 				 * data. If he > hs, buf[hs..he] is all zeroes.
417 				 */
418 				if (hs > nw)
419 					if (fwrite(buf + nw, hs - nw, 1, fp)
420 					    != 1)
421 					break;
422 				if (he > hs)
423 					if (fseeko(fp, he - hs, SEEK_CUR) == -1)
424 						break;
425 			}
426 		}
427 		if (nw != wl) {
428 			syslog(LOG_ERR,
429 			    "write error on %s file: %m", filename);
430 			syslog(LOG_WARNING,
431 			    "WARNING: vmcore may be incomplete");
432 			nerr++;
433 			return (-1);
434 		}
435 		if (verbose) {
436 			dmpcnt += wl;
437 			printf("%llu\r", (unsigned long long)dmpcnt);
438 			fflush(stdout);
439 		}
440 		dumpsize -= wl;
441 		if (got_siginfo) {
442 			printf("%s %.1lf%%\n", filename, (100.0 - (100.0 *
443 			    (double)dumpsize / (double)origsize)));
444 			got_siginfo = 0;
445 		}
446 	}
447 	return (0);
448 }
449 
450 /*
451  * Specialized version of dump-reading logic for use with textdumps, which
452  * are written backwards from the end of the partition, and must be reversed
453  * before being written to the file.  Textdumps are small, so do a bit less
454  * work to optimize/sparsify.
455  */
456 static int
457 DoTextdumpFile(int fd, off_t dumpsize, off_t lasthd, char *buf,
458     const char *device, const char *filename, FILE *fp)
459 {
460 	int nr, nw, wl;
461 	off_t dmpcnt, totsize;
462 
463 	totsize = dumpsize;
464 	dmpcnt = 0;
465 	wl = 512;
466 	if ((dumpsize % wl) != 0) {
467 		syslog(LOG_ERR, "textdump uneven multiple of 512 on %s",
468 		    device);
469 		nerr++;
470 		return (-1);
471 	}
472 	while (dumpsize > 0) {
473 		nr = pread(fd, buf, wl, lasthd - (totsize - dumpsize) - wl);
474 		if (nr != wl) {
475 			if (nr == 0)
476 				syslog(LOG_WARNING,
477 				    "WARNING: EOF on dump device");
478 			else
479 				syslog(LOG_ERR, "read error on %s: %m", device);
480 			nerr++;
481 			return (-1);
482 		}
483 		nw = fwrite(buf, 1, wl, fp);
484 		if (nw != wl) {
485 			syslog(LOG_ERR,
486 			    "write error on %s file: %m", filename);
487 			syslog(LOG_WARNING,
488 			    "WARNING: textdump may be incomplete");
489 			nerr++;
490 			return (-1);
491 		}
492 		if (verbose) {
493 			dmpcnt += wl;
494 			printf("%llu\r", (unsigned long long)dmpcnt);
495 			fflush(stdout);
496 		}
497 		dumpsize -= wl;
498 	}
499 	return (0);
500 }
501 
502 static void
503 DoFile(const char *savedir, const char *device)
504 {
505 	xo_handle_t *xostdout, *xoinfo;
506 	static char infoname[PATH_MAX], corename[PATH_MAX], linkname[PATH_MAX];
507 	static char keyname[PATH_MAX];
508 	static char *buf = NULL;
509 	char *temp = NULL;
510 	struct kerneldumpheader kdhf, kdhl;
511 	uint8_t *dumpkey;
512 	off_t mediasize, dumpextent, dumplength, firsthd, lasthd;
513 	FILE *info, *fp;
514 	mode_t oumask;
515 	int fd, fdinfo, error;
516 	int bounds, status;
517 	u_int sectorsize, xostyle;
518 	uint32_t dumpkeysize;
519 	bool iscompressed, isencrypted, istextdump, ret;
520 
521 	bounds = getbounds();
522 	dumpkey = NULL;
523 	mediasize = 0;
524 	status = STATUS_UNKNOWN;
525 
526 	xostdout = xo_create_to_file(stdout, XO_STYLE_TEXT, 0);
527 	if (xostdout == NULL) {
528 		syslog(LOG_ERR, "%s: %m", infoname);
529 		return;
530 	}
531 
532 	if (maxdumps > 0 && bounds == maxdumps)
533 		bounds = 0;
534 
535 	if (buf == NULL) {
536 		buf = malloc(BUFFERSIZE);
537 		if (buf == NULL) {
538 			syslog(LOG_ERR, "%m");
539 			return;
540 		}
541 	}
542 
543 	if (verbose)
544 		printf("checking for kernel dump on device %s\n", device);
545 
546 	fd = open(device, (checkfor || keep) ? O_RDONLY : O_RDWR);
547 	if (fd < 0) {
548 		syslog(LOG_ERR, "%s: %m", device);
549 		return;
550 	}
551 
552 	error = ioctl(fd, DIOCGMEDIASIZE, &mediasize);
553 	if (!error)
554 		error = ioctl(fd, DIOCGSECTORSIZE, &sectorsize);
555 	if (error) {
556 		syslog(LOG_ERR,
557 		    "couldn't find media and/or sector size of %s: %m", device);
558 		goto closefd;
559 	}
560 
561 	if (verbose) {
562 		printf("mediasize = %lld bytes\n", (long long)mediasize);
563 		printf("sectorsize = %u bytes\n", sectorsize);
564 	}
565 
566 	if (sectorsize < sizeof(kdhl)) {
567 		syslog(LOG_ERR,
568 		    "Sector size is less the kernel dump header %zu",
569 		    sizeof(kdhl));
570 		goto closefd;
571 	}
572 
573 	lasthd = mediasize - sectorsize;
574 	temp = malloc(sectorsize);
575 	if (temp == NULL) {
576 		syslog(LOG_ERR, "%m");
577 		goto closefd;
578 	}
579 	if (lseek(fd, lasthd, SEEK_SET) != lasthd ||
580 	    read(fd, temp, sectorsize) != (ssize_t)sectorsize) {
581 		syslog(LOG_ERR,
582 		    "error reading last dump header at offset %lld in %s: %m",
583 		    (long long)lasthd, device);
584 		goto closefd;
585 	}
586 	memcpy(&kdhl, temp, sizeof(kdhl));
587 	iscompressed = istextdump = false;
588 	if (compare_magic(&kdhl, TEXTDUMPMAGIC)) {
589 		if (verbose)
590 			printf("textdump magic on last dump header on %s\n",
591 			    device);
592 		istextdump = true;
593 		if (dtoh32(kdhl.version) != KERNELDUMP_TEXT_VERSION) {
594 			syslog(LOG_ERR,
595 			    "unknown version (%d) in last dump header on %s",
596 			    dtoh32(kdhl.version), device);
597 
598 			status = STATUS_BAD;
599 			if (force == 0)
600 				goto closefd;
601 		}
602 	} else if (compare_magic(&kdhl, KERNELDUMPMAGIC)) {
603 		if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
604 			syslog(LOG_ERR,
605 			    "unknown version (%d) in last dump header on %s",
606 			    dtoh32(kdhl.version), device);
607 
608 			status = STATUS_BAD;
609 			if (force == 0)
610 				goto closefd;
611 		}
612 		switch (kdhl.compression) {
613 		case KERNELDUMP_COMP_NONE:
614 			break;
615 		case KERNELDUMP_COMP_GZIP:
616 			if (compress && verbose)
617 				printf("dump is already compressed\n");
618 			compress = false;
619 			iscompressed = true;
620 			break;
621 		default:
622 			syslog(LOG_ERR, "unknown compression type %d on %s",
623 			    kdhl.compression, device);
624 			break;
625 		}
626 	} else {
627 		if (verbose)
628 			printf("magic mismatch on last dump header on %s\n",
629 			    device);
630 
631 		status = STATUS_BAD;
632 		if (force == 0)
633 			goto closefd;
634 
635 		if (compare_magic(&kdhl, KERNELDUMPMAGIC_CLEARED)) {
636 			if (verbose)
637 				printf("forcing magic on %s\n", device);
638 			memcpy(kdhl.magic, KERNELDUMPMAGIC, sizeof(kdhl.magic));
639 		} else {
640 			syslog(LOG_ERR, "unable to force dump - bad magic");
641 			goto closefd;
642 		}
643 		if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
644 			syslog(LOG_ERR,
645 			    "unknown version (%d) in last dump header on %s",
646 			    dtoh32(kdhl.version), device);
647 
648 			status = STATUS_BAD;
649 			if (force == 0)
650 				goto closefd;
651 		}
652 	}
653 
654 	nfound++;
655 	if (clear)
656 		goto nuke;
657 
658 	if (kerneldump_parity(&kdhl)) {
659 		syslog(LOG_ERR,
660 		    "parity error on last dump header on %s", device);
661 		nerr++;
662 		status = STATUS_BAD;
663 		if (force == 0)
664 			goto closefd;
665 	}
666 	dumpextent = dtoh64(kdhl.dumpextent);
667 	dumplength = dtoh64(kdhl.dumplength);
668 	dumpkeysize = dtoh32(kdhl.dumpkeysize);
669 	firsthd = lasthd - dumpextent - sectorsize - dumpkeysize;
670 	if (lseek(fd, firsthd, SEEK_SET) != firsthd ||
671 	    read(fd, temp, sectorsize) != (ssize_t)sectorsize) {
672 		syslog(LOG_ERR,
673 		    "error reading first dump header at offset %lld in %s: %m",
674 		    (long long)firsthd, device);
675 		nerr++;
676 		goto closefd;
677 	}
678 	memcpy(&kdhf, temp, sizeof(kdhf));
679 
680 	if (verbose >= 2) {
681 		printf("First dump headers:\n");
682 		printheader(xostdout, &kdhf, device, bounds, -1);
683 
684 		printf("\nLast dump headers:\n");
685 		printheader(xostdout, &kdhl, device, bounds, -1);
686 		printf("\n");
687 	}
688 
689 	if (memcmp(&kdhl, &kdhf, sizeof(kdhl))) {
690 		syslog(LOG_ERR,
691 		    "first and last dump headers disagree on %s", device);
692 		nerr++;
693 		status = STATUS_BAD;
694 		if (force == 0)
695 			goto closefd;
696 	} else {
697 		status = STATUS_GOOD;
698 	}
699 
700 	if (checkfor) {
701 		printf("A dump exists on %s\n", device);
702 		close(fd);
703 		exit(0);
704 	}
705 
706 	if (kdhl.panicstring[0] != '\0')
707 		syslog(LOG_ALERT, "reboot after panic: %.*s",
708 		    (int)sizeof(kdhl.panicstring), kdhl.panicstring);
709 	else
710 		syslog(LOG_ALERT, "reboot");
711 
712 	if (verbose)
713 		printf("Checking for available free space\n");
714 
715 	if (!check_space(savedir, dumplength, bounds)) {
716 		nerr++;
717 		goto closefd;
718 	}
719 
720 	writebounds(bounds + 1);
721 
722 	saved_dump_remove(bounds);
723 
724 	snprintf(infoname, sizeof(infoname), "info.%d", bounds);
725 
726 	/*
727 	 * Create or overwrite any existing dump header files.
728 	 */
729 	fdinfo = open(infoname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
730 	if (fdinfo < 0) {
731 		syslog(LOG_ERR, "%s: %m", infoname);
732 		nerr++;
733 		goto closefd;
734 	}
735 
736 	oumask = umask(S_IRWXG|S_IRWXO); /* Restrict access to the core file. */
737 	isencrypted = (dumpkeysize > 0);
738 	if (compress) {
739 		snprintf(corename, sizeof(corename), "%s.%d.gz",
740 		    istextdump ? "textdump.tar" :
741 		    (isencrypted ? "vmcore_encrypted" : "vmcore"), bounds);
742 		fp = zopen(corename, "w");
743 	} else if (iscompressed && !isencrypted) {
744 		snprintf(corename, sizeof(corename), "vmcore.%d.gz", bounds);
745 		fp = fopen(corename, "w");
746 	} else {
747 		snprintf(corename, sizeof(corename), "%s.%d",
748 		    istextdump ? "textdump.tar" :
749 		    (isencrypted ? "vmcore_encrypted" : "vmcore"), bounds);
750 		fp = fopen(corename, "w");
751 	}
752 	if (fp == NULL) {
753 		syslog(LOG_ERR, "%s: %m", corename);
754 		close(fdinfo);
755 		nerr++;
756 		goto closefd;
757 	}
758 	(void)umask(oumask);
759 
760 	info = fdopen(fdinfo, "w");
761 
762 	if (info == NULL) {
763 		syslog(LOG_ERR, "fdopen failed: %m");
764 		nerr++;
765 		goto closeall;
766 	}
767 
768 	xostyle = xo_get_style(NULL);
769 	xoinfo = xo_create_to_file(info, xostyle, 0);
770 	if (xoinfo == NULL) {
771 		syslog(LOG_ERR, "%s: %m", infoname);
772 		nerr++;
773 		goto closeall;
774 	}
775 	xo_open_container_h(xoinfo, "crashdump");
776 
777 	if (verbose)
778 		printheader(xostdout, &kdhl, device, bounds, status);
779 
780 	printheader(xoinfo, &kdhl, device, bounds, status);
781 	xo_close_container_h(xoinfo, "crashdump");
782 	xo_flush_h(xoinfo);
783 	xo_finish_h(xoinfo);
784 	fclose(info);
785 
786 	if (isencrypted) {
787 		dumpkey = calloc(1, dumpkeysize);
788 		if (dumpkey == NULL) {
789 			syslog(LOG_ERR, "Unable to allocate kernel dump key.");
790 			nerr++;
791 			goto closeall;
792 		}
793 
794 		if (read(fd, dumpkey, dumpkeysize) != (ssize_t)dumpkeysize) {
795 			syslog(LOG_ERR, "Unable to read kernel dump key: %m.");
796 			nerr++;
797 			goto closeall;
798 		}
799 
800 		snprintf(keyname, sizeof(keyname), "key.%d", bounds);
801 		ret = writekey(keyname, dumpkey, dumpkeysize);
802 		explicit_bzero(dumpkey, dumpkeysize);
803 		if (!ret) {
804 			nerr++;
805 			goto closeall;
806 		}
807 	}
808 
809 	syslog(LOG_NOTICE, "writing %s%score to %s/%s",
810 	    isencrypted ? "encrypted " : "", compress ? "compressed " : "",
811 	    savedir, corename);
812 
813 	if (istextdump) {
814 		if (DoTextdumpFile(fd, dumplength, lasthd, buf, device,
815 		    corename, fp) < 0)
816 			goto closeall;
817 	} else {
818 		if (DoRegularFile(fd, dumplength, sectorsize,
819 		    !(compress || iscompressed || isencrypted), buf, device,
820 		    corename, fp) < 0) {
821 			goto closeall;
822 		}
823 	}
824 	if (verbose)
825 		printf("\n");
826 
827 	if (fclose(fp) < 0) {
828 		syslog(LOG_ERR, "error on %s: %m", corename);
829 		nerr++;
830 		goto closefd;
831 	}
832 
833 	symlinks_remove();
834 	if (symlink(infoname, "info.last") == -1) {
835 		syslog(LOG_WARNING, "unable to create symlink %s/%s: %m",
836 		    savedir, "info.last");
837 	}
838 	if (isencrypted) {
839 		if (symlink(keyname, "key.last") == -1) {
840 			syslog(LOG_WARNING,
841 			    "unable to create symlink %s/%s: %m", savedir,
842 			    "key.last");
843 		}
844 	}
845 	if (compress || iscompressed) {
846 		snprintf(linkname, sizeof(linkname), "%s.last.gz",
847 		    istextdump ? "textdump.tar" :
848 		    (isencrypted ? "vmcore_encrypted" : "vmcore"));
849 	} else {
850 		snprintf(linkname, sizeof(linkname), "%s.last",
851 		    istextdump ? "textdump.tar" :
852 		    (isencrypted ? "vmcore_encrypted" : "vmcore"));
853 	}
854 	if (symlink(corename, linkname) == -1) {
855 		syslog(LOG_WARNING, "unable to create symlink %s/%s: %m",
856 		    savedir, linkname);
857 	}
858 
859 	nsaved++;
860 
861 	if (verbose)
862 		printf("dump saved\n");
863 
864 nuke:
865 	if (!keep) {
866 		if (verbose)
867 			printf("clearing dump header\n");
868 		memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof(kdhl.magic));
869 		memcpy(temp, &kdhl, sizeof(kdhl));
870 		if (lseek(fd, lasthd, SEEK_SET) != lasthd ||
871 		    write(fd, temp, sectorsize) != (ssize_t)sectorsize)
872 			syslog(LOG_ERR,
873 			    "error while clearing the dump header: %m");
874 	}
875 	xo_close_container_h(xostdout, "crashdump");
876 	xo_finish_h(xostdout);
877 	free(dumpkey);
878 	free(temp);
879 	close(fd);
880 	return;
881 
882 closeall:
883 	fclose(fp);
884 
885 closefd:
886 	free(dumpkey);
887 	free(temp);
888 	close(fd);
889 }
890 
891 static void
892 usage(void)
893 {
894 	xo_error("%s\n%s\n%s\n",
895 	    "usage: savecore -c [-v] [device ...]",
896 	    "       savecore -C [-v] [device ...]",
897 	    "       savecore [-fkvz] [-m maxdumps] [directory [device ...]]");
898 	exit(1);
899 }
900 
901 int
902 main(int argc, char **argv)
903 {
904 	const char *savedir = ".";
905 	struct fstab *fsp;
906 	int i, ch, error;
907 
908 	checkfor = compress = clear = force = keep = verbose = 0;
909 	nfound = nsaved = nerr = 0;
910 
911 	openlog("savecore", LOG_PERROR, LOG_DAEMON);
912 	signal(SIGINFO, infohandler);
913 
914 	argc = xo_parse_args(argc, argv);
915 	if (argc < 0)
916 		exit(1);
917 
918 	while ((ch = getopt(argc, argv, "Ccfkm:vz")) != -1)
919 		switch(ch) {
920 		case 'C':
921 			checkfor = 1;
922 			break;
923 		case 'c':
924 			clear = 1;
925 			break;
926 		case 'f':
927 			force = 1;
928 			break;
929 		case 'k':
930 			keep = 1;
931 			break;
932 		case 'm':
933 			maxdumps = atoi(optarg);
934 			if (maxdumps <= 0) {
935 				syslog(LOG_ERR, "Invalid maxdump value");
936 				exit(1);
937 			}
938 			break;
939 		case 'v':
940 			verbose++;
941 			break;
942 		case 'z':
943 			compress = 1;
944 			break;
945 		case '?':
946 		default:
947 			usage();
948 		}
949 	if (checkfor && (clear || force || keep))
950 		usage();
951 	if (clear && (compress || keep))
952 		usage();
953 	if (maxdumps > 0 && (checkfor || clear))
954 		usage();
955 	argc -= optind;
956 	argv += optind;
957 	if (argc >= 1 && !checkfor && !clear) {
958 		error = chdir(argv[0]);
959 		if (error) {
960 			syslog(LOG_ERR, "chdir(%s): %m", argv[0]);
961 			exit(1);
962 		}
963 		savedir = argv[0];
964 		argc--;
965 		argv++;
966 	}
967 	if (argc == 0) {
968 		for (;;) {
969 			fsp = getfsent();
970 			if (fsp == NULL)
971 				break;
972 			if (strcmp(fsp->fs_vfstype, "swap") &&
973 			    strcmp(fsp->fs_vfstype, "dump"))
974 				continue;
975 			DoFile(savedir, fsp->fs_spec);
976 		}
977 		endfsent();
978 	} else {
979 		for (i = 0; i < argc; i++)
980 			DoFile(savedir, argv[i]);
981 	}
982 
983 	/* Emit minimal output. */
984 	if (nfound == 0) {
985 		if (checkfor) {
986 			if (verbose)
987 				printf("No dump exists\n");
988 			exit(1);
989 		}
990 		if (verbose)
991 			syslog(LOG_WARNING, "no dumps found");
992 	} else if (nsaved == 0) {
993 		if (nerr != 0) {
994 			if (verbose)
995 				syslog(LOG_WARNING,
996 				    "unsaved dumps found but not saved");
997 			exit(1);
998 		} else if (verbose)
999 			syslog(LOG_WARNING, "no unsaved dumps found");
1000 	}
1001 
1002 	return (0);
1003 }
1004 
1005 static void
1006 infohandler(int sig __unused)
1007 {
1008 	got_siginfo = 1;
1009 }
1010