xref: /freebsd/sbin/savecore/savecore.c (revision e168b357aa7fe7ae2bb9b56373a3aada3ebf56d7)
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. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *	This product includes software developed by the University of
49  *	California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  */
66 
67 #include <sys/cdefs.h>
68 __FBSDID("$FreeBSD$");
69 
70 #include <sys/param.h>
71 #include <sys/disk.h>
72 #include <sys/kerneldump.h>
73 #include <sys/param.h>
74 #include <sys/mount.h>
75 #include <sys/stat.h>
76 #include <errno.h>
77 #include <fcntl.h>
78 #include <fstab.h>
79 #include <paths.h>
80 #include <stdarg.h>
81 #include <stdio.h>
82 #include <stdlib.h>
83 #include <string.h>
84 #include <syslog.h>
85 #include <time.h>
86 #include <unistd.h>
87 
88 /* The size of the buffer used for I/O. */
89 #define	BUFFERSIZE	(1024*1024)
90 
91 #define	STATUS_BAD	0
92 #define	STATUS_GOOD	1
93 #define	STATUS_UNKNOWN	2
94 
95 static int checkfor, compress, clear, force, keep, verbose;	/* flags */
96 static int nfound, nsaved, nerr;			/* statistics */
97 
98 extern FILE *zopen(const char *, const char *);
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", h->architectureversion);
111 	dumplen = dtoh64(h->dumplength);
112 	fprintf(f, "  Dump Length: %lldB (%lld MB)\n", (long long)dumplen,
113 	    (long long)(dumplen >> 20));
114 	fprintf(f, "  Blocksize: %d\n", dtoh32(h->blocksize));
115 	t = dtoh64(h->dumptime);
116 	fprintf(f, "  Dumptime: %s", ctime(&t));
117 	fprintf(f, "  Hostname: %s\n", h->hostname);
118 	fprintf(f, "  Magic: %s\n", h->magic);
119 	fprintf(f, "  Version String: %s", h->versionstring);
120 	fprintf(f, "  Panic String: %s\n", h->panicstring);
121 	fprintf(f, "  Dump Parity: %u\n", h->parity);
122 	fprintf(f, "  Bounds: %d\n", bounds);
123 
124 	switch(status) {
125 	case STATUS_BAD:
126 		stat_str = "bad";
127 		break;
128 	case STATUS_GOOD:
129 		stat_str = "good";
130 		break;
131 	default:
132 		stat_str = "unknown";
133 	}
134 	fprintf(f, "  Dump Status: %s\n", stat_str);
135 	fflush(f);
136 }
137 
138 static int
139 getbounds(void) {
140 	FILE *fp;
141 	char buf[6];
142 	int ret;
143 
144 	ret = 0;
145 
146 	if ((fp = fopen("bounds", "r")) == NULL) {
147 		syslog(LOG_WARNING, "unable to open bounds file, using 0");
148 		return (ret);
149 	}
150 
151 	if (fgets(buf, sizeof buf, fp) == NULL) {
152 		syslog(LOG_WARNING, "unable to read from bounds, using 0");
153 		fclose(fp);
154 		return (ret);
155 	}
156 
157 	errno = 0;
158 	ret = (int)strtol(buf, NULL, 10);
159 	if (ret == 0 && (errno == EINVAL || errno == ERANGE))
160 		syslog(LOG_WARNING, "invalid value found in bounds, using 0");
161 	return (ret);
162 }
163 
164 static void
165 writebounds(int bounds) {
166 	FILE *fp;
167 
168 	if ((fp = fopen("bounds", "w")) == NULL) {
169 		syslog(LOG_WARNING, "unable to write to bounds file: %m");
170 		return;
171 	}
172 
173 	if (verbose)
174 		printf("bounds number: %d\n", bounds);
175 
176 	fprintf(fp, "%d\n", bounds);
177 	fclose(fp);
178 }
179 
180 /*
181  * Check that sufficient space is available on the disk that holds the
182  * save directory.
183  */
184 static int
185 check_space(const char *savedir, off_t dumpsize)
186 {
187 	FILE *fp;
188 	off_t minfree, spacefree, totfree, needed;
189 	struct statfs fsbuf;
190 	char buf[100], path[MAXPATHLEN];
191 
192 	if (statfs(savedir, &fsbuf) < 0) {
193 		syslog(LOG_ERR, "%s: %m", savedir);
194 		exit(1);
195 	}
196  	spacefree = ((off_t) fsbuf.f_bavail * fsbuf.f_bsize) / 1024;
197 	totfree = ((off_t) fsbuf.f_bfree * fsbuf.f_bsize) / 1024;
198 
199 	(void)snprintf(path, sizeof(path), "%s/minfree", savedir);
200 	if ((fp = fopen(path, "r")) == NULL)
201 		minfree = 0;
202 	else {
203 		if (fgets(buf, sizeof(buf), fp) == NULL)
204 			minfree = 0;
205 		else
206 			minfree = atoi(buf);
207 		(void)fclose(fp);
208 	}
209 
210 	needed = dumpsize / 1024 + 2;	/* 2 for info file */
211  	if (((minfree > 0) ? spacefree : totfree) - needed < minfree) {
212 		syslog(LOG_WARNING,
213 	"no dump, not enough free space on device (%lld available, need %lld)",
214 		    (long long)(minfree > 0 ? spacefree : totfree),
215 		    (long long)needed);
216 		return (0);
217 	}
218 	if (spacefree - needed < 0)
219 		syslog(LOG_WARNING,
220 		    "dump performed, but free space threshold crossed");
221 	return (1);
222 }
223 
224 #define BLOCKSIZE (1<<12)
225 #define BLOCKMASK (~(BLOCKSIZE-1))
226 
227 static void
228 DoFile(const char *savedir, const char *device)
229 {
230 	static char *buf = NULL;
231 	struct kerneldumpheader kdhf, kdhl;
232 	off_t mediasize, dumpsize, firsthd, lasthd, dmpcnt;
233 	FILE *info, *fp;
234 	mode_t oumask;
235 	int fd, fdinfo, error, wl;
236 	int nr, nw, hs, he = 0;
237 	int bounds, status;
238 	u_int sectorsize;
239 
240 	bounds = getbounds();
241 	dmpcnt = 0;
242 	mediasize = 0;
243 	status = STATUS_UNKNOWN;
244 
245 	if (buf == NULL) {
246 		buf = malloc(BUFFERSIZE);
247 		if (buf == NULL) {
248 			syslog(LOG_ERR, "%m");
249 			return;
250 		}
251 	}
252 
253 	if (verbose)
254 		printf("checking for kernel dump on device %s\n", device);
255 
256 	fd = open(device, O_RDWR);
257 	if (fd < 0) {
258 		syslog(LOG_ERR, "%s: %m", device);
259 		return;
260 	}
261 
262 	error = ioctl(fd, DIOCGMEDIASIZE, &mediasize);
263 	if (!error)
264 		error = ioctl(fd, DIOCGSECTORSIZE, &sectorsize);
265 	if (error) {
266 		syslog(LOG_ERR,
267 		    "couldn't find media and/or sector size of %s: %m", device);
268 		goto closefd;
269 	}
270 
271 	if (verbose) {
272 		printf("mediasize = %lld\n", (long long)mediasize);
273 		printf("sectorsize = %u\n", sectorsize);
274 	}
275 
276 	lasthd = mediasize - sectorsize;
277 	lseek(fd, lasthd, SEEK_SET);
278 	error = read(fd, &kdhl, sizeof kdhl);
279 	if (error != sizeof kdhl) {
280 		syslog(LOG_ERR,
281 		    "error reading last dump header at offset %lld in %s: %m",
282 		    (long long)lasthd, device);
283 		goto closefd;
284 	}
285 	if (memcmp(kdhl.magic, KERNELDUMPMAGIC, sizeof kdhl.magic)) {
286 		if (verbose)
287 			printf("magic mismatch on last dump header on %s\n",
288 			    device);
289 
290 		status = STATUS_BAD;
291 		if (force == 0)
292 			goto closefd;
293 
294 		if (memcmp(kdhl.magic, KERNELDUMPMAGIC_CLEARED,
295 			    sizeof kdhl.magic) == 0) {
296 			if (verbose)
297 				printf("forcing magic on %s\n", device);
298 			memcpy(kdhl.magic, KERNELDUMPMAGIC,
299 			    sizeof kdhl.magic);
300 		} else {
301 			syslog(LOG_ERR, "unable to force dump - bad magic");
302 			goto closefd;
303 		}
304 	}
305 	if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
306 		syslog(LOG_ERR,
307 		    "unknown version (%d) in last dump header on %s",
308 		    dtoh32(kdhl.version), device);
309 
310 		status = STATUS_BAD;
311 		if (force == 0)
312 			goto closefd;
313 	}
314 
315 	nfound++;
316 	if (clear)
317 		goto nuke;
318 
319 	if (kerneldump_parity(&kdhl)) {
320 		syslog(LOG_ERR,
321 		    "parity error on last dump header on %s", device);
322 		nerr++;
323 		status = STATUS_BAD;
324 		if (force == 0)
325 			goto closefd;
326 	}
327 	dumpsize = dtoh64(kdhl.dumplength);
328 	firsthd = lasthd - dumpsize - sizeof kdhf;
329 	lseek(fd, firsthd, SEEK_SET);
330 	error = read(fd, &kdhf, sizeof kdhf);
331 	if (error != sizeof kdhf) {
332 		syslog(LOG_ERR,
333 		    "error reading first dump header at offset %lld in %s: %m",
334 		    (long long)firsthd, device);
335 		nerr++;
336 		goto closefd;
337 	}
338 
339 	if (verbose >= 2) {
340 		printf("First dump headers:\n");
341 		printheader(stdout, &kdhf, device, bounds, -1);
342 
343 		printf("\nLast dump headers:\n");
344 		printheader(stdout, &kdhl, device, bounds, -1);
345 		printf("\n");
346 	}
347 
348 	if (memcmp(&kdhl, &kdhf, sizeof kdhl)) {
349 		syslog(LOG_ERR,
350 		    "first and last dump headers disagree on %s", device);
351 		nerr++;
352 		status = STATUS_BAD;
353 		if (force == 0)
354 			goto closefd;
355 	} else {
356 		status = STATUS_GOOD;
357 	}
358 
359 	if (checkfor) {
360 		printf("A dump exists on %s\n", device);
361 		close(fd);
362 		exit(0);
363 	}
364 
365 	if (kdhl.panicstring[0])
366 		syslog(LOG_ALERT, "reboot after panic: %s", kdhl.panicstring);
367 	else
368 		syslog(LOG_ALERT, "reboot");
369 
370 	if (verbose)
371 		printf("Checking for available free space\n");
372 	if (!check_space(savedir, dumpsize)) {
373 		nerr++;
374 		goto closefd;
375 	}
376 
377 	writebounds(bounds + 1);
378 
379 	sprintf(buf, "info.%d", bounds);
380 
381 	/*
382 	 * Create or overwrite any existing dump header files.
383 	 */
384 	fdinfo = open(buf, O_WRONLY | O_CREAT | O_TRUNC, 0600);
385 	if (fdinfo < 0) {
386 		syslog(LOG_ERR, "%s: %m", buf);
387 		nerr++;
388 		goto closefd;
389 	}
390 	oumask = umask(S_IRWXG|S_IRWXO); /* Restrict access to the core file.*/
391 	if (compress) {
392 		sprintf(buf, "vmcore.%d.gz", bounds);
393 		fp = zopen(buf, "w");
394 	} else {
395 		sprintf(buf, "vmcore.%d", bounds);
396 		fp = fopen(buf, "w");
397 	}
398 	if (fp == NULL) {
399 		syslog(LOG_ERR, "%s: %m", buf);
400 		close(fdinfo);
401 		nerr++;
402 		goto closefd;
403 	}
404 	(void)umask(oumask);
405 
406 	info = fdopen(fdinfo, "w");
407 
408 	if (verbose)
409 		printheader(stdout, &kdhl, device, bounds, status);
410 
411 	printheader(info, &kdhl, device, bounds, status);
412 	fclose(info);
413 
414 	syslog(LOG_NOTICE, "writing %score to %s",
415 	    compress ? "compressed " : "", buf);
416 
417 	while (dumpsize > 0) {
418 		wl = BUFFERSIZE;
419 		if (wl > dumpsize)
420 			wl = dumpsize;
421 		nr = read(fd, buf, wl);
422 		if (nr != wl) {
423 			if (nr == 0)
424 				syslog(LOG_WARNING,
425 				    "WARNING: EOF on dump device");
426 			else
427 				syslog(LOG_ERR, "read error on %s: %m", device);
428 			nerr++;
429 			goto closeall;
430 		}
431 		if (compress) {
432 			nw = fwrite(buf, 1, wl, fp);
433 		} else {
434 			for (nw = 0; nw < nr; nw = he) {
435 				/* find a contiguous block of zeroes */
436 				for (hs = nw; hs < nr; hs += BLOCKSIZE) {
437 					for (he = hs; he < nr && buf[he] == 0;
438 					    ++he)
439 						/* nothing */ ;
440 					/* is the hole long enough to matter? */
441 					if (he >= hs + BLOCKSIZE)
442 						break;
443 				}
444 
445 				/* back down to a block boundary */
446 				he &= BLOCKMASK;
447 
448 				/*
449 				 * 1) Don't go beyond the end of the buffer.
450 				 * 2) If the end of the buffer is less than
451 				 *    BLOCKSIZE bytes away, we're at the end
452 				 *    of the file, so just grab what's left.
453 				 */
454 				if (hs + BLOCKSIZE > nr)
455 					hs = he = nr;
456 
457 				/*
458 				 * At this point, we have a partial ordering:
459 				 *     nw <= hs <= he <= nr
460 				 * If hs > nw, buf[nw..hs] contains non-zero data.
461 				 * If he > hs, buf[hs..he] is all zeroes.
462 				 */
463 				if (hs > nw)
464 					if (fwrite(buf + nw, hs - nw, 1, fp)
465 					    != 1)
466 					break;
467 				if (he > hs)
468 					if (fseeko(fp, he - hs, SEEK_CUR) == -1)
469 						break;
470 			}
471 		}
472 		if (nw != wl) {
473 			syslog(LOG_ERR,
474 			    "write error on vmcore.%d file: %m", bounds);
475 			syslog(LOG_WARNING,
476 			    "WARNING: vmcore may be incomplete");
477 			nerr++;
478 			goto closeall;
479 		}
480 		if (verbose) {
481 			dmpcnt += wl;
482 			printf("%llu\r", (unsigned long long)dmpcnt);
483 			fflush(stdout);
484 		}
485 		dumpsize -= wl;
486 	}
487 	if (verbose)
488 		printf("\n");
489 
490 	if (fclose(fp) < 0) {
491 		syslog(LOG_ERR, "error on vmcore.%d: %m", bounds);
492 		nerr++;
493 		goto closeall;
494 	}
495 	nsaved++;
496 
497 	if (verbose)
498 		printf("dump saved\n");
499 
500 nuke:
501 	if (clear || !keep) {
502 		if (verbose)
503 			printf("clearing dump header\n");
504 		memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof kdhl.magic);
505 		lseek(fd, lasthd, SEEK_SET);
506 		error = write(fd, &kdhl, sizeof kdhl);
507 		if (error != sizeof kdhl)
508 			syslog(LOG_ERR,
509 			    "error while clearing the dump header: %m");
510 	}
511 	close(fd);
512 	return;
513 
514 closeall:
515 	fclose(fp);
516 
517 closefd:
518 	close(fd);
519 }
520 
521 static void
522 usage(void)
523 {
524 	fprintf(stderr, "%s\n%s\n%s\n",
525 	    "usage: savecore -c",
526 	    "       savecore -C [-v] [directory device]",
527 	    "       savecore [-fkvz] [directory [device ...]]");
528 	exit (1);
529 }
530 
531 int
532 main(int argc, char **argv)
533 {
534 	const char *savedir = ".";
535 	struct fstab *fsp;
536 	int i, ch, error;
537 
538 	checkfor = compress = clear = force = keep = verbose = 0;
539 	nfound = nsaved = nerr = 0;
540 
541 	openlog("savecore", LOG_PERROR, LOG_DAEMON);
542 
543 	while ((ch = getopt(argc, argv, "Ccfkvz")) != -1)
544 		switch(ch) {
545 		case 'C':
546 			checkfor = 1;
547 			break;
548 		case 'c':
549 			clear = 1;
550 			break;
551 		case 'k':
552 			keep = 1;
553 			break;
554 		case 'v':
555 			verbose++;
556 			break;
557 		case 'f':
558 			force = 1;
559 			break;
560 		case 'z':
561 			compress = 1;
562 			break;
563 		case '?':
564 		default:
565 			usage();
566 		}
567 	if (checkfor && (clear || force || keep))
568 		usage();
569 	argc -= optind;
570 	argv += optind;
571 	if (argc >= 1) {
572 		error = chdir(argv[0]);
573 		if (error) {
574 			syslog(LOG_ERR, "chdir(%s): %m", argv[0]);
575 			exit(1);
576 		}
577 		savedir = argv[0];
578 		argc--;
579 		argv++;
580 	}
581 	if (argc == 0) {
582 		for (;;) {
583 			fsp = getfsent();
584 			if (fsp == NULL)
585 				break;
586 			if (strcmp(fsp->fs_vfstype, "swap") &&
587 			    strcmp(fsp->fs_vfstype, "dump"))
588 				continue;
589 			DoFile(savedir, fsp->fs_spec);
590 		}
591 	} else {
592 		for (i = 0; i < argc; i++)
593 			DoFile(savedir, argv[i]);
594 	}
595 
596 	/* Emit minimal output. */
597 	if (nfound == 0) {
598 		if (checkfor) {
599 			printf("No dump exists\n");
600 			exit(1);
601 		}
602 		syslog(LOG_WARNING, "no dumps found");
603 	}
604 	else if (nsaved == 0) {
605 		if (nerr != 0)
606 			syslog(LOG_WARNING, "unsaved dumps found but not saved");
607 		else
608 			syslog(LOG_WARNING, "no unsaved dumps found");
609 	}
610 
611 	return (0);
612 }
613