xref: /freebsd/sbin/savecore/savecore.c (revision 7c1b51d6dc2e165ae7333373513b080f17cf79bd)
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 
125 	t = dtoh64(h->dumptime);
126 	xo_emit_h(xo, "{P:  }{Lwc:Dumptime}{:dumptime/%s}", ctime(&t));
127 	xo_emit_h(xo, "{P:  }{Lwc:Hostname}{:hostname/%s}\n", h->hostname);
128 	xo_emit_h(xo, "{P:  }{Lwc:Magic}{:magic/%s}\n", h->magic);
129 	xo_emit_h(xo, "{P:  }{Lwc:Version String}{:version_string/%s}",
130 	    h->versionstring);
131 	xo_emit_h(xo, "{P:  }{Lwc:Panic String}{:panic_string/%s}\n",
132 	    h->panicstring);
133 	xo_emit_h(xo, "{P:  }{Lwc:Dump Parity}{:dump_parity/%u}\n", h->parity);
134 	xo_emit_h(xo, "{P:  }{Lwc:Bounds}{:bounds/%d}\n", bounds);
135 
136 	switch (status) {
137 	case STATUS_BAD:
138 		stat_str = "bad";
139 		break;
140 	case STATUS_GOOD:
141 		stat_str = "good";
142 		break;
143 	default:
144 		stat_str = "unknown";
145 		break;
146 	}
147 	xo_emit_h(xo, "{P:  }{Lwc:Dump Status}{:dump_status/%s}\n", stat_str);
148 	xo_flush_h(xo);
149 }
150 
151 static int
152 getbounds(void)
153 {
154 	FILE *fp;
155 	char buf[6];
156 	int ret;
157 
158 	ret = 0;
159 
160 	if ((fp = fopen("bounds", "r")) == NULL) {
161 		if (verbose)
162 			printf("unable to open bounds file, using 0\n");
163 		return (ret);
164 	}
165 
166 	if (fgets(buf, sizeof buf, fp) == NULL) {
167 		if (feof(fp))
168 			syslog(LOG_WARNING, "bounds file is empty, using 0");
169 		else
170 			syslog(LOG_WARNING, "bounds file: %s", strerror(errno));
171 		fclose(fp);
172 		return (ret);
173 	}
174 
175 	errno = 0;
176 	ret = (int)strtol(buf, NULL, 10);
177 	if (ret == 0 && (errno == EINVAL || errno == ERANGE))
178 		syslog(LOG_WARNING, "invalid value found in bounds, using 0");
179 	fclose(fp);
180 	return (ret);
181 }
182 
183 static void
184 writebounds(int bounds)
185 {
186 	FILE *fp;
187 
188 	if ((fp = fopen("bounds", "w")) == NULL) {
189 		syslog(LOG_WARNING, "unable to write to bounds file: %m");
190 		return;
191 	}
192 
193 	if (verbose)
194 		printf("bounds number: %d\n", bounds);
195 
196 	fprintf(fp, "%d\n", bounds);
197 	fclose(fp);
198 }
199 
200 static bool
201 writekey(const char *keyname, uint8_t *dumpkey, uint32_t dumpkeysize)
202 {
203 	int fd;
204 
205 	fd = open(keyname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
206 	if (fd == -1) {
207 		syslog(LOG_ERR, "Unable to open %s to write the key: %m.",
208 		    keyname);
209 		return (false);
210 	}
211 
212 	if (write(fd, dumpkey, dumpkeysize) != (ssize_t)dumpkeysize) {
213 		syslog(LOG_ERR, "Unable to write the key to %s: %m.", keyname);
214 		close(fd);
215 		return (false);
216 	}
217 
218 	close(fd);
219 	return (true);
220 }
221 
222 static off_t
223 file_size(const char *path)
224 {
225 	struct stat sb;
226 
227 	/* Ignore all errors, those file may not exists. */
228 	if (stat(path, &sb) == -1)
229 		return (0);
230 	return (sb.st_size);
231 }
232 
233 static off_t
234 saved_dump_size(int bounds)
235 {
236 	static char path[PATH_MAX];
237 	off_t dumpsize;
238 
239 	dumpsize = 0;
240 
241 	(void)snprintf(path, sizeof(path), "info.%d", bounds);
242 	dumpsize += file_size(path);
243 	(void)snprintf(path, sizeof(path), "vmcore.%d", bounds);
244 	dumpsize += file_size(path);
245 	(void)snprintf(path, sizeof(path), "vmcore.%d.gz", bounds);
246 	dumpsize += file_size(path);
247 	(void)snprintf(path, sizeof(path), "textdump.tar.%d", bounds);
248 	dumpsize += file_size(path);
249 	(void)snprintf(path, sizeof(path), "textdump.tar.%d.gz", bounds);
250 	dumpsize += file_size(path);
251 
252 	return (dumpsize);
253 }
254 
255 static void
256 saved_dump_remove(int bounds)
257 {
258 	static char path[PATH_MAX];
259 
260 	(void)snprintf(path, sizeof(path), "info.%d", bounds);
261 	(void)unlink(path);
262 	(void)snprintf(path, sizeof(path), "vmcore.%d", bounds);
263 	(void)unlink(path);
264 	(void)snprintf(path, sizeof(path), "vmcore.%d.gz", bounds);
265 	(void)unlink(path);
266 	(void)snprintf(path, sizeof(path), "textdump.tar.%d", bounds);
267 	(void)unlink(path);
268 	(void)snprintf(path, sizeof(path), "textdump.tar.%d.gz", bounds);
269 	(void)unlink(path);
270 }
271 
272 static void
273 symlinks_remove(void)
274 {
275 
276 	(void)unlink("info.last");
277 	(void)unlink("key.last");
278 	(void)unlink("vmcore.last");
279 	(void)unlink("vmcore.last.gz");
280 	(void)unlink("vmcore_encrypted.last");
281 	(void)unlink("vmcore_encrypted.last.gz");
282 	(void)unlink("textdump.tar.last");
283 	(void)unlink("textdump.tar.last.gz");
284 }
285 
286 /*
287  * Check that sufficient space is available on the disk that holds the
288  * save directory.
289  */
290 static int
291 check_space(const char *savedir, off_t dumpsize, int bounds)
292 {
293 	FILE *fp;
294 	off_t available, minfree, spacefree, totfree, needed;
295 	struct statfs fsbuf;
296 	char buf[100];
297 
298 	if (statfs(".", &fsbuf) < 0) {
299 		syslog(LOG_ERR, "%s: %m", savedir);
300 		exit(1);
301 	}
302 	spacefree = ((off_t) fsbuf.f_bavail * fsbuf.f_bsize) / 1024;
303 	totfree = ((off_t) fsbuf.f_bfree * fsbuf.f_bsize) / 1024;
304 
305 	if ((fp = fopen("minfree", "r")) == NULL)
306 		minfree = 0;
307 	else {
308 		if (fgets(buf, sizeof(buf), fp) == NULL)
309 			minfree = 0;
310 		else {
311 			char *endp;
312 
313 			errno = 0;
314 			minfree = strtoll(buf, &endp, 10);
315 			if (minfree == 0 && errno != 0)
316 				minfree = -1;
317 			else {
318 				while (*endp != '\0' && isspace(*endp))
319 					endp++;
320 				if (*endp != '\0' || minfree < 0)
321 					minfree = -1;
322 			}
323 			if (minfree < 0)
324 				syslog(LOG_WARNING,
325 				    "`minfree` didn't contain a valid size "
326 				    "(`%s`). Defaulting to 0", buf);
327 		}
328 		(void)fclose(fp);
329 	}
330 
331 	available = minfree > 0 ? spacefree - minfree : totfree;
332 	needed = dumpsize / 1024 + 2;	/* 2 for info file */
333 	needed -= saved_dump_size(bounds);
334 	if (available < needed) {
335 		syslog(LOG_WARNING,
336 		    "no dump: not enough free space on device (need at least "
337 		    "%jdkB for dump; %jdkB available; %jdkB reserved)",
338 		    (intmax_t)needed,
339 		    (intmax_t)available + minfree,
340 		    (intmax_t)minfree);
341 		return (0);
342 	}
343 	if (spacefree - needed < 0)
344 		syslog(LOG_WARNING,
345 		    "dump performed, but free space threshold crossed");
346 	return (1);
347 }
348 
349 static bool
350 compare_magic(const struct kerneldumpheader *kdh, const char *magic)
351 {
352 
353 	return (strncmp(kdh->magic, magic, sizeof(kdh->magic)) == 0);
354 }
355 
356 #define BLOCKSIZE (1<<12)
357 #define BLOCKMASK (~(BLOCKSIZE-1))
358 
359 static int
360 DoRegularFile(int fd, bool isencrypted, off_t dumpsize, char *buf,
361     const char *device, const char *filename, FILE *fp)
362 {
363 	int he, hs, nr, nw, wl;
364 	off_t dmpcnt, origsize;
365 
366 	dmpcnt = 0;
367 	origsize = dumpsize;
368 	he = 0;
369 	while (dumpsize > 0) {
370 		wl = BUFFERSIZE;
371 		if (wl > dumpsize)
372 			wl = dumpsize;
373 		nr = read(fd, buf, wl);
374 		if (nr != wl) {
375 			if (nr == 0)
376 				syslog(LOG_WARNING,
377 				    "WARNING: EOF on dump device");
378 			else
379 				syslog(LOG_ERR, "read error on %s: %m", device);
380 			nerr++;
381 			return (-1);
382 		}
383 		if (compress || isencrypted) {
384 			nw = fwrite(buf, 1, wl, fp);
385 		} else {
386 			for (nw = 0; nw < nr; nw = he) {
387 				/* find a contiguous block of zeroes */
388 				for (hs = nw; hs < nr; hs += BLOCKSIZE) {
389 					for (he = hs; he < nr && buf[he] == 0;
390 					    ++he)
391 						/* nothing */ ;
392 					/* is the hole long enough to matter? */
393 					if (he >= hs + BLOCKSIZE)
394 						break;
395 				}
396 
397 				/* back down to a block boundary */
398 				he &= BLOCKMASK;
399 
400 				/*
401 				 * 1) Don't go beyond the end of the buffer.
402 				 * 2) If the end of the buffer is less than
403 				 *    BLOCKSIZE bytes away, we're at the end
404 				 *    of the file, so just grab what's left.
405 				 */
406 				if (hs + BLOCKSIZE > nr)
407 					hs = he = nr;
408 
409 				/*
410 				 * At this point, we have a partial ordering:
411 				 *     nw <= hs <= he <= nr
412 				 * If hs > nw, buf[nw..hs] contains non-zero
413 				 * data. If he > hs, buf[hs..he] is all zeroes.
414 				 */
415 				if (hs > nw)
416 					if (fwrite(buf + nw, hs - nw, 1, fp)
417 					    != 1)
418 					break;
419 				if (he > hs)
420 					if (fseeko(fp, he - hs, SEEK_CUR) == -1)
421 						break;
422 			}
423 		}
424 		if (nw != wl) {
425 			syslog(LOG_ERR,
426 			    "write error on %s file: %m", filename);
427 			syslog(LOG_WARNING,
428 			    "WARNING: vmcore may be incomplete");
429 			nerr++;
430 			return (-1);
431 		}
432 		if (verbose) {
433 			dmpcnt += wl;
434 			printf("%llu\r", (unsigned long long)dmpcnt);
435 			fflush(stdout);
436 		}
437 		dumpsize -= wl;
438 		if (got_siginfo) {
439 			printf("%s %.1lf%%\n", filename, (100.0 - (100.0 *
440 			    (double)dumpsize / (double)origsize)));
441 			got_siginfo = 0;
442 		}
443 	}
444 	return (0);
445 }
446 
447 /*
448  * Specialized version of dump-reading logic for use with textdumps, which
449  * are written backwards from the end of the partition, and must be reversed
450  * before being written to the file.  Textdumps are small, so do a bit less
451  * work to optimize/sparsify.
452  */
453 static int
454 DoTextdumpFile(int fd, off_t dumpsize, off_t lasthd, char *buf,
455     const char *device, const char *filename, FILE *fp)
456 {
457 	int nr, nw, wl;
458 	off_t dmpcnt, totsize;
459 
460 	totsize = dumpsize;
461 	dmpcnt = 0;
462 	wl = 512;
463 	if ((dumpsize % wl) != 0) {
464 		syslog(LOG_ERR, "textdump uneven multiple of 512 on %s",
465 		    device);
466 		nerr++;
467 		return (-1);
468 	}
469 	while (dumpsize > 0) {
470 		nr = pread(fd, buf, wl, lasthd - (totsize - dumpsize) - wl);
471 		if (nr != wl) {
472 			if (nr == 0)
473 				syslog(LOG_WARNING,
474 				    "WARNING: EOF on dump device");
475 			else
476 				syslog(LOG_ERR, "read error on %s: %m", device);
477 			nerr++;
478 			return (-1);
479 		}
480 		nw = fwrite(buf, 1, wl, fp);
481 		if (nw != wl) {
482 			syslog(LOG_ERR,
483 			    "write error on %s file: %m", filename);
484 			syslog(LOG_WARNING,
485 			    "WARNING: textdump may be incomplete");
486 			nerr++;
487 			return (-1);
488 		}
489 		if (verbose) {
490 			dmpcnt += wl;
491 			printf("%llu\r", (unsigned long long)dmpcnt);
492 			fflush(stdout);
493 		}
494 		dumpsize -= wl;
495 	}
496 	return (0);
497 }
498 
499 static void
500 DoFile(const char *savedir, const char *device)
501 {
502 	xo_handle_t *xostdout, *xoinfo;
503 	static char infoname[PATH_MAX], corename[PATH_MAX], linkname[PATH_MAX];
504 	static char keyname[PATH_MAX];
505 	static char *buf = NULL;
506 	char *temp = NULL;
507 	struct kerneldumpheader kdhf, kdhl;
508 	uint8_t *dumpkey;
509 	off_t mediasize, dumpsize, firsthd, lasthd;
510 	FILE *info, *fp;
511 	mode_t oumask;
512 	int fd, fdinfo, error;
513 	int bounds, status;
514 	u_int sectorsize, xostyle;
515 	int istextdump;
516 	uint32_t dumpkeysize;
517 	bool isencrypted, ret;
518 
519 	bounds = getbounds();
520 	dumpkey = NULL;
521 	mediasize = 0;
522 	status = STATUS_UNKNOWN;
523 
524 	xostdout = xo_create_to_file(stdout, XO_STYLE_TEXT, 0);
525 	if (xostdout == NULL) {
526 		syslog(LOG_ERR, "%s: %m", infoname);
527 		return;
528 	}
529 
530 	if (maxdumps > 0 && bounds == maxdumps)
531 		bounds = 0;
532 
533 	if (buf == NULL) {
534 		buf = malloc(BUFFERSIZE);
535 		if (buf == NULL) {
536 			syslog(LOG_ERR, "%m");
537 			return;
538 		}
539 	}
540 
541 	if (verbose)
542 		printf("checking for kernel dump on device %s\n", device);
543 
544 	fd = open(device, (checkfor || keep) ? O_RDONLY : O_RDWR);
545 	if (fd < 0) {
546 		syslog(LOG_ERR, "%s: %m", device);
547 		return;
548 	}
549 
550 	error = ioctl(fd, DIOCGMEDIASIZE, &mediasize);
551 	if (!error)
552 		error = ioctl(fd, DIOCGSECTORSIZE, &sectorsize);
553 	if (error) {
554 		syslog(LOG_ERR,
555 		    "couldn't find media and/or sector size of %s: %m", device);
556 		goto closefd;
557 	}
558 
559 	if (verbose) {
560 		printf("mediasize = %lld bytes\n", (long long)mediasize);
561 		printf("sectorsize = %u bytes\n", sectorsize);
562 	}
563 
564 	if (sectorsize < sizeof(kdhl)) {
565 		syslog(LOG_ERR,
566 		    "Sector size is less the kernel dump header %zu",
567 		    sizeof(kdhl));
568 		goto closefd;
569 	}
570 
571 	lasthd = mediasize - sectorsize;
572 	temp = malloc(sectorsize);
573 	if (temp == NULL) {
574 		syslog(LOG_ERR, "%m");
575 		goto closefd;
576 	}
577 	if (lseek(fd, lasthd, SEEK_SET) != lasthd ||
578 	    read(fd, temp, sectorsize) != (ssize_t)sectorsize) {
579 		syslog(LOG_ERR,
580 		    "error reading last dump header at offset %lld in %s: %m",
581 		    (long long)lasthd, device);
582 		goto closefd;
583 	}
584 	memcpy(&kdhl, temp, sizeof(kdhl));
585 	istextdump = 0;
586 	if (compare_magic(&kdhl, TEXTDUMPMAGIC)) {
587 		if (verbose)
588 			printf("textdump magic on last dump header on %s\n",
589 			    device);
590 		istextdump = 1;
591 		if (dtoh32(kdhl.version) != KERNELDUMP_TEXT_VERSION) {
592 			syslog(LOG_ERR,
593 			    "unknown version (%d) in last dump header on %s",
594 			    dtoh32(kdhl.version), device);
595 
596 			status = STATUS_BAD;
597 			if (force == 0)
598 				goto closefd;
599 		}
600 	} else if (compare_magic(&kdhl, KERNELDUMPMAGIC)) {
601 		if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
602 			syslog(LOG_ERR,
603 			    "unknown version (%d) in last dump header on %s",
604 			    dtoh32(kdhl.version), device);
605 
606 			status = STATUS_BAD;
607 			if (force == 0)
608 				goto closefd;
609 		}
610 	} else {
611 		if (verbose)
612 			printf("magic mismatch on last dump header on %s\n",
613 			    device);
614 
615 		status = STATUS_BAD;
616 		if (force == 0)
617 			goto closefd;
618 
619 		if (compare_magic(&kdhl, KERNELDUMPMAGIC_CLEARED)) {
620 			if (verbose)
621 				printf("forcing magic on %s\n", device);
622 			memcpy(kdhl.magic, KERNELDUMPMAGIC,
623 			    sizeof kdhl.magic);
624 		} else {
625 			syslog(LOG_ERR, "unable to force dump - bad magic");
626 			goto closefd;
627 		}
628 		if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
629 			syslog(LOG_ERR,
630 			    "unknown version (%d) in last dump header on %s",
631 			    dtoh32(kdhl.version), device);
632 
633 			status = STATUS_BAD;
634 			if (force == 0)
635 				goto closefd;
636 		}
637 	}
638 
639 	nfound++;
640 	if (clear)
641 		goto nuke;
642 
643 	if (kerneldump_parity(&kdhl)) {
644 		syslog(LOG_ERR,
645 		    "parity error on last dump header on %s", device);
646 		nerr++;
647 		status = STATUS_BAD;
648 		if (force == 0)
649 			goto closefd;
650 	}
651 	dumpsize = dtoh64(kdhl.dumplength);
652 	dumpkeysize = dtoh32(kdhl.dumpkeysize);
653 	firsthd = lasthd - dumpsize - sectorsize - dumpkeysize;
654 	if (lseek(fd, firsthd, SEEK_SET) != firsthd ||
655 	    read(fd, temp, sectorsize) != (ssize_t)sectorsize) {
656 		syslog(LOG_ERR,
657 		    "error reading first dump header at offset %lld in %s: %m",
658 		    (long long)firsthd, device);
659 		nerr++;
660 		goto closefd;
661 	}
662 	memcpy(&kdhf, temp, sizeof(kdhf));
663 
664 	if (verbose >= 2) {
665 		printf("First dump headers:\n");
666 		printheader(xostdout, &kdhf, device, bounds, -1);
667 
668 		printf("\nLast dump headers:\n");
669 		printheader(xostdout, &kdhl, device, bounds, -1);
670 		printf("\n");
671 	}
672 
673 	if (memcmp(&kdhl, &kdhf, sizeof(kdhl))) {
674 		syslog(LOG_ERR,
675 		    "first and last dump headers disagree on %s", device);
676 		nerr++;
677 		status = STATUS_BAD;
678 		if (force == 0)
679 			goto closefd;
680 	} else {
681 		status = STATUS_GOOD;
682 	}
683 
684 	if (checkfor) {
685 		printf("A dump exists on %s\n", device);
686 		close(fd);
687 		exit(0);
688 	}
689 
690 	if (kdhl.panicstring[0] != '\0')
691 		syslog(LOG_ALERT, "reboot after panic: %.*s",
692 		    (int)sizeof(kdhl.panicstring), kdhl.panicstring);
693 	else
694 		syslog(LOG_ALERT, "reboot");
695 
696 	if (verbose)
697 		printf("Checking for available free space\n");
698 
699 	if (!check_space(savedir, dumpsize, bounds)) {
700 		nerr++;
701 		goto closefd;
702 	}
703 
704 	writebounds(bounds + 1);
705 
706 	saved_dump_remove(bounds);
707 
708 	snprintf(infoname, sizeof(infoname), "info.%d", bounds);
709 
710 	/*
711 	 * Create or overwrite any existing dump header files.
712 	 */
713 	fdinfo = open(infoname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
714 	if (fdinfo < 0) {
715 		syslog(LOG_ERR, "%s: %m", infoname);
716 		nerr++;
717 		goto closefd;
718 	}
719 
720 	oumask = umask(S_IRWXG|S_IRWXO); /* Restrict access to the core file. */
721 	isencrypted = (dumpkeysize > 0);
722 	if (compress) {
723 		snprintf(corename, sizeof(corename), "%s.%d.gz",
724 		    istextdump ? "textdump.tar" :
725 		    (isencrypted ? "vmcore_encrypted" : "vmcore"), bounds);
726 		fp = zopen(corename, "w");
727 	} else {
728 		snprintf(corename, sizeof(corename), "%s.%d",
729 		    istextdump ? "textdump.tar" :
730 		    (isencrypted ? "vmcore_encrypted" : "vmcore"), bounds);
731 		fp = fopen(corename, "w");
732 	}
733 	if (fp == NULL) {
734 		syslog(LOG_ERR, "%s: %m", corename);
735 		close(fdinfo);
736 		nerr++;
737 		goto closefd;
738 	}
739 	(void)umask(oumask);
740 
741 	info = fdopen(fdinfo, "w");
742 
743 	if (info == NULL) {
744 		syslog(LOG_ERR, "fdopen failed: %m");
745 		nerr++;
746 		goto closeall;
747 	}
748 
749 	xostyle = xo_get_style(NULL);
750 	xoinfo = xo_create_to_file(info, xostyle, 0);
751 	if (xoinfo == NULL) {
752 		syslog(LOG_ERR, "%s: %m", infoname);
753 		nerr++;
754 		goto closeall;
755 	}
756 	xo_open_container_h(xoinfo, "crashdump");
757 
758 	if (verbose)
759 		printheader(xostdout, &kdhl, device, bounds, status);
760 
761 	printheader(xoinfo, &kdhl, device, bounds, status);
762 	xo_close_container_h(xoinfo, "crashdump");
763 	xo_flush_h(xoinfo);
764 	xo_finish_h(xoinfo);
765 	fclose(info);
766 
767 	if (isencrypted) {
768 		dumpkey = calloc(1, dumpkeysize);
769 		if (dumpkey == NULL) {
770 			syslog(LOG_ERR, "Unable to allocate kernel dump key.");
771 			nerr++;
772 			goto closeall;
773 		}
774 
775 		if (read(fd, dumpkey, dumpkeysize) != (ssize_t)dumpkeysize) {
776 			syslog(LOG_ERR, "Unable to read kernel dump key: %m.");
777 			nerr++;
778 			goto closeall;
779 		}
780 
781 		snprintf(keyname, sizeof(keyname), "key.%d", bounds);
782 		ret = writekey(keyname, dumpkey, dumpkeysize);
783 		explicit_bzero(dumpkey, dumpkeysize);
784 		if (!ret) {
785 			nerr++;
786 			goto closeall;
787 		}
788 	}
789 
790 	syslog(LOG_NOTICE, "writing %s%score to %s/%s",
791 	    isencrypted ? "encrypted " : "", compress ? "compressed " : "",
792 	    savedir, corename);
793 
794 	if (istextdump) {
795 		if (DoTextdumpFile(fd, dumpsize, lasthd, buf, device,
796 		    corename, fp) < 0)
797 			goto closeall;
798 	} else {
799 		if (DoRegularFile(fd, isencrypted, dumpsize, buf, device,
800 		    corename, fp) < 0) {
801 			goto closeall;
802 		}
803 	}
804 	if (verbose)
805 		printf("\n");
806 
807 	if (fclose(fp) < 0) {
808 		syslog(LOG_ERR, "error on %s: %m", corename);
809 		nerr++;
810 		goto closefd;
811 	}
812 
813 	symlinks_remove();
814 	if (symlink(infoname, "info.last") == -1) {
815 		syslog(LOG_WARNING, "unable to create symlink %s/%s: %m",
816 		    savedir, "info.last");
817 	}
818 	if (isencrypted) {
819 		if (symlink(keyname, "key.last") == -1) {
820 			syslog(LOG_WARNING,
821 			    "unable to create symlink %s/%s: %m", savedir,
822 			    "key.last");
823 		}
824 	}
825 	if (compress) {
826 		snprintf(linkname, sizeof(linkname), "%s.last.gz",
827 		    istextdump ? "textdump.tar" :
828 		    (isencrypted ? "vmcore_encrypted" : "vmcore"));
829 	} else {
830 		snprintf(linkname, sizeof(linkname), "%s.last",
831 		    istextdump ? "textdump.tar" :
832 		    (isencrypted ? "vmcore_encrypted" : "vmcore"));
833 	}
834 	if (symlink(corename, linkname) == -1) {
835 		syslog(LOG_WARNING, "unable to create symlink %s/%s: %m",
836 		    savedir, linkname);
837 	}
838 
839 	nsaved++;
840 
841 	if (verbose)
842 		printf("dump saved\n");
843 
844 nuke:
845 	if (!keep) {
846 		if (verbose)
847 			printf("clearing dump header\n");
848 		memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof(kdhl.magic));
849 		memcpy(temp, &kdhl, sizeof(kdhl));
850 		if (lseek(fd, lasthd, SEEK_SET) != lasthd ||
851 		    write(fd, temp, sectorsize) != (ssize_t)sectorsize)
852 			syslog(LOG_ERR,
853 			    "error while clearing the dump header: %m");
854 	}
855 	xo_close_container_h(xostdout, "crashdump");
856 	xo_finish_h(xostdout);
857 	free(dumpkey);
858 	free(temp);
859 	close(fd);
860 	return;
861 
862 closeall:
863 	fclose(fp);
864 
865 closefd:
866 	free(dumpkey);
867 	free(temp);
868 	close(fd);
869 }
870 
871 static void
872 usage(void)
873 {
874 	xo_error("%s\n%s\n%s\n",
875 	    "usage: savecore -c [-v] [device ...]",
876 	    "       savecore -C [-v] [device ...]",
877 	    "       savecore [-fkvz] [-m maxdumps] [directory [device ...]]");
878 	exit(1);
879 }
880 
881 int
882 main(int argc, char **argv)
883 {
884 	const char *savedir = ".";
885 	struct fstab *fsp;
886 	int i, ch, error;
887 
888 	checkfor = compress = clear = force = keep = verbose = 0;
889 	nfound = nsaved = nerr = 0;
890 
891 	openlog("savecore", LOG_PERROR, LOG_DAEMON);
892 	signal(SIGINFO, infohandler);
893 
894 	argc = xo_parse_args(argc, argv);
895 	if (argc < 0)
896 		exit(1);
897 
898 	while ((ch = getopt(argc, argv, "Ccfkm:vz")) != -1)
899 		switch(ch) {
900 		case 'C':
901 			checkfor = 1;
902 			break;
903 		case 'c':
904 			clear = 1;
905 			break;
906 		case 'f':
907 			force = 1;
908 			break;
909 		case 'k':
910 			keep = 1;
911 			break;
912 		case 'm':
913 			maxdumps = atoi(optarg);
914 			if (maxdumps <= 0) {
915 				syslog(LOG_ERR, "Invalid maxdump value");
916 				exit(1);
917 			}
918 			break;
919 		case 'v':
920 			verbose++;
921 			break;
922 		case 'z':
923 			compress = 1;
924 			break;
925 		case '?':
926 		default:
927 			usage();
928 		}
929 	if (checkfor && (clear || force || keep))
930 		usage();
931 	if (clear && (compress || keep))
932 		usage();
933 	if (maxdumps > 0 && (checkfor || clear))
934 		usage();
935 	argc -= optind;
936 	argv += optind;
937 	if (argc >= 1 && !checkfor && !clear) {
938 		error = chdir(argv[0]);
939 		if (error) {
940 			syslog(LOG_ERR, "chdir(%s): %m", argv[0]);
941 			exit(1);
942 		}
943 		savedir = argv[0];
944 		argc--;
945 		argv++;
946 	}
947 	if (argc == 0) {
948 		for (;;) {
949 			fsp = getfsent();
950 			if (fsp == NULL)
951 				break;
952 			if (strcmp(fsp->fs_vfstype, "swap") &&
953 			    strcmp(fsp->fs_vfstype, "dump"))
954 				continue;
955 			DoFile(savedir, fsp->fs_spec);
956 		}
957 		endfsent();
958 	} else {
959 		for (i = 0; i < argc; i++)
960 			DoFile(savedir, argv[i]);
961 	}
962 
963 	/* Emit minimal output. */
964 	if (nfound == 0) {
965 		if (checkfor) {
966 			if (verbose)
967 				printf("No dump exists\n");
968 			exit(1);
969 		}
970 		if (verbose)
971 			syslog(LOG_WARNING, "no dumps found");
972 	} else if (nsaved == 0) {
973 		if (nerr != 0) {
974 			if (verbose)
975 				syslog(LOG_WARNING,
976 				    "unsaved dumps found but not saved");
977 			exit(1);
978 		} else if (verbose)
979 			syslog(LOG_WARNING, "no unsaved dumps found");
980 	}
981 
982 	return (0);
983 }
984 
985 static void
986 infohandler(int sig __unused)
987 {
988 	got_siginfo = 1;
989 }
990