xref: /freebsd/sbin/savecore/savecore.c (revision c6ec7d31830ab1c80edae95ad5e4b9dba10c47ac)
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  * 4. 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 <errno.h>
72 #include <fcntl.h>
73 #include <fstab.h>
74 #include <paths.h>
75 #include <signal.h>
76 #include <stdarg.h>
77 #include <stdio.h>
78 #include <stdlib.h>
79 #include <string.h>
80 #include <syslog.h>
81 #include <time.h>
82 #include <unistd.h>
83 
84 /* The size of the buffer used for I/O. */
85 #define	BUFFERSIZE	(1024*1024)
86 
87 #define	STATUS_BAD	0
88 #define	STATUS_GOOD	1
89 #define	STATUS_UNKNOWN	2
90 
91 static int checkfor, compress, clear, force, keep, verbose;	/* flags */
92 static int nfound, nsaved, nerr;			/* statistics */
93 static int maxdumps;
94 
95 extern FILE *zopen(const char *, const char *);
96 
97 static sig_atomic_t got_siginfo;
98 static void infohandler(int);
99 
100 static void
101 printheader(FILE *f, const struct kerneldumpheader *h, const char *device,
102     int bounds, const int status)
103 {
104 	uint64_t dumplen;
105 	time_t t;
106 	const char *stat_str;
107 
108 	fprintf(f, "Dump header from device %s\n", device);
109 	fprintf(f, "  Architecture: %s\n", h->architecture);
110 	fprintf(f, "  Architecture Version: %u\n",
111 	    dtoh32(h->architectureversion));
112 	dumplen = dtoh64(h->dumplength);
113 	fprintf(f, "  Dump Length: %lldB (%lld MB)\n", (long long)dumplen,
114 	    (long long)(dumplen >> 20));
115 	fprintf(f, "  Blocksize: %d\n", dtoh32(h->blocksize));
116 	t = dtoh64(h->dumptime);
117 	fprintf(f, "  Dumptime: %s", ctime(&t));
118 	fprintf(f, "  Hostname: %s\n", h->hostname);
119 	fprintf(f, "  Magic: %s\n", h->magic);
120 	fprintf(f, "  Version String: %s", h->versionstring);
121 	fprintf(f, "  Panic String: %s\n", h->panicstring);
122 	fprintf(f, "  Dump Parity: %u\n", h->parity);
123 	fprintf(f, "  Bounds: %d\n", bounds);
124 
125 	switch(status) {
126 	case STATUS_BAD:
127 		stat_str = "bad";
128 		break;
129 	case STATUS_GOOD:
130 		stat_str = "good";
131 		break;
132 	default:
133 		stat_str = "unknown";
134 	}
135 	fprintf(f, "  Dump Status: %s\n", stat_str);
136 	fflush(f);
137 }
138 
139 static int
140 getbounds(void) {
141 	FILE *fp;
142 	char buf[6];
143 	int ret;
144 
145 	ret = 0;
146 
147 	if ((fp = fopen("bounds", "r")) == NULL) {
148 		if (verbose)
149 			printf("unable to open bounds file, using 0\n");
150 		return (ret);
151 	}
152 
153 	if (fgets(buf, sizeof buf, fp) == NULL) {
154 		syslog(LOG_WARNING, "unable to read from bounds, using 0");
155 		fclose(fp);
156 		return (ret);
157 	}
158 
159 	errno = 0;
160 	ret = (int)strtol(buf, NULL, 10);
161 	if (ret == 0 && (errno == EINVAL || errno == ERANGE))
162 		syslog(LOG_WARNING, "invalid value found in bounds, using 0");
163 	return (ret);
164 }
165 
166 static void
167 writebounds(int bounds) {
168 	FILE *fp;
169 
170 	if ((fp = fopen("bounds", "w")) == NULL) {
171 		syslog(LOG_WARNING, "unable to write to bounds file: %m");
172 		return;
173 	}
174 
175 	if (verbose)
176 		printf("bounds number: %d\n", bounds);
177 
178 	fprintf(fp, "%d\n", bounds);
179 	fclose(fp);
180 }
181 
182 static off_t
183 file_size(const char *path)
184 {
185 	struct stat sb;
186 
187 	/* Ignore all errors, those file may not exists. */
188 	if (stat(path, &sb) == -1)
189 		return (0);
190 	return (sb.st_size);
191 }
192 
193 static off_t
194 saved_dump_size(int bounds)
195 {
196 	static char path[PATH_MAX];
197 	off_t dumpsize;
198 
199 	dumpsize = 0;
200 
201 	(void)snprintf(path, sizeof(path), "info.%d", bounds);
202 	dumpsize += file_size(path);
203 	(void)snprintf(path, sizeof(path), "vmcore.%d", bounds);
204 	dumpsize += file_size(path);
205 	(void)snprintf(path, sizeof(path), "vmcore.%d.gz", bounds);
206 	dumpsize += file_size(path);
207 	(void)snprintf(path, sizeof(path), "textdump.tar.%d", bounds);
208 	dumpsize += file_size(path);
209 	(void)snprintf(path, sizeof(path), "textdump.tar.%d.gz", bounds);
210 	dumpsize += file_size(path);
211 
212 	return (dumpsize);
213 }
214 
215 static void
216 saved_dump_remove(int bounds)
217 {
218 	static char path[PATH_MAX];
219 
220 	(void)snprintf(path, sizeof(path), "info.%d", bounds);
221 	(void)unlink(path);
222 	(void)snprintf(path, sizeof(path), "vmcore.%d", bounds);
223 	(void)unlink(path);
224 	(void)snprintf(path, sizeof(path), "vmcore.%d.gz", bounds);
225 	(void)unlink(path);
226 	(void)snprintf(path, sizeof(path), "textdump.tar.%d", bounds);
227 	(void)unlink(path);
228 	(void)snprintf(path, sizeof(path), "textdump.tar.%d.gz", bounds);
229 	(void)unlink(path);
230 }
231 
232 static void
233 symlinks_remove(void)
234 {
235 
236 	(void)unlink("info.last");
237 	(void)unlink("vmcore.last");
238 	(void)unlink("vmcore.last.gz");
239 	(void)unlink("textdump.tar.last");
240 	(void)unlink("textdump.tar.last.gz");
241 }
242 
243 /*
244  * Check that sufficient space is available on the disk that holds the
245  * save directory.
246  */
247 static int
248 check_space(const char *savedir, off_t dumpsize, int bounds)
249 {
250 	FILE *fp;
251 	off_t minfree, spacefree, totfree, needed;
252 	struct statfs fsbuf;
253 	char buf[100];
254 
255 	if (statfs(".", &fsbuf) < 0) {
256 		syslog(LOG_ERR, "%s: %m", savedir);
257 		exit(1);
258 	}
259 	spacefree = ((off_t) fsbuf.f_bavail * fsbuf.f_bsize) / 1024;
260 	totfree = ((off_t) fsbuf.f_bfree * fsbuf.f_bsize) / 1024;
261 
262 	if ((fp = fopen("minfree", "r")) == NULL)
263 		minfree = 0;
264 	else {
265 		if (fgets(buf, sizeof(buf), fp) == NULL)
266 			minfree = 0;
267 		else
268 			minfree = atoi(buf);
269 		(void)fclose(fp);
270 	}
271 
272 	needed = dumpsize / 1024 + 2;	/* 2 for info file */
273 	needed -= saved_dump_size(bounds);
274 	if ((minfree > 0 ? spacefree : totfree) - needed < minfree) {
275 		syslog(LOG_WARNING,
276 	"no dump, not enough free space on device (%lld available, need %lld)",
277 		    (long long)(minfree > 0 ? spacefree : totfree),
278 		    (long long)needed);
279 		return (0);
280 	}
281 	if (spacefree - needed < 0)
282 		syslog(LOG_WARNING,
283 		    "dump performed, but free space threshold crossed");
284 	return (1);
285 }
286 
287 #define BLOCKSIZE (1<<12)
288 #define BLOCKMASK (~(BLOCKSIZE-1))
289 
290 static int
291 DoRegularFile(int fd, off_t dumpsize, char *buf, const char *device,
292     const char *filename, FILE *fp)
293 {
294 	int he, hs, nr, nw, wl;
295 	off_t dmpcnt, origsize;
296 
297 	dmpcnt = 0;
298 	origsize = dumpsize;
299 	he = 0;
300 	while (dumpsize > 0) {
301 		wl = BUFFERSIZE;
302 		if (wl > dumpsize)
303 			wl = dumpsize;
304 		nr = read(fd, buf, wl);
305 		if (nr != wl) {
306 			if (nr == 0)
307 				syslog(LOG_WARNING,
308 				    "WARNING: EOF on dump device");
309 			else
310 				syslog(LOG_ERR, "read error on %s: %m", device);
311 			nerr++;
312 			return (-1);
313 		}
314 		if (compress) {
315 			nw = fwrite(buf, 1, wl, fp);
316 		} else {
317 			for (nw = 0; nw < nr; nw = he) {
318 				/* find a contiguous block of zeroes */
319 				for (hs = nw; hs < nr; hs += BLOCKSIZE) {
320 					for (he = hs; he < nr && buf[he] == 0;
321 					    ++he)
322 						/* nothing */ ;
323 					/* is the hole long enough to matter? */
324 					if (he >= hs + BLOCKSIZE)
325 						break;
326 				}
327 
328 				/* back down to a block boundary */
329 				he &= BLOCKMASK;
330 
331 				/*
332 				 * 1) Don't go beyond the end of the buffer.
333 				 * 2) If the end of the buffer is less than
334 				 *    BLOCKSIZE bytes away, we're at the end
335 				 *    of the file, so just grab what's left.
336 				 */
337 				if (hs + BLOCKSIZE > nr)
338 					hs = he = nr;
339 
340 				/*
341 				 * At this point, we have a partial ordering:
342 				 *     nw <= hs <= he <= nr
343 				 * If hs > nw, buf[nw..hs] contains non-zero data.
344 				 * If he > hs, buf[hs..he] is all zeroes.
345 				 */
346 				if (hs > nw)
347 					if (fwrite(buf + nw, hs - nw, 1, fp)
348 					    != 1)
349 					break;
350 				if (he > hs)
351 					if (fseeko(fp, he - hs, SEEK_CUR) == -1)
352 						break;
353 			}
354 		}
355 		if (nw != wl) {
356 			syslog(LOG_ERR,
357 			    "write error on %s file: %m", filename);
358 			syslog(LOG_WARNING,
359 			    "WARNING: vmcore may be incomplete");
360 			nerr++;
361 			return (-1);
362 		}
363 		if (verbose) {
364 			dmpcnt += wl;
365 			printf("%llu\r", (unsigned long long)dmpcnt);
366 			fflush(stdout);
367 		}
368 		dumpsize -= wl;
369 		if (got_siginfo) {
370 			printf("%s %.1lf%%\n", filename, (100.0 - (100.0 *
371 			    (double)dumpsize / (double)origsize)));
372 			got_siginfo = 0;
373 		}
374 	}
375 	return (0);
376 }
377 
378 /*
379  * Specialized version of dump-reading logic for use with textdumps, which
380  * are written backwards from the end of the partition, and must be reversed
381  * before being written to the file.  Textdumps are small, so do a bit less
382  * work to optimize/sparsify.
383  */
384 static int
385 DoTextdumpFile(int fd, off_t dumpsize, off_t lasthd, char *buf,
386     const char *device, const char *filename, FILE *fp)
387 {
388 	int nr, nw, wl;
389 	off_t dmpcnt, totsize;
390 
391 	totsize = dumpsize;
392 	dmpcnt = 0;
393 	wl = 512;
394 	if ((dumpsize % wl) != 0) {
395 		syslog(LOG_ERR, "textdump uneven multiple of 512 on %s",
396 		    device);
397 		nerr++;
398 		return (-1);
399 	}
400 	while (dumpsize > 0) {
401 		nr = pread(fd, buf, wl, lasthd - (totsize - dumpsize) - wl);
402 		if (nr != wl) {
403 			if (nr == 0)
404 				syslog(LOG_WARNING,
405 				    "WARNING: EOF on dump device");
406 			else
407 				syslog(LOG_ERR, "read error on %s: %m", device);
408 			nerr++;
409 			return (-1);
410 		}
411 		nw = fwrite(buf, 1, wl, fp);
412 		if (nw != wl) {
413 			syslog(LOG_ERR,
414 			    "write error on %s file: %m", filename);
415 			syslog(LOG_WARNING,
416 			    "WARNING: textdump may be incomplete");
417 			nerr++;
418 			return (-1);
419 		}
420 		if (verbose) {
421 			dmpcnt += wl;
422 			printf("%llu\r", (unsigned long long)dmpcnt);
423 			fflush(stdout);
424 		}
425 		dumpsize -= wl;
426 	}
427 	return (0);
428 }
429 
430 static void
431 DoFile(const char *savedir, const char *device)
432 {
433 	static char infoname[PATH_MAX], corename[PATH_MAX], linkname[PATH_MAX];
434 	static char *buf = NULL;
435 	struct kerneldumpheader kdhf, kdhl;
436 	off_t mediasize, dumpsize, firsthd, lasthd;
437 	FILE *info, *fp;
438 	mode_t oumask;
439 	int fd, fdinfo, error;
440 	int bounds, status;
441 	u_int sectorsize;
442 	int istextdump;
443 
444 	bounds = getbounds();
445 	mediasize = 0;
446 	status = STATUS_UNKNOWN;
447 
448 	if (maxdumps > 0 && bounds == maxdumps)
449 		bounds = 0;
450 
451 	if (buf == NULL) {
452 		buf = malloc(BUFFERSIZE);
453 		if (buf == NULL) {
454 			syslog(LOG_ERR, "%m");
455 			return;
456 		}
457 	}
458 
459 	if (verbose)
460 		printf("checking for kernel dump on device %s\n", device);
461 
462 	fd = open(device, (checkfor || keep) ? O_RDONLY : O_RDWR);
463 	if (fd < 0) {
464 		syslog(LOG_ERR, "%s: %m", device);
465 		return;
466 	}
467 
468 	error = ioctl(fd, DIOCGMEDIASIZE, &mediasize);
469 	if (!error)
470 		error = ioctl(fd, DIOCGSECTORSIZE, &sectorsize);
471 	if (error) {
472 		syslog(LOG_ERR,
473 		    "couldn't find media and/or sector size of %s: %m", device);
474 		goto closefd;
475 	}
476 
477 	if (verbose) {
478 		printf("mediasize = %lld\n", (long long)mediasize);
479 		printf("sectorsize = %u\n", sectorsize);
480 	}
481 
482 	lasthd = mediasize - sectorsize;
483 	lseek(fd, lasthd, SEEK_SET);
484 	error = read(fd, &kdhl, sizeof kdhl);
485 	if (error != sizeof kdhl) {
486 		syslog(LOG_ERR,
487 		    "error reading last dump header at offset %lld in %s: %m",
488 		    (long long)lasthd, device);
489 		goto closefd;
490 	}
491 	istextdump = 0;
492 	if (strncmp(kdhl.magic, TEXTDUMPMAGIC, sizeof kdhl) == 0) {
493 		if (verbose)
494 			printf("textdump magic on last dump header on %s\n",
495 			    device);
496 		istextdump = 1;
497 		if (dtoh32(kdhl.version) != KERNELDUMP_TEXT_VERSION) {
498 			syslog(LOG_ERR,
499 			    "unknown version (%d) in last dump header on %s",
500 			    dtoh32(kdhl.version), device);
501 
502 			status = STATUS_BAD;
503 			if (force == 0)
504 				goto closefd;
505 		}
506 	} else if (memcmp(kdhl.magic, KERNELDUMPMAGIC, sizeof kdhl.magic) ==
507 	    0) {
508 		if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
509 			syslog(LOG_ERR,
510 			    "unknown version (%d) in last dump header on %s",
511 			    dtoh32(kdhl.version), device);
512 
513 			status = STATUS_BAD;
514 			if (force == 0)
515 				goto closefd;
516 		}
517 	} else {
518 		if (verbose)
519 			printf("magic mismatch on last dump header on %s\n",
520 			    device);
521 
522 		status = STATUS_BAD;
523 		if (force == 0)
524 			goto closefd;
525 
526 		if (memcmp(kdhl.magic, KERNELDUMPMAGIC_CLEARED,
527 			    sizeof kdhl.magic) == 0) {
528 			if (verbose)
529 				printf("forcing magic on %s\n", device);
530 			memcpy(kdhl.magic, KERNELDUMPMAGIC,
531 			    sizeof kdhl.magic);
532 		} else {
533 			syslog(LOG_ERR, "unable to force dump - bad magic");
534 			goto closefd;
535 		}
536 		if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
537 			syslog(LOG_ERR,
538 			    "unknown version (%d) in last dump header on %s",
539 			    dtoh32(kdhl.version), device);
540 
541 			status = STATUS_BAD;
542 			if (force == 0)
543 				goto closefd;
544 		}
545 	}
546 
547 	nfound++;
548 	if (clear)
549 		goto nuke;
550 
551 	if (kerneldump_parity(&kdhl)) {
552 		syslog(LOG_ERR,
553 		    "parity error on last dump header on %s", device);
554 		nerr++;
555 		status = STATUS_BAD;
556 		if (force == 0)
557 			goto closefd;
558 	}
559 	dumpsize = dtoh64(kdhl.dumplength);
560 	firsthd = lasthd - dumpsize - sizeof kdhf;
561 	lseek(fd, firsthd, SEEK_SET);
562 	error = read(fd, &kdhf, sizeof kdhf);
563 	if (error != sizeof kdhf) {
564 		syslog(LOG_ERR,
565 		    "error reading first dump header at offset %lld in %s: %m",
566 		    (long long)firsthd, device);
567 		nerr++;
568 		goto closefd;
569 	}
570 
571 	if (verbose >= 2) {
572 		printf("First dump headers:\n");
573 		printheader(stdout, &kdhf, device, bounds, -1);
574 
575 		printf("\nLast dump headers:\n");
576 		printheader(stdout, &kdhl, device, bounds, -1);
577 		printf("\n");
578 	}
579 
580 	if (memcmp(&kdhl, &kdhf, sizeof kdhl)) {
581 		syslog(LOG_ERR,
582 		    "first and last dump headers disagree on %s", device);
583 		nerr++;
584 		status = STATUS_BAD;
585 		if (force == 0)
586 			goto closefd;
587 	} else {
588 		status = STATUS_GOOD;
589 	}
590 
591 	if (checkfor) {
592 		printf("A dump exists on %s\n", device);
593 		close(fd);
594 		exit(0);
595 	}
596 
597 	if (kdhl.panicstring[0])
598 		syslog(LOG_ALERT, "reboot after panic: %s", kdhl.panicstring);
599 	else
600 		syslog(LOG_ALERT, "reboot");
601 
602 	if (verbose)
603 		printf("Checking for available free space\n");
604 
605 	if (!check_space(savedir, dumpsize, bounds)) {
606 		nerr++;
607 		goto closefd;
608 	}
609 
610 	writebounds(bounds + 1);
611 
612 	saved_dump_remove(bounds);
613 
614 	snprintf(infoname, sizeof(infoname), "info.%d", bounds);
615 
616 	/*
617 	 * Create or overwrite any existing dump header files.
618 	 */
619 	fdinfo = open(infoname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
620 	if (fdinfo < 0) {
621 		syslog(LOG_ERR, "%s: %m", buf);
622 		nerr++;
623 		goto closefd;
624 	}
625 	oumask = umask(S_IRWXG|S_IRWXO); /* Restrict access to the core file.*/
626 	if (compress) {
627 		snprintf(corename, sizeof(corename), "%s.%d.gz",
628 		    istextdump ? "textdump.tar" : "vmcore", bounds);
629 		fp = zopen(corename, "w");
630 	} else {
631 		snprintf(corename, sizeof(corename), "%s.%d",
632 		    istextdump ? "textdump.tar" : "vmcore", bounds);
633 		fp = fopen(corename, "w");
634 	}
635 	if (fp == NULL) {
636 		syslog(LOG_ERR, "%s: %m", corename);
637 		close(fdinfo);
638 		nerr++;
639 		goto closefd;
640 	}
641 	(void)umask(oumask);
642 
643 	info = fdopen(fdinfo, "w");
644 
645 	if (info == NULL) {
646 		syslog(LOG_ERR, "fdopen failed: %m");
647 		nerr++;
648 		goto closefd;
649 	}
650 
651 	if (verbose)
652 		printheader(stdout, &kdhl, device, bounds, status);
653 
654 	printheader(info, &kdhl, device, bounds, status);
655 	fclose(info);
656 
657 	syslog(LOG_NOTICE, "writing %score to %s/%s",
658 	    compress ? "compressed " : "", savedir, corename);
659 
660 	if (istextdump) {
661 		if (DoTextdumpFile(fd, dumpsize, lasthd, buf, device,
662 		    corename, fp) < 0)
663 			goto closeall;
664 	} else {
665 		if (DoRegularFile(fd, dumpsize, buf, device, corename, fp)
666 		    < 0)
667 			goto closeall;
668 	}
669 	if (verbose)
670 		printf("\n");
671 
672 	if (fclose(fp) < 0) {
673 		syslog(LOG_ERR, "error on %s: %m", corename);
674 		nerr++;
675 		goto closeall;
676 	}
677 
678 	symlinks_remove();
679 	if (symlink(infoname, "info.last") == -1) {
680 		syslog(LOG_WARNING, "unable to create symlink %s/%s: %m",
681 		    savedir, "info.last");
682 	}
683 	if (compress) {
684 		snprintf(linkname, sizeof(linkname), "%s.last.gz",
685 		    istextdump ? "textdump.tar" : "vmcore");
686 	} else {
687 		snprintf(linkname, sizeof(linkname), "%s.last",
688 		    istextdump ? "textdump.tar" : "vmcore");
689 	}
690 	if (symlink(corename, linkname) == -1) {
691 		syslog(LOG_WARNING, "unable to create symlink %s/%s: %m",
692 		    savedir, linkname);
693 	}
694 
695 	nsaved++;
696 
697 	if (verbose)
698 		printf("dump saved\n");
699 
700 nuke:
701 	if (!keep) {
702 		if (verbose)
703 			printf("clearing dump header\n");
704 		memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof kdhl.magic);
705 		lseek(fd, lasthd, SEEK_SET);
706 		error = write(fd, &kdhl, sizeof kdhl);
707 		if (error != sizeof kdhl)
708 			syslog(LOG_ERR,
709 			    "error while clearing the dump header: %m");
710 	}
711 	close(fd);
712 	return;
713 
714 closeall:
715 	fclose(fp);
716 
717 closefd:
718 	close(fd);
719 }
720 
721 static void
722 usage(void)
723 {
724 	fprintf(stderr, "%s\n%s\n%s\n",
725 	    "usage: savecore -c [-v] [device ...]",
726 	    "       savecore -C [-v] [device ...]",
727 	    "       savecore [-fkvz] [-m maxdumps] [directory [device ...]]");
728 	exit(1);
729 }
730 
731 int
732 main(int argc, char **argv)
733 {
734 	const char *savedir = ".";
735 	struct fstab *fsp;
736 	int i, ch, error;
737 
738 	checkfor = compress = clear = force = keep = verbose = 0;
739 	nfound = nsaved = nerr = 0;
740 
741 	openlog("savecore", LOG_PERROR, LOG_DAEMON);
742 	signal(SIGINFO, infohandler);
743 
744 	while ((ch = getopt(argc, argv, "Ccfkm:vz")) != -1)
745 		switch(ch) {
746 		case 'C':
747 			checkfor = 1;
748 			break;
749 		case 'c':
750 			clear = 1;
751 			break;
752 		case 'f':
753 			force = 1;
754 			break;
755 		case 'k':
756 			keep = 1;
757 			break;
758 		case 'm':
759 			maxdumps = atoi(optarg);
760 			if (maxdumps <= 0) {
761 				syslog(LOG_ERR, "Invalid maxdump value");
762 				exit(1);
763 			}
764 			break;
765 		case 'v':
766 			verbose++;
767 			break;
768 		case 'z':
769 			compress = 1;
770 			break;
771 		case '?':
772 		default:
773 			usage();
774 		}
775 	if (checkfor && (clear || force || keep))
776 		usage();
777 	if (clear && (compress || keep))
778 		usage();
779 	if (maxdumps > 0 && (checkfor || clear))
780 		usage();
781 	argc -= optind;
782 	argv += optind;
783 	if (argc >= 1 && !checkfor && !clear) {
784 		error = chdir(argv[0]);
785 		if (error) {
786 			syslog(LOG_ERR, "chdir(%s): %m", argv[0]);
787 			exit(1);
788 		}
789 		savedir = argv[0];
790 		argc--;
791 		argv++;
792 	}
793 	if (argc == 0) {
794 		for (;;) {
795 			fsp = getfsent();
796 			if (fsp == NULL)
797 				break;
798 			if (strcmp(fsp->fs_vfstype, "swap") &&
799 			    strcmp(fsp->fs_vfstype, "dump"))
800 				continue;
801 			DoFile(savedir, fsp->fs_spec);
802 		}
803 	} else {
804 		for (i = 0; i < argc; i++)
805 			DoFile(savedir, argv[i]);
806 	}
807 
808 	/* Emit minimal output. */
809 	if (nfound == 0) {
810 		if (checkfor) {
811 			printf("No dump exists\n");
812 			exit(1);
813 		}
814 		syslog(LOG_WARNING, "no dumps found");
815 	}
816 	else if (nsaved == 0) {
817 		if (nerr != 0)
818 			syslog(LOG_WARNING, "unsaved dumps found but not saved");
819 		else
820 			syslog(LOG_WARNING, "no unsaved dumps found");
821 	}
822 
823 	return (0);
824 }
825 
826 static void
827 infohandler(int sig __unused)
828 {
829 	got_siginfo = 1;
830 }
831