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