xref: /freebsd/sbin/savecore/savecore.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
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 	/*
225 	 * XXX On ia64 something breaks when the buffer is put on the
226 	 * stack. When the buffer is roughly larger than 128K the read()
227 	 * below simply fails with errno=14 (EFAULT). We work around
228 	 * this by doing a one-time allocation...
229 	 */
230 	if (buf == NULL) {
231 		buf = malloc(BUFFERSIZE);
232 		if (buf == NULL) {
233 			syslog(LOG_ERR, "%m");
234 			return;
235 		}
236 	}
237 
238 	if (verbose)
239 		printf("checking for kernel dump on device %s\n", device);
240 
241 	fd = open(device, O_RDWR);
242 	if (fd < 0) {
243 		syslog(LOG_ERR, "%s: %m", device);
244 		return;
245 	}
246 
247 	error = ioctl(fd, DIOCGMEDIASIZE, &mediasize);
248 	if (!error)
249 		error = ioctl(fd, DIOCGSECTORSIZE, &sectorsize);
250 	if (error) {
251 		syslog(LOG_ERR,
252 		    "couldn't find media and/or sector size of %s: %m", device);
253 		goto closefd;
254 	}
255 
256 	if (verbose) {
257 		printf("mediasize = %lld\n", (long long)mediasize);
258 		printf("sectorsize = %u\n", sectorsize);
259 	}
260 
261 	lasthd = mediasize - sectorsize;
262 	lseek(fd, lasthd, SEEK_SET);
263 	error = read(fd, &kdhl, sizeof kdhl);
264 	if (error != sizeof kdhl) {
265 		syslog(LOG_ERR,
266 		    "error reading last dump header at offset %lld in %s: %m",
267 		    (long long)lasthd, device);
268 		goto closefd;
269 	}
270 	if (memcmp(kdhl.magic, KERNELDUMPMAGIC, sizeof kdhl.magic)) {
271 		if (verbose)
272 			printf("magic mismatch on last dump header on %s\n",
273 			    device);
274 
275 		if (force == 0)
276 			goto closefd;
277 
278 		if (memcmp(kdhl.magic, KERNELDUMPMAGIC_CLEARED,
279 			    sizeof kdhl.magic) == 0) {
280 			if (verbose)
281 				printf("forcing magic on %s\n", device);
282 			memcpy(kdhl.magic, KERNELDUMPMAGIC,
283 			    sizeof kdhl.magic);
284 		} else {
285 			syslog(LOG_ERR, "unable to force dump - bad magic");
286 			goto closefd;
287 		}
288 	}
289 	if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
290 		syslog(LOG_ERR,
291 		    "unknown version (%d) in last dump header on %s",
292 		    dtoh32(kdhl.version), device);
293 		goto closefd;
294 	}
295 
296 	nfound++;
297 	if (clear)
298 		goto nuke;
299 
300 	if (kerneldump_parity(&kdhl)) {
301 		syslog(LOG_ERR,
302 		    "parity error on last dump header on %s", device);
303 		nerr++;
304 		goto closefd;
305 	}
306 	dumpsize = dtoh64(kdhl.dumplength);
307 	firsthd = lasthd - dumpsize - sizeof kdhf;
308 	lseek(fd, firsthd, SEEK_SET);
309 	error = read(fd, &kdhf, sizeof kdhf);
310 	if (error != sizeof kdhf) {
311 		syslog(LOG_ERR,
312 		    "error reading first dump header at offset %lld in %s: %m",
313 		    (long long)firsthd, device);
314 		nerr++;
315 		goto closefd;
316 	}
317 	if (memcmp(&kdhl, &kdhf, sizeof kdhl)) {
318 		syslog(LOG_ERR,
319 		    "first and last dump headers disagree on %s", device);
320 		nerr++;
321 		goto closefd;
322 	}
323 
324 	if (checkfor) {
325 		printf("A dump exists on %s\n", device);
326 		close(fd);
327 		exit(0);
328 	}
329 
330 	if (kdhl.panicstring[0])
331 		syslog(LOG_ALERT, "reboot after panic: %s", kdhl.panicstring);
332 	else
333 		syslog(LOG_ALERT, "reboot");
334 
335 	if (verbose)
336 		printf("Checking for available free space\n");
337 	if (!check_space(savedir, dumpsize)) {
338 		nerr++;
339 		goto closefd;
340 	}
341 
342 	bounds = getbounds();
343 
344 	sprintf(buf, "info.%d", bounds);
345 
346 	/*
347 	 * Create or overwrite any existing files.
348 	 */
349 	fdinfo = open(buf, O_WRONLY | O_CREAT | O_TRUNC, 0600);
350 	if (fdinfo < 0) {
351 		syslog(LOG_ERR, "%s: %m", buf);
352 		nerr++;
353 		goto closefd;
354 	}
355 	oumask = umask(S_IRWXG|S_IRWXO); /* Restrict access to the core file.*/
356 	if (compress) {
357 		sprintf(buf, "vmcore.%d.gz", bounds);
358 		fp = zopen(buf, "w");
359 	} else {
360 		sprintf(buf, "vmcore.%d", bounds);
361 		fp = fopen(buf, "w");
362 	}
363 	if (fp == NULL) {
364 		syslog(LOG_ERR, "%s: %m", buf);
365 		close(fdinfo);
366 		nerr++;
367 		goto closefd;
368 	}
369 	(void)umask(oumask);
370 
371 	info = fdopen(fdinfo, "w");
372 
373 	if (verbose)
374 		printheader(stdout, &kdhl, device, bounds);
375 
376 	printheader(info, &kdhl, device, bounds);
377 	fclose(info);
378 
379 	syslog(LOG_NOTICE, "writing %score to %s",
380 	    compress ? "compressed " : "", buf);
381 
382 	while (dumpsize > 0) {
383 		wl = BUFFERSIZE;
384 		if (wl > dumpsize)
385 			wl = dumpsize;
386 		nr = read(fd, buf, wl);
387 		if (nr != wl) {
388 			if (nr == 0)
389 				syslog(LOG_WARNING,
390 				    "WARNING: EOF on dump device");
391 			else
392 				syslog(LOG_ERR, "read error on %s: %m", device);
393 			nerr++;
394 			goto closeall;
395 		}
396 		if (compress) {
397 			nw = fwrite(buf, 1, wl, fp);
398 		} else {
399 			for (nw = 0; nw < nr; nw = he) {
400 			    /* find a contiguous block of zeroes */
401 			    for (hs = nw; hs < nr; hs += BLOCKSIZE) {
402 				for (he = hs; he < nr && buf[he] == 0; ++he)
403 				    /* nothing */ ;
404 				/* is the hole long enough to matter? */
405 				if (he >= hs + BLOCKSIZE)
406 				    break;
407 			    }
408 
409 			    /* back down to a block boundary */
410 			    he &= BLOCKMASK;
411 
412 			    /*
413 			     * 1) Don't go beyond the end of the buffer.
414 			     * 2) If the end of the buffer is less than
415 			     *    BLOCKSIZE bytes away, we're at the end
416 			     *    of the file, so just grab what's left.
417 			     */
418 			    if (hs + BLOCKSIZE > nr)
419 				hs = he = nr;
420 
421 			    /*
422 			     * At this point, we have a partial ordering:
423 			     *     nw <= hs <= he <= nr
424 			     * If hs > nw, buf[nw..hs] contains non-zero data.
425 			     * If he > hs, buf[hs..he] is all zeroes.
426 			     */
427 			    if (hs > nw)
428 				if (fwrite(buf + nw, hs - nw, 1, fp) != 1)
429 				    break;
430 			    if (he > hs)
431 				if (fseek(fp, he - hs, SEEK_CUR) == -1)
432 				    break;
433 			}
434 		}
435 		if (nw != wl) {
436 			syslog(LOG_ERR,
437 			    "write error on vmcore.%d file: %m", bounds);
438 			syslog(LOG_WARNING,
439 			    "WARNING: vmcore may be incomplete");
440 			nerr++;
441 			goto closeall;
442 		}
443 		if (verbose) {
444 			dmpcnt += wl;
445 			printf("%llu\r", (unsigned long long)dmpcnt);
446 			fflush(stdout);
447 		}
448 		dumpsize -= wl;
449 	}
450 	if (verbose)
451 		printf("\n");
452 
453 	if (fclose(fp) < 0) {
454 		syslog(LOG_ERR, "error on vmcore.%d: %m", bounds);
455 		nerr++;
456 		goto closeall;
457 	}
458 	nsaved++;
459 
460 	if (verbose)
461 		printf("dump saved\n");
462 
463 nuke:
464 	if (clear || !keep) {
465 		if (verbose)
466 			printf("clearing dump header\n");
467 		memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof kdhl.magic);
468 		lseek(fd, lasthd, SEEK_SET);
469 		error = write(fd, &kdhl, sizeof kdhl);
470 		if (error != sizeof kdhl)
471 			syslog(LOG_ERR,
472 			    "error while clearing the dump header: %m");
473 	}
474 	close(fd);
475 	return;
476 
477 closeall:
478 	fclose(fp);
479 
480 closefd:
481 	close(fd);
482 }
483 
484 static void
485 usage(void)
486 {
487 	fprintf(stderr, "usage: savecore [-Cv|-cfkv] [directory [device...]]\n");
488 	exit (1);
489 }
490 
491 int
492 main(int argc, char **argv)
493 {
494 	int i, ch, error;
495 	struct fstab *fsp;
496 	char *savedir;
497 
498 	openlog("savecore", LOG_PERROR, LOG_DAEMON);
499 
500 	savedir = strdup(".");
501 	if (savedir == NULL) {
502 		syslog(LOG_ERR, "Cannot allocate memory");
503 		exit(1);
504 	}
505 	while ((ch = getopt(argc, argv, "CcdfkN:vz")) != -1)
506 		switch(ch) {
507 		case 'C':
508 			checkfor = 1;
509 			break;
510 		case 'c':
511 			clear = 1;
512 			break;
513 		case 'k':
514 			keep = 1;
515 			break;
516 		case 'v':
517 			verbose = 1;
518 			break;
519 		case 'f':
520 			force = 1;
521 			break;
522 		case 'z':
523 			compress = 1;
524 			break;
525 		case 'd':	/* Obsolete */
526 		case 'N':
527 		case '?':
528 		default:
529 			usage();
530 		}
531 	if (checkfor && (clear || force || keep))
532 		usage();
533 	argc -= optind;
534 	argv += optind;
535 	if (argc >= 1) {
536 		error = chdir(argv[0]);
537 		if (error) {
538 			syslog(LOG_ERR, "chdir(%s): %m", argv[0]);
539 			exit(1);
540 		}
541 		savedir = argv[0];
542 		argc--;
543 		argv++;
544 	}
545 	if (argc == 0) {
546 		for (;;) {
547 			fsp = getfsent();
548 			if (fsp == NULL)
549 				break;
550 			if (strcmp(fsp->fs_vfstype, "swap") &&
551 			    strcmp(fsp->fs_vfstype, "dump"))
552 				continue;
553 			DoFile(savedir, fsp->fs_spec);
554 		}
555 	} else {
556 		for (i = 0; i < argc; i++)
557 			DoFile(savedir, argv[i]);
558 	}
559 
560 	/* Emit minimal output. */
561 	if (nfound == 0) {
562 		if (checkfor) {
563 			printf("No dump exists\n");
564 			exit(1);
565 		}
566 		syslog(LOG_WARNING, "no dumps found");
567 	}
568 	else if (nsaved == 0) {
569 		if (nerr != 0)
570 			syslog(LOG_WARNING, "unsaved dumps found but not saved");
571 		else
572 			syslog(LOG_WARNING, "no unsaved dumps found");
573 	}
574 
575 	return (0);
576 }
577