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