savecore.c revision 244321
1184870Syongari/*-
2184870Syongari * Copyright (c) 2002 Poul-Henning Kamp
3184870Syongari * Copyright (c) 2002 Networks Associates Technology, Inc.
4184870Syongari * All rights reserved.
5184870Syongari *
6184870Syongari * This software was developed for the FreeBSD Project by Poul-Henning Kamp
7184870Syongari * and NAI Labs, the Security Research Division of Network Associates, Inc.
8184870Syongari * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
9184870Syongari * DARPA CHATS research program.
10184870Syongari *
11184870Syongari * Redistribution and use in source and binary forms, with or without
12184870Syongari * modification, are permitted provided that the following conditions
13184870Syongari * are met:
14184870Syongari * 1. Redistributions of source code must retain the above copyright
15184870Syongari *    notice, this list of conditions and the following disclaimer.
16184870Syongari * 2. Redistributions in binary form must reproduce the above copyright
17184870Syongari *    notice, this list of conditions and the following disclaimer in the
18184870Syongari *    documentation and/or other materials provided with the distribution.
19184870Syongari * 3. The names of the authors may not be used to endorse or promote
20184870Syongari *    products derived from this software without specific prior written
21184870Syongari *    permission.
22184870Syongari *
23184870Syongari * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
24184870Syongari * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25184870Syongari * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26184870Syongari * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
27184870Syongari * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28184870Syongari * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29184870Syongari * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30184870Syongari * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31184870Syongari * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32184870Syongari * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33184870Syongari * SUCH DAMAGE.
34184870Syongari *
35184870Syongari * Copyright (c) 1986, 1992, 1993
36184870Syongari *	The Regents of the University of California.  All rights reserved.
37184870Syongari *
38184870Syongari * Redistribution and use in source and binary forms, with or without
39184870Syongari * modification, are permitted provided that the following conditions
40184870Syongari * are met:
41184870Syongari * 1. Redistributions of source code must retain the above copyright
42184870Syongari *    notice, this list of conditions and the following disclaimer.
43263957Syongari * 2. Redistributions in binary form must reproduce the above copyright
44184870Syongari *    notice, this list of conditions and the following disclaimer in the
45184870Syongari *    documentation and/or other materials provided with the distribution.
46184870Syongari * 4. Neither the name of the University nor the names of its contributors
47184870Syongari *    may be used to endorse or promote products derived from this software
48184870Syongari *    without specific prior written permission.
49184870Syongari *
50184870Syongari * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51184870Syongari * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52184870Syongari * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53184870Syongari * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54184870Syongari * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55184870Syongari * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56184870Syongari * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57184870Syongari * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58184870Syongari * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59184870Syongari * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60184870Syongari * SUCH DAMAGE.
61184870Syongari */
62184870Syongari
63184870Syongari#include <sys/cdefs.h>
64184870Syongari__FBSDID("$FreeBSD: head/sbin/savecore/savecore.c 244321 2012-12-16 23:09:27Z pjd $");
65184870Syongari
66184870Syongari#include <sys/param.h>
67184870Syongari#include <sys/disk.h>
68184870Syongari#include <sys/kerneldump.h>
69184870Syongari#include <sys/mount.h>
70184870Syongari#include <sys/stat.h>
71184870Syongari#include <errno.h>
72184870Syongari#include <fcntl.h>
73184870Syongari#include <fstab.h>
74184870Syongari#include <paths.h>
75184870Syongari#include <signal.h>
76184870Syongari#include <stdarg.h>
77184870Syongari#include <stdio.h>
78184870Syongari#include <stdlib.h>
79184870Syongari#include <string.h>
80184870Syongari#include <syslog.h>
81184870Syongari#include <time.h>
82184870Syongari#include <unistd.h>
83184870Syongari
84184870Syongari/* The size of the buffer used for I/O. */
85184870Syongari#define	BUFFERSIZE	(1024*1024)
86184870Syongari
87184870Syongari#define	STATUS_BAD	0
88184870Syongari#define	STATUS_GOOD	1
89184870Syongari#define	STATUS_UNKNOWN	2
90184870Syongari
91184870Syongaristatic int checkfor, compress, clear, force, keep, verbose;	/* flags */
92184870Syongaristatic int nfound, nsaved, nerr;			/* statistics */
93184870Syongaristatic int maxdumps;
94184870Syongari
95184870Syongariextern FILE *zopen(const char *, const char *);
96184870Syongari
97184870Syongaristatic sig_atomic_t got_siginfo;
98184870Syongaristatic void infohandler(int);
99184870Syongari
100184870Syongaristatic void
101184870Syongariprintheader(FILE *f, const struct kerneldumpheader *h, const char *device,
102184870Syongari    int bounds, const int status)
103184870Syongari{
104184870Syongari	uint64_t dumplen;
105184870Syongari	time_t t;
106184870Syongari	const char *stat_str;
107184870Syongari
108184870Syongari	fprintf(f, "Dump header from device %s\n", device);
109184870Syongari	fprintf(f, "  Architecture: %s\n", h->architecture);
110184870Syongari	fprintf(f, "  Architecture Version: %u\n",
111184870Syongari	    dtoh32(h->architectureversion));
112184870Syongari	dumplen = dtoh64(h->dumplength);
113184870Syongari	fprintf(f, "  Dump Length: %lldB (%lld MB)\n", (long long)dumplen,
114184870Syongari	    (long long)(dumplen >> 20));
115184870Syongari	fprintf(f, "  Blocksize: %d\n", dtoh32(h->blocksize));
116184870Syongari	t = dtoh64(h->dumptime);
117184870Syongari	fprintf(f, "  Dumptime: %s", ctime(&t));
118184870Syongari	fprintf(f, "  Hostname: %s\n", h->hostname);
119184870Syongari	fprintf(f, "  Magic: %s\n", h->magic);
120184870Syongari	fprintf(f, "  Version String: %s", h->versionstring);
121184870Syongari	fprintf(f, "  Panic String: %s\n", h->panicstring);
122184870Syongari	fprintf(f, "  Dump Parity: %u\n", h->parity);
123184870Syongari	fprintf(f, "  Bounds: %d\n", bounds);
124184870Syongari
125184870Syongari	switch(status) {
126184870Syongari	case STATUS_BAD:
127184870Syongari		stat_str = "bad";
128184870Syongari		break;
129184870Syongari	case STATUS_GOOD:
130184870Syongari		stat_str = "good";
131184870Syongari		break;
132184870Syongari	default:
133184870Syongari		stat_str = "unknown";
134184870Syongari	}
135184870Syongari	fprintf(f, "  Dump Status: %s\n", stat_str);
136184870Syongari	fflush(f);
137184870Syongari}
138184870Syongari
139184870Syongaristatic int
140184870Syongarigetbounds(void) {
141184870Syongari	FILE *fp;
142184870Syongari	char buf[6];
143184870Syongari	int ret;
144184870Syongari
145184870Syongari	ret = 0;
146184870Syongari
147184870Syongari	if ((fp = fopen("bounds", "r")) == NULL) {
148184870Syongari		if (verbose)
149184870Syongari			printf("unable to open bounds file, using 0\n");
150184870Syongari		return (ret);
151184870Syongari	}
152184870Syongari
153184870Syongari	if (fgets(buf, sizeof buf, fp) == NULL) {
154184870Syongari		syslog(LOG_WARNING, "unable to read from bounds, using 0");
155184870Syongari		fclose(fp);
156184870Syongari		return (ret);
157184870Syongari	}
158184870Syongari
159184870Syongari	errno = 0;
160184870Syongari	ret = (int)strtol(buf, NULL, 10);
161184870Syongari	if (ret == 0 && (errno == EINVAL || errno == ERANGE))
162184870Syongari		syslog(LOG_WARNING, "invalid value found in bounds, using 0");
163184870Syongari	return (ret);
164184870Syongari}
165184870Syongari
166184870Syongaristatic void
167184870Syongariwritebounds(int bounds) {
168184870Syongari	FILE *fp;
169184870Syongari
170184870Syongari	if ((fp = fopen("bounds", "w")) == NULL) {
171184870Syongari		syslog(LOG_WARNING, "unable to write to bounds file: %m");
172184870Syongari		return;
173184870Syongari	}
174184870Syongari
175184870Syongari	if (verbose)
176184870Syongari		printf("bounds number: %d\n", bounds);
177184870Syongari
178184870Syongari	fprintf(fp, "%d\n", bounds);
179184870Syongari	fclose(fp);
180184870Syongari}
181184870Syongari
182184870Syongaristatic off_t
183184870Syongarifile_size(const char *path)
184184870Syongari{
185184870Syongari	struct stat sb;
186184870Syongari
187184870Syongari	/* Ignore all errors, those file may not exists. */
188184870Syongari	if (stat(path, &sb) == -1)
189184870Syongari		return (0);
190184870Syongari	return (sb.st_size);
191184870Syongari}
192184870Syongari
193184870Syongaristatic off_t
194184870Syongarisaved_dump_size(int bounds)
195184870Syongari{
196184870Syongari	static char path[PATH_MAX];
197184870Syongari	off_t dumpsize;
198184870Syongari
199184870Syongari	dumpsize = 0;
200184870Syongari
201184870Syongari	(void)snprintf(path, sizeof(path), "info.%d", bounds);
202184870Syongari	dumpsize += file_size(path);
203184870Syongari	(void)snprintf(path, sizeof(path), "vmcore.%d", bounds);
204184870Syongari	dumpsize += file_size(path);
205184870Syongari	(void)snprintf(path, sizeof(path), "vmcore.%d.gz", bounds);
206184870Syongari	dumpsize += file_size(path);
207184870Syongari	(void)snprintf(path, sizeof(path), "textdump.tar.%d", bounds);
208184870Syongari	dumpsize += file_size(path);
209184870Syongari	(void)snprintf(path, sizeof(path), "textdump.tar.%d.gz", bounds);
210184870Syongari	dumpsize += file_size(path);
211184870Syongari
212184870Syongari	return (dumpsize);
213184870Syongari}
214184870Syongari
215184870Syongaristatic void
216184870Syongarisaved_dump_remove(int bounds)
217184870Syongari{
218184870Syongari	static char path[PATH_MAX];
219184870Syongari
220184870Syongari	(void)snprintf(path, sizeof(path), "info.%d", bounds);
221184870Syongari	(void)unlink(path);
222184870Syongari	(void)snprintf(path, sizeof(path), "vmcore.%d", bounds);
223184870Syongari	(void)unlink(path);
224184870Syongari	(void)snprintf(path, sizeof(path), "vmcore.%d.gz", bounds);
225184870Syongari	(void)unlink(path);
226184870Syongari	(void)snprintf(path, sizeof(path), "textdump.tar.%d", bounds);
227184870Syongari	(void)unlink(path);
228184870Syongari	(void)snprintf(path, sizeof(path), "textdump.tar.%d.gz", bounds);
229184870Syongari	(void)unlink(path);
230184870Syongari}
231184870Syongari
232184870Syongaristatic void
233184870Syongarisymlinks_remove(void)
234184870Syongari{
235184870Syongari
236184870Syongari	(void)unlink("info.last");
237184870Syongari	(void)unlink("vmcore.last");
238184870Syongari	(void)unlink("vmcore.last.gz");
239184870Syongari	(void)unlink("textdump.tar.last");
240184870Syongari	(void)unlink("textdump.tar.last.gz");
241184870Syongari}
242184870Syongari
243184870Syongari/*
244184870Syongari * Check that sufficient space is available on the disk that holds the
245184870Syongari * save directory.
246184870Syongari */
247184870Syongaristatic int
248184870Syongaricheck_space(const char *savedir, off_t dumpsize, int bounds)
249184870Syongari{
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
290static int
291DoRegularFile(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 */
384static int
385DoTextdumpFile(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
430static void
431DoFile(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
700nuke:
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
714closeall:
715	fclose(fp);
716
717closefd:
718	close(fd);
719}
720
721static void
722usage(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
731int
732main(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
826static void
827infohandler(int sig __unused)
828{
829	got_siginfo = 1;
830}
831