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