xref: /freebsd/sbin/savecore/savecore.c (revision 6b3455a7665208c366849f0b2b3bc916fb97516e)
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 int checkfor, compress, clear, force, keep, verbose;	/* flags */
92 int nfound, nsaved, nerr;			/* statistics */
93 
94 extern FILE *zopen(const char *, const char *);
95 
96 static void
97 printheader(FILE *f, const struct kerneldumpheader *h, const char *device,
98     int bounds)
99 {
100 	uint64_t dumplen;
101 	time_t t;
102 
103 	fprintf(f, "Good dump found on device %s\n", device);
104 	fprintf(f, "  Architecture: %s\n", h->architecture);
105 	fprintf(f, "  Architecture version: %d\n",
106 	    dtoh32(h->architectureversion));
107 	dumplen = dtoh64(h->dumplength);
108 	fprintf(f, "  Dump length: %lldB (%lld MB)\n", (long long)dumplen,
109 	    (long long)(dumplen >> 20));
110 	fprintf(f, "  Blocksize: %d\n", dtoh32(h->blocksize));
111 	t = dtoh64(h->dumptime);
112 	fprintf(f, "  Dumptime: %s", ctime(&t));
113 	fprintf(f, "  Hostname: %s\n", h->hostname);
114 	fprintf(f, "  Versionstring: %s", h->versionstring);
115 	fprintf(f, "  Panicstring: %s\n", h->panicstring);
116 	fprintf(f, "  Bounds: %d\n", bounds);
117 	fflush(f);
118 }
119 
120 static int
121 getbounds(void) {
122 	FILE *fp;
123 	char buf[6];
124 	int ret;
125 
126 	ret = 0;
127 
128 	if ((fp = fopen("bounds", "r")) == NULL) {
129 		syslog(LOG_WARNING, "unable to open bounds file, using 0");
130 		goto newfile;
131 	}
132 
133 	if (fgets(buf, sizeof buf, fp) == NULL) {
134 		syslog(LOG_WARNING, "unable to read from bounds, using 0");
135 		fclose(fp);
136 		goto newfile;
137 	}
138 
139 	errno = 0;
140 	ret = (int)strtol(buf, NULL, 10);
141 	if (ret == 0 && (errno == EINVAL || errno == ERANGE))
142 		syslog(LOG_WARNING, "invalid value found in bounds, using 0");
143 
144 newfile:
145 
146 	if ((fp = fopen("bounds", "w")) == NULL) {
147 		syslog(LOG_WARNING, "unable to write to bounds file: %m");
148 		goto done;
149 	}
150 
151 	if (verbose)
152 		printf("bounds number: %d\n", ret);
153 
154 	fprintf(fp, "%d\n", (ret + 1));
155 	fclose(fp);
156 
157 done:
158 	return (ret);
159 }
160 
161 /*
162  * Check that sufficient space is available on the disk that holds the
163  * save directory.
164  */
165 static int
166 check_space(char *savedir, off_t dumpsize)
167 {
168 	FILE *fp;
169 	off_t minfree, spacefree, totfree, needed;
170 	struct statfs fsbuf;
171 	char buf[100], path[MAXPATHLEN];
172 
173 	if (statfs(savedir, &fsbuf) < 0) {
174 		syslog(LOG_ERR, "%s: %m", savedir);
175 		exit(1);
176 	}
177  	spacefree = ((off_t) fsbuf.f_bavail * fsbuf.f_bsize) / 1024;
178 	totfree = ((off_t) fsbuf.f_bfree * fsbuf.f_bsize) / 1024;
179 
180 	(void)snprintf(path, sizeof(path), "%s/minfree", savedir);
181 	if ((fp = fopen(path, "r")) == NULL)
182 		minfree = 0;
183 	else {
184 		if (fgets(buf, sizeof(buf), fp) == NULL)
185 			minfree = 0;
186 		else
187 			minfree = atoi(buf);
188 		(void)fclose(fp);
189 	}
190 
191 	needed = dumpsize / 1024 + 2;	/* 2 for info file */
192  	if (((minfree > 0) ? spacefree : totfree) - needed < minfree) {
193 		syslog(LOG_WARNING,
194 	"no dump, not enough free space on device (%lld available, need %lld)",
195 		    (long long)(minfree > 0 ? spacefree : totfree),
196 		    (long long)needed);
197 		return (0);
198 	}
199 	if (spacefree - needed < 0)
200 		syslog(LOG_WARNING,
201 		    "dump performed, but free space threshold crossed");
202 	return (1);
203 }
204 
205 #define BLOCKSIZE (1<<12)
206 #define BLOCKMASK (~(BLOCKSIZE-1))
207 
208 static void
209 DoFile(char *savedir, const char *device)
210 {
211 	static char *buf = NULL;
212 	struct kerneldumpheader kdhf, kdhl;
213 	off_t mediasize, dumpsize, firsthd, lasthd, dmpcnt;
214 	FILE *info, *fp;
215 	int fd, fdinfo, error, wl;
216 	int nr, nw, hs, he;
217 	int bounds;
218 	u_int sectorsize;
219 	mode_t oumask;
220 
221 	dmpcnt = 0;
222 	mediasize = 0;
223 
224 	if (buf == NULL) {
225 		buf = malloc(BUFFERSIZE);
226 		if (buf == NULL) {
227 			syslog(LOG_ERR, "%m");
228 			return;
229 		}
230 	}
231 
232 	if (verbose)
233 		printf("checking for kernel dump on device %s\n", device);
234 
235 	fd = open(device, O_RDWR);
236 	if (fd < 0) {
237 		syslog(LOG_ERR, "%s: %m", device);
238 		return;
239 	}
240 
241 	error = ioctl(fd, DIOCGMEDIASIZE, &mediasize);
242 	if (!error)
243 		error = ioctl(fd, DIOCGSECTORSIZE, &sectorsize);
244 	if (error) {
245 		syslog(LOG_ERR,
246 		    "couldn't find media and/or sector size of %s: %m", device);
247 		goto closefd;
248 	}
249 
250 	if (verbose) {
251 		printf("mediasize = %lld\n", (long long)mediasize);
252 		printf("sectorsize = %u\n", sectorsize);
253 	}
254 
255 	lasthd = mediasize - sectorsize;
256 	lseek(fd, lasthd, SEEK_SET);
257 	error = read(fd, &kdhl, sizeof kdhl);
258 	if (error != sizeof kdhl) {
259 		syslog(LOG_ERR,
260 		    "error reading last dump header at offset %lld in %s: %m",
261 		    (long long)lasthd, device);
262 		goto closefd;
263 	}
264 	if (memcmp(kdhl.magic, KERNELDUMPMAGIC, sizeof kdhl.magic)) {
265 		if (verbose)
266 			printf("magic mismatch on last dump header on %s\n",
267 			    device);
268 
269 		if (force == 0)
270 			goto closefd;
271 
272 		if (memcmp(kdhl.magic, KERNELDUMPMAGIC_CLEARED,
273 			    sizeof kdhl.magic) == 0) {
274 			if (verbose)
275 				printf("forcing magic on %s\n", device);
276 			memcpy(kdhl.magic, KERNELDUMPMAGIC,
277 			    sizeof kdhl.magic);
278 		} else {
279 			syslog(LOG_ERR, "unable to force dump - bad magic");
280 			goto closefd;
281 		}
282 	}
283 	if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
284 		syslog(LOG_ERR,
285 		    "unknown version (%d) in last dump header on %s",
286 		    dtoh32(kdhl.version), device);
287 		goto closefd;
288 	}
289 
290 	nfound++;
291 	if (clear)
292 		goto nuke;
293 
294 	if (kerneldump_parity(&kdhl)) {
295 		syslog(LOG_ERR,
296 		    "parity error on last dump header on %s", device);
297 		nerr++;
298 		goto closefd;
299 	}
300 	dumpsize = dtoh64(kdhl.dumplength);
301 	firsthd = lasthd - dumpsize - sizeof kdhf;
302 	lseek(fd, firsthd, SEEK_SET);
303 	error = read(fd, &kdhf, sizeof kdhf);
304 	if (error != sizeof kdhf) {
305 		syslog(LOG_ERR,
306 		    "error reading first dump header at offset %lld in %s: %m",
307 		    (long long)firsthd, device);
308 		nerr++;
309 		goto closefd;
310 	}
311 	if (memcmp(&kdhl, &kdhf, sizeof kdhl)) {
312 		syslog(LOG_ERR,
313 		    "first and last dump headers disagree on %s", device);
314 		nerr++;
315 		goto closefd;
316 	}
317 
318 	if (checkfor) {
319 		printf("A dump exists on %s\n", device);
320 		close(fd);
321 		exit(0);
322 	}
323 
324 	if (kdhl.panicstring[0])
325 		syslog(LOG_ALERT, "reboot after panic: %s", kdhl.panicstring);
326 	else
327 		syslog(LOG_ALERT, "reboot");
328 
329 	if (verbose)
330 		printf("Checking for available free space\n");
331 	if (!check_space(savedir, dumpsize)) {
332 		nerr++;
333 		goto closefd;
334 	}
335 
336 	bounds = getbounds();
337 
338 	sprintf(buf, "info.%d", bounds);
339 
340 	/*
341 	 * Create or overwrite any existing files.
342 	 */
343 	fdinfo = open(buf, O_WRONLY | O_CREAT | O_TRUNC, 0600);
344 	if (fdinfo < 0) {
345 		syslog(LOG_ERR, "%s: %m", buf);
346 		nerr++;
347 		goto closefd;
348 	}
349 	oumask = umask(S_IRWXG|S_IRWXO); /* Restrict access to the core file.*/
350 	if (compress) {
351 		sprintf(buf, "vmcore.%d.gz", bounds);
352 		fp = zopen(buf, "w");
353 	} else {
354 		sprintf(buf, "vmcore.%d", bounds);
355 		fp = fopen(buf, "w");
356 	}
357 	if (fp == NULL) {
358 		syslog(LOG_ERR, "%s: %m", buf);
359 		close(fdinfo);
360 		nerr++;
361 		goto closefd;
362 	}
363 	(void)umask(oumask);
364 
365 	info = fdopen(fdinfo, "w");
366 
367 	if (verbose)
368 		printheader(stdout, &kdhl, device, bounds);
369 
370 	printheader(info, &kdhl, device, bounds);
371 	fclose(info);
372 
373 	syslog(LOG_NOTICE, "writing %score to %s",
374 	    compress ? "compressed " : "", buf);
375 
376 	while (dumpsize > 0) {
377 		wl = BUFFERSIZE;
378 		if (wl > dumpsize)
379 			wl = dumpsize;
380 		nr = read(fd, buf, wl);
381 		if (nr != wl) {
382 			if (nr == 0)
383 				syslog(LOG_WARNING,
384 				    "WARNING: EOF on dump device");
385 			else
386 				syslog(LOG_ERR, "read error on %s: %m", device);
387 			nerr++;
388 			goto closeall;
389 		}
390 		if (compress) {
391 			nw = fwrite(buf, 1, wl, fp);
392 		} else {
393 			for (nw = 0; nw < nr; nw = he) {
394 			    /* find a contiguous block of zeroes */
395 			    for (hs = nw; hs < nr; hs += BLOCKSIZE) {
396 				for (he = hs; he < nr && buf[he] == 0; ++he)
397 				    /* nothing */ ;
398 				/* is the hole long enough to matter? */
399 				if (he >= hs + BLOCKSIZE)
400 				    break;
401 			    }
402 
403 			    /* back down to a block boundary */
404 			    he &= BLOCKMASK;
405 
406 			    /*
407 			     * 1) Don't go beyond the end of the buffer.
408 			     * 2) If the end of the buffer is less than
409 			     *    BLOCKSIZE bytes away, we're at the end
410 			     *    of the file, so just grab what's left.
411 			     */
412 			    if (hs + BLOCKSIZE > nr)
413 				hs = he = nr;
414 
415 			    /*
416 			     * At this point, we have a partial ordering:
417 			     *     nw <= hs <= he <= nr
418 			     * If hs > nw, buf[nw..hs] contains non-zero data.
419 			     * If he > hs, buf[hs..he] is all zeroes.
420 			     */
421 			    if (hs > nw)
422 				if (fwrite(buf + nw, hs - nw, 1, fp) != 1)
423 				    break;
424 			    if (he > hs)
425 				if (fseeko(fp, he - hs, SEEK_CUR) == -1)
426 				    break;
427 			}
428 		}
429 		if (nw != wl) {
430 			syslog(LOG_ERR,
431 			    "write error on vmcore.%d file: %m", bounds);
432 			syslog(LOG_WARNING,
433 			    "WARNING: vmcore may be incomplete");
434 			nerr++;
435 			goto closeall;
436 		}
437 		if (verbose) {
438 			dmpcnt += wl;
439 			printf("%llu\r", (unsigned long long)dmpcnt);
440 			fflush(stdout);
441 		}
442 		dumpsize -= wl;
443 	}
444 	if (verbose)
445 		printf("\n");
446 
447 	if (fclose(fp) < 0) {
448 		syslog(LOG_ERR, "error on vmcore.%d: %m", bounds);
449 		nerr++;
450 		goto closeall;
451 	}
452 	nsaved++;
453 
454 	if (verbose)
455 		printf("dump saved\n");
456 
457 nuke:
458 	if (clear || !keep) {
459 		if (verbose)
460 			printf("clearing dump header\n");
461 		memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof kdhl.magic);
462 		lseek(fd, lasthd, SEEK_SET);
463 		error = write(fd, &kdhl, sizeof kdhl);
464 		if (error != sizeof kdhl)
465 			syslog(LOG_ERR,
466 			    "error while clearing the dump header: %m");
467 	}
468 	close(fd);
469 	return;
470 
471 closeall:
472 	fclose(fp);
473 
474 closefd:
475 	close(fd);
476 }
477 
478 static void
479 usage(void)
480 {
481 	fprintf(stderr,
482 	    "usage: savecore [-Cv|-cfkvz] [directory [device...]]\n");
483 	exit (1);
484 }
485 
486 int
487 main(int argc, char **argv)
488 {
489 	int i, ch, error;
490 	struct fstab *fsp;
491 	char *savedir;
492 
493 	openlog("savecore", LOG_PERROR, LOG_DAEMON);
494 
495 	savedir = strdup(".");
496 	if (savedir == NULL) {
497 		syslog(LOG_ERR, "Cannot allocate memory");
498 		exit(1);
499 	}
500 	while ((ch = getopt(argc, argv, "Ccfkvz")) != -1)
501 		switch(ch) {
502 		case 'C':
503 			checkfor = 1;
504 			break;
505 		case 'c':
506 			clear = 1;
507 			break;
508 		case 'k':
509 			keep = 1;
510 			break;
511 		case 'v':
512 			verbose = 1;
513 			break;
514 		case 'f':
515 			force = 1;
516 			break;
517 		case 'z':
518 			compress = 1;
519 			break;
520 		case '?':
521 		default:
522 			usage();
523 		}
524 	if (checkfor && (clear || force || keep))
525 		usage();
526 	argc -= optind;
527 	argv += optind;
528 	if (argc >= 1) {
529 		error = chdir(argv[0]);
530 		if (error) {
531 			syslog(LOG_ERR, "chdir(%s): %m", argv[0]);
532 			exit(1);
533 		}
534 		savedir = argv[0];
535 		argc--;
536 		argv++;
537 	}
538 	if (argc == 0) {
539 		for (;;) {
540 			fsp = getfsent();
541 			if (fsp == NULL)
542 				break;
543 			if (strcmp(fsp->fs_vfstype, "swap") &&
544 			    strcmp(fsp->fs_vfstype, "dump"))
545 				continue;
546 			DoFile(savedir, fsp->fs_spec);
547 		}
548 	} else {
549 		for (i = 0; i < argc; i++)
550 			DoFile(savedir, argv[i]);
551 	}
552 
553 	/* Emit minimal output. */
554 	if (nfound == 0) {
555 		if (checkfor) {
556 			printf("No dump exists\n");
557 			exit(1);
558 		}
559 		syslog(LOG_WARNING, "no dumps found");
560 	}
561 	else if (nsaved == 0) {
562 		if (nerr != 0)
563 			syslog(LOG_WARNING, "unsaved dumps found but not saved");
564 		else
565 			syslog(LOG_WARNING, "no unsaved dumps found");
566 	}
567 
568 	return (0);
569 }
570