]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/savecore/savecore.c
Merge llvm, clang, lld and lldb release_40 branch 292732, and update
[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 <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 (%lld available, need %lld)",
307                     (long long)(minfree > 0 ? spacefree : totfree),
308                     (long long)needed);
309                 return (0);
310         }
311         if (spacefree - needed < 0)
312                 syslog(LOG_WARNING,
313                     "dump performed, but free space threshold crossed");
314         return (1);
315 }
316
317 #define BLOCKSIZE (1<<12)
318 #define BLOCKMASK (~(BLOCKSIZE-1))
319
320 static int
321 DoRegularFile(int fd, bool isencrypted, off_t dumpsize, char *buf,
322     const char *device, const char *filename, FILE *fp)
323 {
324         int he, hs, nr, nw, wl;
325         off_t dmpcnt, origsize;
326
327         dmpcnt = 0;
328         origsize = dumpsize;
329         he = 0;
330         while (dumpsize > 0) {
331                 wl = BUFFERSIZE;
332                 if (wl > dumpsize)
333                         wl = dumpsize;
334                 nr = read(fd, buf, wl);
335                 if (nr != wl) {
336                         if (nr == 0)
337                                 syslog(LOG_WARNING,
338                                     "WARNING: EOF on dump device");
339                         else
340                                 syslog(LOG_ERR, "read error on %s: %m", device);
341                         nerr++;
342                         return (-1);
343                 }
344                 if (compress || isencrypted) {
345                         nw = fwrite(buf, 1, wl, fp);
346                 } else {
347                         for (nw = 0; nw < nr; nw = he) {
348                                 /* find a contiguous block of zeroes */
349                                 for (hs = nw; hs < nr; hs += BLOCKSIZE) {
350                                         for (he = hs; he < nr && buf[he] == 0;
351                                             ++he)
352                                                 /* nothing */ ;
353                                         /* is the hole long enough to matter? */
354                                         if (he >= hs + BLOCKSIZE)
355                                                 break;
356                                 }
357
358                                 /* back down to a block boundary */
359                                 he &= BLOCKMASK;
360
361                                 /*
362                                  * 1) Don't go beyond the end of the buffer.
363                                  * 2) If the end of the buffer is less than
364                                  *    BLOCKSIZE bytes away, we're at the end
365                                  *    of the file, so just grab what's left.
366                                  */
367                                 if (hs + BLOCKSIZE > nr)
368                                         hs = he = nr;
369
370                                 /*
371                                  * At this point, we have a partial ordering:
372                                  *     nw <= hs <= he <= nr
373                                  * If hs > nw, buf[nw..hs] contains non-zero data.
374                                  * If he > hs, buf[hs..he] is all zeroes.
375                                  */
376                                 if (hs > nw)
377                                         if (fwrite(buf + nw, hs - nw, 1, fp)
378                                             != 1)
379                                         break;
380                                 if (he > hs)
381                                         if (fseeko(fp, he - hs, SEEK_CUR) == -1)
382                                                 break;
383                         }
384                 }
385                 if (nw != wl) {
386                         syslog(LOG_ERR,
387                             "write error on %s file: %m", filename);
388                         syslog(LOG_WARNING,
389                             "WARNING: vmcore may be incomplete");
390                         nerr++;
391                         return (-1);
392                 }
393                 if (verbose) {
394                         dmpcnt += wl;
395                         printf("%llu\r", (unsigned long long)dmpcnt);
396                         fflush(stdout);
397                 }
398                 dumpsize -= wl;
399                 if (got_siginfo) {
400                         printf("%s %.1lf%%\n", filename, (100.0 - (100.0 *
401                             (double)dumpsize / (double)origsize)));
402                         got_siginfo = 0;
403                 }
404         }
405         return (0);
406 }
407
408 /*
409  * Specialized version of dump-reading logic for use with textdumps, which
410  * are written backwards from the end of the partition, and must be reversed
411  * before being written to the file.  Textdumps are small, so do a bit less
412  * work to optimize/sparsify.
413  */
414 static int
415 DoTextdumpFile(int fd, off_t dumpsize, off_t lasthd, char *buf,
416     const char *device, const char *filename, FILE *fp)
417 {
418         int nr, nw, wl;
419         off_t dmpcnt, totsize;
420
421         totsize = dumpsize;
422         dmpcnt = 0;
423         wl = 512;
424         if ((dumpsize % wl) != 0) {
425                 syslog(LOG_ERR, "textdump uneven multiple of 512 on %s",
426                     device);
427                 nerr++;
428                 return (-1);
429         }
430         while (dumpsize > 0) {
431                 nr = pread(fd, buf, wl, lasthd - (totsize - dumpsize) - wl);
432                 if (nr != wl) {
433                         if (nr == 0)
434                                 syslog(LOG_WARNING,
435                                     "WARNING: EOF on dump device");
436                         else
437                                 syslog(LOG_ERR, "read error on %s: %m", device);
438                         nerr++;
439                         return (-1);
440                 }
441                 nw = fwrite(buf, 1, wl, fp);
442                 if (nw != wl) {
443                         syslog(LOG_ERR,
444                             "write error on %s file: %m", filename);
445                         syslog(LOG_WARNING,
446                             "WARNING: textdump may be incomplete");
447                         nerr++;
448                         return (-1);
449                 }
450                 if (verbose) {
451                         dmpcnt += wl;
452                         printf("%llu\r", (unsigned long long)dmpcnt);
453                         fflush(stdout);
454                 }
455                 dumpsize -= wl;
456         }
457         return (0);
458 }
459
460 static void
461 DoFile(const char *savedir, const char *device)
462 {
463         xo_handle_t *xostdout, *xoinfo;
464         static char infoname[PATH_MAX], corename[PATH_MAX], linkname[PATH_MAX];
465         static char keyname[PATH_MAX];
466         static char *buf = NULL;
467         char *temp = NULL;
468         struct kerneldumpheader kdhf, kdhl;
469         uint8_t *dumpkey;
470         off_t mediasize, dumpsize, firsthd, lasthd;
471         FILE *info, *fp;
472         mode_t oumask;
473         int fd, fdinfo, error;
474         int bounds, status;
475         u_int sectorsize, xostyle;
476         int istextdump;
477         uint32_t dumpkeysize;
478         bool isencrypted, ret;
479
480         bounds = getbounds();
481         mediasize = 0;
482         status = STATUS_UNKNOWN;
483
484         xostdout = xo_create_to_file(stdout, XO_STYLE_TEXT, 0);
485         if (xostdout == NULL) {
486                 syslog(LOG_ERR, "%s: %m", infoname);
487                 return;
488         }
489
490         if (maxdumps > 0 && bounds == maxdumps)
491                 bounds = 0;
492
493         if (buf == NULL) {
494                 buf = malloc(BUFFERSIZE);
495                 if (buf == NULL) {
496                         syslog(LOG_ERR, "%m");
497                         return;
498                 }
499         }
500
501         if (verbose)
502                 printf("checking for kernel dump on device %s\n", device);
503
504         fd = open(device, (checkfor || keep) ? O_RDONLY : O_RDWR);
505         if (fd < 0) {
506                 syslog(LOG_ERR, "%s: %m", device);
507                 return;
508         }
509
510         error = ioctl(fd, DIOCGMEDIASIZE, &mediasize);
511         if (!error)
512                 error = ioctl(fd, DIOCGSECTORSIZE, &sectorsize);
513         if (error) {
514                 syslog(LOG_ERR,
515                     "couldn't find media and/or sector size of %s: %m", device);
516                 goto closefd;
517         }
518
519         if (verbose) {
520                 printf("mediasize = %lld\n", (long long)mediasize);
521                 printf("sectorsize = %u\n", sectorsize);
522         }
523
524         if (sectorsize < sizeof(kdhl)) {
525                 syslog(LOG_ERR,
526                     "Sector size is less the kernel dump header %zu",
527                     sizeof(kdhl));
528                 goto closefd;
529         }
530
531         lasthd = mediasize - sectorsize;
532         temp = malloc(sectorsize);
533         if (temp == NULL) {
534                 syslog(LOG_ERR, "%m");
535                 goto closefd;
536         }
537         if (lseek(fd, lasthd, SEEK_SET) != lasthd ||
538             read(fd, temp, sectorsize) != (ssize_t)sectorsize) {
539                 syslog(LOG_ERR,
540                     "error reading last dump header at offset %lld in %s: %m",
541                     (long long)lasthd, device);
542                 goto closefd;
543         }
544         memcpy(&kdhl, temp, sizeof(kdhl));
545         istextdump = 0;
546         if (strncmp(kdhl.magic, TEXTDUMPMAGIC, sizeof kdhl) == 0) {
547                 if (verbose)
548                         printf("textdump magic on last dump header on %s\n",
549                             device);
550                 istextdump = 1;
551                 if (dtoh32(kdhl.version) != KERNELDUMP_TEXT_VERSION) {
552                         syslog(LOG_ERR,
553                             "unknown version (%d) in last dump header on %s",
554                             dtoh32(kdhl.version), device);
555
556                         status = STATUS_BAD;
557                         if (force == 0)
558                                 goto closefd;
559                 }
560         } else if (memcmp(kdhl.magic, KERNELDUMPMAGIC, sizeof kdhl.magic) ==
561             0) {
562                 if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
563                         syslog(LOG_ERR,
564                             "unknown version (%d) in last dump header on %s",
565                             dtoh32(kdhl.version), device);
566
567                         status = STATUS_BAD;
568                         if (force == 0)
569                                 goto closefd;
570                 }
571         } else {
572                 if (verbose)
573                         printf("magic mismatch on last dump header on %s\n",
574                             device);
575
576                 status = STATUS_BAD;
577                 if (force == 0)
578                         goto closefd;
579
580                 if (memcmp(kdhl.magic, KERNELDUMPMAGIC_CLEARED,
581                             sizeof kdhl.magic) == 0) {
582                         if (verbose)
583                                 printf("forcing magic on %s\n", device);
584                         memcpy(kdhl.magic, KERNELDUMPMAGIC,
585                             sizeof kdhl.magic);
586                 } else {
587                         syslog(LOG_ERR, "unable to force dump - bad magic");
588                         goto closefd;
589                 }
590                 if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
591                         syslog(LOG_ERR,
592                             "unknown version (%d) in last dump header on %s",
593                             dtoh32(kdhl.version), device);
594
595                         status = STATUS_BAD;
596                         if (force == 0)
597                                 goto closefd;
598                 }
599         }
600
601         nfound++;
602         if (clear)
603                 goto nuke;
604
605         if (kerneldump_parity(&kdhl)) {
606                 syslog(LOG_ERR,
607                     "parity error on last dump header on %s", device);
608                 nerr++;
609                 status = STATUS_BAD;
610                 if (force == 0)
611                         goto closefd;
612         }
613         dumpsize = dtoh64(kdhl.dumplength);
614         dumpkeysize = dtoh32(kdhl.dumpkeysize);
615         firsthd = lasthd - dumpsize - sectorsize - dumpkeysize;
616         if (lseek(fd, firsthd, SEEK_SET) != firsthd ||
617             read(fd, temp, sectorsize) != (ssize_t)sectorsize) {
618                 syslog(LOG_ERR,
619                     "error reading first dump header at offset %lld in %s: %m",
620                     (long long)firsthd, device);
621                 nerr++;
622                 goto closefd;
623         }
624         memcpy(&kdhf, temp, sizeof(kdhf));
625
626         if (verbose >= 2) {
627                 printf("First dump headers:\n");
628                 printheader(xostdout, &kdhf, device, bounds, -1);
629
630                 printf("\nLast dump headers:\n");
631                 printheader(xostdout, &kdhl, device, bounds, -1);
632                 printf("\n");
633         }
634
635         if (memcmp(&kdhl, &kdhf, sizeof(kdhl))) {
636                 syslog(LOG_ERR,
637                     "first and last dump headers disagree on %s", device);
638                 nerr++;
639                 status = STATUS_BAD;
640                 if (force == 0)
641                         goto closefd;
642         } else {
643                 status = STATUS_GOOD;
644         }
645
646         if (checkfor) {
647                 printf("A dump exists on %s\n", device);
648                 close(fd);
649                 exit(0);
650         }
651
652         if (kdhl.panicstring[0] != '\0')
653                 syslog(LOG_ALERT, "reboot after panic: %*s",
654                     (int)sizeof(kdhl.panicstring), kdhl.panicstring);
655         else
656                 syslog(LOG_ALERT, "reboot");
657
658         if (verbose)
659                 printf("Checking for available free space\n");
660
661         if (!check_space(savedir, dumpsize, bounds)) {
662                 nerr++;
663                 goto closefd;
664         }
665
666         writebounds(bounds + 1);
667
668         saved_dump_remove(bounds);
669
670         snprintf(infoname, sizeof(infoname), "info.%d", bounds);
671
672         /*
673          * Create or overwrite any existing dump header files.
674          */
675         fdinfo = open(infoname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
676         if (fdinfo < 0) {
677                 syslog(LOG_ERR, "%s: %m", infoname);
678                 nerr++;
679                 goto closefd;
680         }
681
682         oumask = umask(S_IRWXG|S_IRWXO); /* Restrict access to the core file.*/
683         isencrypted = (dumpkeysize > 0);
684         if (compress) {
685                 snprintf(corename, sizeof(corename), "%s.%d.gz",
686                     istextdump ? "textdump.tar" :
687                     (isencrypted ? "vmcore_encrypted" : "vmcore"), bounds);
688                 fp = zopen(corename, "w");
689         } else {
690                 snprintf(corename, sizeof(corename), "%s.%d",
691                     istextdump ? "textdump.tar" :
692                     (isencrypted ? "vmcore_encrypted" : "vmcore"), bounds);
693                 fp = fopen(corename, "w");
694         }
695         if (fp == NULL) {
696                 syslog(LOG_ERR, "%s: %m", corename);
697                 close(fdinfo);
698                 nerr++;
699                 goto closefd;
700         }
701         (void)umask(oumask);
702
703         info = fdopen(fdinfo, "w");
704
705         if (info == NULL) {
706                 syslog(LOG_ERR, "fdopen failed: %m");
707                 nerr++;
708                 goto closeall;
709         }
710
711         xostyle = xo_get_style(NULL);
712         xoinfo = xo_create_to_file(info, xostyle, 0);
713         if (xoinfo == NULL) {
714                 syslog(LOG_ERR, "%s: %m", infoname);
715                 nerr++;
716                 goto closeall;
717         }
718         xo_open_container_h(xoinfo, "crashdump");
719
720         if (verbose)
721                 printheader(xostdout, &kdhl, device, bounds, status);
722
723         printheader(xoinfo, &kdhl, device, bounds, status);
724         xo_close_container_h(xoinfo, "crashdump");
725         xo_flush_h(xoinfo);
726         xo_finish_h(xoinfo);
727         fclose(info);
728
729         if (isencrypted) {
730                 dumpkey = calloc(1, dumpkeysize);
731                 if (dumpkey == NULL) {
732                         syslog(LOG_ERR, "Unable to allocate kernel dump key.");
733                         nerr++;
734                         goto closeall;
735                 }
736
737                 if (read(fd, dumpkey, dumpkeysize) != (ssize_t)dumpkeysize) {
738                         syslog(LOG_ERR, "Unable to read kernel dump key: %m.");
739                         nerr++;
740                         goto closeall;
741                 }
742
743                 snprintf(keyname, sizeof(keyname), "key.%d", bounds);
744                 ret = writekey(keyname, dumpkey, dumpkeysize);
745                 explicit_bzero(dumpkey, dumpkeysize);
746                 if (!ret) {
747                         nerr++;
748                         goto closeall;
749                 }
750         }
751
752         syslog(LOG_NOTICE, "writing %s%score to %s/%s",
753             isencrypted ? "encrypted " : "", compress ? "compressed " : "",
754             savedir, corename);
755
756         if (istextdump) {
757                 if (DoTextdumpFile(fd, dumpsize, lasthd, buf, device,
758                     corename, fp) < 0)
759                         goto closeall;
760         } else {
761                 if (DoRegularFile(fd, isencrypted, dumpsize, buf, device,
762                     corename, fp) < 0) {
763                         goto closeall;
764                 }
765         }
766         if (verbose)
767                 printf("\n");
768
769         if (fclose(fp) < 0) {
770                 syslog(LOG_ERR, "error on %s: %m", corename);
771                 nerr++;
772                 goto closefd;
773         }
774
775         symlinks_remove();
776         if (symlink(infoname, "info.last") == -1) {
777                 syslog(LOG_WARNING, "unable to create symlink %s/%s: %m",
778                     savedir, "info.last");
779         }
780         if (isencrypted) {
781                 if (symlink(keyname, "key.last") == -1) {
782                         syslog(LOG_WARNING,
783                             "unable to create symlink %s/%s: %m", savedir,
784                             "key.last");
785                 }
786         }
787         if (compress) {
788                 snprintf(linkname, sizeof(linkname), "%s.last.gz",
789                     istextdump ? "textdump.tar" :
790                     (isencrypted ? "vmcore_encrypted" : "vmcore"));
791         } else {
792                 snprintf(linkname, sizeof(linkname), "%s.last",
793                     istextdump ? "textdump.tar" :
794                     (isencrypted ? "vmcore_encrypted" : "vmcore"));
795         }
796         if (symlink(corename, linkname) == -1) {
797                 syslog(LOG_WARNING, "unable to create symlink %s/%s: %m",
798                     savedir, linkname);
799         }
800
801         nsaved++;
802
803         if (verbose)
804                 printf("dump saved\n");
805
806 nuke:
807         if (!keep) {
808                 if (verbose)
809                         printf("clearing dump header\n");
810                 memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof(kdhl.magic));
811                 memcpy(temp, &kdhl, sizeof(kdhl));
812                 if (lseek(fd, lasthd, SEEK_SET) != lasthd ||
813                     write(fd, temp, sectorsize) != (ssize_t)sectorsize)
814                         syslog(LOG_ERR,
815                             "error while clearing the dump header: %m");
816         }
817         xo_close_container_h(xostdout, "crashdump");
818         xo_finish_h(xostdout);
819         free(temp);
820         close(fd);
821         return;
822
823 closeall:
824         fclose(fp);
825
826 closefd:
827         free(temp);
828         close(fd);
829 }
830
831 static void
832 usage(void)
833 {
834         xo_error("%s\n%s\n%s\n",
835             "usage: savecore -c [-v] [device ...]",
836             "       savecore -C [-v] [device ...]",
837             "       savecore [-fkvz] [-m maxdumps] [directory [device ...]]");
838         exit(1);
839 }
840
841 int
842 main(int argc, char **argv)
843 {
844         const char *savedir = ".";
845         struct fstab *fsp;
846         int i, ch, error;
847
848         checkfor = compress = clear = force = keep = verbose = 0;
849         nfound = nsaved = nerr = 0;
850
851         openlog("savecore", LOG_PERROR, LOG_DAEMON);
852         signal(SIGINFO, infohandler);
853
854         argc = xo_parse_args(argc, argv);
855         if (argc < 0)
856                 exit(1);
857
858         while ((ch = getopt(argc, argv, "Ccfkm:vz")) != -1)
859                 switch(ch) {
860                 case 'C':
861                         checkfor = 1;
862                         break;
863                 case 'c':
864                         clear = 1;
865                         break;
866                 case 'f':
867                         force = 1;
868                         break;
869                 case 'k':
870                         keep = 1;
871                         break;
872                 case 'm':
873                         maxdumps = atoi(optarg);
874                         if (maxdumps <= 0) {
875                                 syslog(LOG_ERR, "Invalid maxdump value");
876                                 exit(1);
877                         }
878                         break;
879                 case 'v':
880                         verbose++;
881                         break;
882                 case 'z':
883                         compress = 1;
884                         break;
885                 case '?':
886                 default:
887                         usage();
888                 }
889         if (checkfor && (clear || force || keep))
890                 usage();
891         if (clear && (compress || keep))
892                 usage();
893         if (maxdumps > 0 && (checkfor || clear))
894                 usage();
895         argc -= optind;
896         argv += optind;
897         if (argc >= 1 && !checkfor && !clear) {
898                 error = chdir(argv[0]);
899                 if (error) {
900                         syslog(LOG_ERR, "chdir(%s): %m", argv[0]);
901                         exit(1);
902                 }
903                 savedir = argv[0];
904                 argc--;
905                 argv++;
906         }
907         if (argc == 0) {
908                 for (;;) {
909                         fsp = getfsent();
910                         if (fsp == NULL)
911                                 break;
912                         if (strcmp(fsp->fs_vfstype, "swap") &&
913                             strcmp(fsp->fs_vfstype, "dump"))
914                                 continue;
915                         DoFile(savedir, fsp->fs_spec);
916                 }
917                 endfsent();
918         } else {
919                 for (i = 0; i < argc; i++)
920                         DoFile(savedir, argv[i]);
921         }
922
923         /* Emit minimal output. */
924         if (nfound == 0) {
925                 if (checkfor) {
926                         if (verbose)
927                                 printf("No dump exists\n");
928                         exit(1);
929                 }
930                 if (verbose)
931                         syslog(LOG_WARNING, "no dumps found");
932         } else if (nsaved == 0) {
933                 if (nerr != 0) {
934                         if (verbose)
935                                 syslog(LOG_WARNING, "unsaved dumps found but not saved");
936                         exit(1);
937                 } else if (verbose)
938                         syslog(LOG_WARNING, "no unsaved dumps found");
939         }
940
941         return (0);
942 }
943
944 static void
945 infohandler(int sig __unused)
946 {
947         got_siginfo = 1;
948 }