nrelease - fix/improve livecd
[dragonfly.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/param.h>
64 #include <sys/kerneldump.h>
65 #include <sys/diskslice.h>
66 #include <sys/ioctl.h>
67 #include <sys/mount.h>
68 #include <sys/stat.h>
69 #include <errno.h>
70 #include <fcntl.h>
71 #include <fstab.h>
72 #include <paths.h>
73 #include <stdarg.h>
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <string.h>
77 #include <syslog.h>
78 #include <time.h>
79 #include <unistd.h>
80
81 /* The size of the buffer used for I/O. */
82 #define BUFFERSIZE      (1024*1024)
83
84 #define STATUS_BAD      0
85 #define STATUS_GOOD     1
86 #define STATUS_UNKNOWN  2
87
88 static int checkfor, compress, clear, force, keep, verbose;     /* flags */
89 static int nfound, nsaved, nerr;                        /* statistics */
90
91 extern FILE *zopen(const char *, const char *);
92
93 static void
94 printheader(FILE *f, const struct kerneldumpheader *h, const char *device,
95     int bounds, const int status)
96 {
97         uint64_t dumplen;
98         time_t t;
99         const char *stat_str;
100
101         fprintf(f, "Dump header from device %s\n", device);
102         fprintf(f, "  Architecture: %s\n", h->architecture);
103         fprintf(f, "  Architecture Version: %u\n",
104             dtoh32(h->architectureversion));
105         dumplen = dtoh64(h->dumplength);
106         fprintf(f, "  Dump Length: %lldB (%lld MB)\n", (long long)dumplen,
107             (long long)(dumplen >> 20));
108         fprintf(f, "  Blocksize: %d\n", dtoh32(h->blocksize));
109         t = dtoh64(h->dumptime);
110         fprintf(f, "  Dumptime: %s", ctime(&t));
111         fprintf(f, "  Hostname: %s\n", h->hostname);
112         fprintf(f, "  Magic: %s\n", h->magic);
113         fprintf(f, "  Version String: %s", h->versionstring);
114         fprintf(f, "  Panic String: %s\n", h->panicstring);
115         fprintf(f, "  Dump Parity: %u\n", h->parity);
116         fprintf(f, "  Bounds: %d\n", bounds);
117
118         switch(status) {
119         case STATUS_BAD:
120                 stat_str = "bad";
121                 break;
122         case STATUS_GOOD:
123                 stat_str = "good";
124                 break;
125         default:
126                 stat_str = "unknown";
127         }
128         fprintf(f, "  Dump Status: %s\n", stat_str);
129         fflush(f);
130 }
131
132 static int
133 getbounds(void) {
134         FILE *fp;
135         char buf[6];
136         int ret;
137
138         ret = 0;
139
140         if ((fp = fopen("bounds", "r")) == NULL) {
141                 if (verbose)
142                         printf("unable to open bounds file, using 0\n");
143                 return (ret);
144         }
145
146         if (fgets(buf, sizeof buf, fp) == NULL) {
147                 syslog(LOG_WARNING, "unable to read from bounds, using 0");
148                 fclose(fp);
149                 return (ret);
150         }
151
152         errno = 0;
153         ret = (int)strtol(buf, NULL, 10);
154         if (ret == 0 && (errno == EINVAL || errno == ERANGE))
155                 syslog(LOG_WARNING, "invalid value found in bounds, using 0");
156         fclose(fp);
157         return (ret);
158 }
159
160 static void
161 writebounds(int bounds) {
162         FILE *fp;
163
164         if ((fp = fopen("bounds", "w")) == NULL) {
165                 syslog(LOG_WARNING, "unable to write to bounds file: %m");
166                 return;
167         }
168
169         if (verbose)
170                 printf("bounds number: %d\n", bounds);
171
172         fprintf(fp, "%d\n", bounds);
173         fclose(fp);
174 }
175
176 /*
177  * Check that sufficient space is available on the disk that holds the
178  * save directory.
179  */
180 static int
181 check_space(const char *savedir, off_t dumpsize)
182 {
183         FILE *fp;
184         off_t minfree, spacefree, totfree, needed;
185         struct statfs fsbuf;
186         char buf[100], path[MAXPATHLEN];
187
188         if (statfs(savedir, &fsbuf) < 0) {
189                 syslog(LOG_ERR, "%s: %m", savedir);
190                 exit(1);
191         }
192         spacefree = ((off_t) fsbuf.f_bavail * fsbuf.f_bsize) / 1024;
193         totfree = ((off_t) fsbuf.f_bfree * fsbuf.f_bsize) / 1024;
194
195         (void)snprintf(path, sizeof(path), "%s/minfree", savedir);
196         if ((fp = fopen(path, "r")) == NULL)
197                 minfree = 0;
198         else {
199                 if (fgets(buf, sizeof(buf), fp) == NULL)
200                         minfree = 0;
201                 else
202                         minfree = atoi(buf);
203                 (void)fclose(fp);
204         }
205
206         needed = dumpsize / 1024 + 2;   /* 2 for info file */
207         if (((minfree > 0) ? spacefree : totfree) - needed < minfree) {
208                 syslog(LOG_WARNING,
209         "no dump, not enough free space on device (%lld available, need %lld)",
210                     (long long)(minfree > 0 ? spacefree : totfree),
211                     (long long)needed);
212                 return (0);
213         }
214         if (spacefree - needed < 0)
215                 syslog(LOG_WARNING,
216                     "dump performed, but free space threshold crossed");
217         return (1);
218 }
219
220 #define BLOCKSIZE (1<<12)
221 #define BLOCKMASK (~(BLOCKSIZE-1))
222
223 static void
224 DoFile(const char *savedir, const char *device)
225 {
226         static char *buf = NULL;
227         struct partinfo dpart;
228         struct kerneldumpheader kdhf, kdhl;
229         off_t mediasize, dumpsize, firsthd, lasthd, dmpcnt;
230         FILE *info, *fp, *fpkern;
231         mode_t oumask;
232         int fd, fdinfo, fdkernin, error, wl;
233         int nr, nw, hs, he = 0;
234         int bounds, status;
235         u_int sectorsize;
236
237         bounds = getbounds();
238         dmpcnt = 0;
239         mediasize = 0;
240         status = STATUS_UNKNOWN;
241
242         if (buf == NULL) {
243                 buf = malloc(BUFFERSIZE);
244                 if (buf == NULL) {
245                         syslog(LOG_ERR, "%m");
246                         return;
247                 }
248         }
249
250         if (verbose)
251                 printf("checking for kernel dump on device %s\n", device);
252
253         fd = open(device, O_RDWR);
254         if (fd < 0) {
255                 syslog(LOG_ERR, "%s: %m", device);
256                 return;
257         }
258
259         bzero(&dpart, sizeof(dpart));
260         error = ioctl(fd, DIOCGPART, &dpart);
261         if (error) {
262                 syslog(LOG_ERR,
263                     "couldn't find media and/or sector size of %s: %m", device);
264                 goto closefd;
265         }
266         mediasize = dpart.media_size;
267         sectorsize = dpart.media_blksize;
268
269         if (verbose) {
270                 printf("mediasize = %lld\n", (long long)mediasize);
271                 printf("sectorsize = %u\n", sectorsize);
272         }
273
274         lasthd = mediasize - sectorsize;
275         lseek(fd, lasthd, SEEK_SET);
276         error = read(fd, &kdhl, sizeof kdhl);
277         if (error != sizeof kdhl) {
278                 syslog(LOG_ERR,
279                     "error reading last dump header at offset %lld in %s: %m",
280                     (long long)lasthd, device);
281                 goto closefd;
282         }
283         if (memcmp(kdhl.magic, KERNELDUMPMAGIC, sizeof kdhl.magic)) {
284                 if (verbose)
285                         printf("magic mismatch on last dump header on %s\n",
286                             device);
287
288                 status = STATUS_BAD;
289                 if (force == 0)
290                         goto closefd;
291
292                 if (memcmp(kdhl.magic, KERNELDUMPMAGIC_CLEARED,
293                             sizeof kdhl.magic) == 0) {
294                         if (verbose)
295                                 printf("forcing magic on %s\n", device);
296                         memcpy(kdhl.magic, KERNELDUMPMAGIC,
297                             sizeof kdhl.magic);
298                 } else {
299                         syslog(LOG_ERR, "unable to force dump - bad magic");
300                         goto closefd;
301                 }
302         }
303         if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
304                 syslog(LOG_ERR,
305                     "unknown version (%d) in last dump header on %s",
306                     dtoh32(kdhl.version), device);
307
308                 status = STATUS_BAD;
309                 if (force == 0)
310                         goto closefd;
311         }
312
313         nfound++;
314         if (clear)
315                 goto nuke;
316
317         if (kerneldump_parity(&kdhl)) {
318                 syslog(LOG_ERR,
319                     "parity error on last dump header on %s", device);
320                 nerr++;
321                 status = STATUS_BAD;
322                 if (force == 0)
323                         goto closefd;
324         }
325         dumpsize = dtoh64(kdhl.dumplength);
326         firsthd = lasthd - dumpsize - sizeof kdhf;
327         lseek(fd, firsthd, SEEK_SET);
328         error = read(fd, &kdhf, sizeof kdhf);
329         if (error != sizeof kdhf) {
330                 syslog(LOG_ERR,
331                     "error reading first dump header at offset %lld in %s: %m",
332                     (long long)firsthd, device);
333                 nerr++;
334                 goto closefd;
335         }
336
337         if (verbose >= 2) {
338                 printf("First dump headers:\n");
339                 printheader(stdout, &kdhf, device, bounds, -1);
340
341                 printf("\nLast dump headers:\n");
342                 printheader(stdout, &kdhl, device, bounds, -1);
343                 printf("\n");
344         }
345
346         if (memcmp(&kdhl, &kdhf, sizeof kdhl)) {
347                 syslog(LOG_ERR,
348                     "first and last dump headers disagree on %s", device);
349                 nerr++;
350                 status = STATUS_BAD;
351                 if (force == 0)
352                         goto closefd;
353         } else {
354                 status = STATUS_GOOD;
355         }
356
357         if (checkfor) {
358                 printf("A dump exists on %s\n", device);
359                 close(fd);
360                 exit(0);
361         }
362
363         if (kdhl.panicstring[0])
364                 syslog(LOG_ALERT, "reboot after panic: %s", kdhl.panicstring);
365         else
366                 syslog(LOG_ALERT, "reboot");
367
368         if (verbose)
369                 printf("Checking for available free space\n");
370         if (!check_space(savedir, dumpsize)) {
371                 nerr++;
372                 goto closefd;
373         }
374
375         writebounds(bounds + 1);
376
377         /*
378          * Write kernel file.
379          */
380         fdkernin = open(getbootfile(), O_RDONLY, 0);
381         if (fdkernin < 0) {
382                 syslog(LOG_ERR, "%s: %m", getbootfile());
383         }
384
385         if (compress) {
386                 sprintf(buf, "kern.%d.gz", bounds);
387                 fpkern = zopen(buf, "w");
388         } else {
389                 sprintf(buf, "kern.%d", bounds);
390                 fpkern = fopen(buf, "w");
391         }
392         if (fpkern == NULL) {
393                 syslog(LOG_ERR, "%s: %m", buf);
394                 close(fdkernin);
395         }
396
397         syslog(LOG_NOTICE, "writing %skernel to %s",
398             compress ? "compressed " : "", buf);
399
400         while ((nr = read(fdkernin, buf, BUFFERSIZE)) > 0) {
401                 nw = fwrite(buf, 1, nr, fpkern);
402                 if (nw != nr) {
403                         syslog(LOG_ERR, "kern.%d: %m", bounds);
404                         syslog(LOG_WARNING,
405                             "WARNING: kernel may be incomplete");
406                         exit(1);
407                 }
408         }
409         if (nr < 0) {
410                 syslog(LOG_ERR, "%s: %m", getbootfile());
411                 syslog(LOG_WARNING,
412                     "WARNING: kernel may be incomplete");
413                 exit(1);
414         }
415         fclose(fpkern);
416         close(fdkernin);
417
418
419         sprintf(buf, "info.%d", bounds);
420
421         /*
422          * Create or overwrite any existing dump header files.
423          */
424         fdinfo = open(buf, O_WRONLY | O_CREAT | O_TRUNC, 0600);
425         if (fdinfo < 0) {
426                 syslog(LOG_ERR, "%s: %m", buf);
427                 nerr++;
428                 goto closefd;
429         }
430         oumask = umask(S_IRWXG|S_IRWXO); /* Restrict access to the core file.*/
431         if (compress) {
432                 sprintf(buf, "vmcore.%d.gz", bounds);
433                 fp = zopen(buf, "w");
434         } else {
435                 sprintf(buf, "vmcore.%d", bounds);
436                 fp = fopen(buf, "w");
437         }
438         if (fp == NULL) {
439                 syslog(LOG_ERR, "%s: %m", buf);
440                 close(fdinfo);
441                 nerr++;
442                 goto closefd;
443         }
444         (void)umask(oumask);
445
446         info = fdopen(fdinfo, "w");
447
448         if (info == NULL) {
449                 syslog(LOG_ERR, "fdopen failed: %m");
450                 nerr++;
451                 goto closefd;
452         }
453
454         if (verbose)
455                 printheader(stdout, &kdhl, device, bounds, status);
456
457         printheader(info, &kdhl, device, bounds, status);
458         fclose(info);
459
460         syslog(LOG_NOTICE, "writing %score to %s",
461             compress ? "compressed " : "", buf);
462
463         while (dumpsize > 0) {
464                 wl = BUFFERSIZE;
465                 if (wl > dumpsize)
466                         wl = dumpsize;
467                 nr = read(fd, buf, wl);
468                 if (nr != wl) {
469                         if (nr == 0)
470                                 syslog(LOG_WARNING,
471                                     "WARNING: EOF on dump device");
472                         else
473                                 syslog(LOG_ERR, "read error on %s: %m", device);
474                         nerr++;
475                         goto closeall;
476                 }
477                 if (compress) {
478                         nw = fwrite(buf, 1, wl, fp);
479                 } else {
480                         for (nw = 0; nw < nr; nw = he) {
481                                 /* find a contiguous block of zeroes */
482                                 for (hs = nw; hs < nr; hs += BLOCKSIZE) {
483                                         for (he = hs; he < nr && buf[he] == 0;
484                                             ++he)
485                                                 /* nothing */ ;
486                                         /* is the hole long enough to matter? */
487                                         if (he >= hs + BLOCKSIZE)
488                                                 break;
489                                 }
490
491                                 /* back down to a block boundary */
492                                 he &= BLOCKMASK;
493
494                                 /*
495                                  * 1) Don't go beyond the end of the buffer.
496                                  * 2) If the end of the buffer is less than
497                                  *    BLOCKSIZE bytes away, we're at the end
498                                  *    of the file, so just grab what's left.
499                                  */
500                                 if (hs + BLOCKSIZE > nr)
501                                         hs = he = nr;
502
503                                 /*
504                                  * At this point, we have a partial ordering:
505                                  *     nw <= hs <= he <= nr
506                                  * If hs > nw, buf[nw..hs] contains non-zero data.
507                                  * If he > hs, buf[hs..he] is all zeroes.
508                                  */
509                                 if (hs > nw)
510                                         if (fwrite(buf + nw, hs - nw, 1, fp)
511                                             != 1)
512                                         break;
513                                 if (he > hs)
514                                         if (fseeko(fp, he - hs, SEEK_CUR) == -1)
515                                                 break;
516                         }
517                 }
518                 if (nw != wl) {
519                         syslog(LOG_ERR,
520                             "write error on vmcore.%d file: %m", bounds);
521                         syslog(LOG_WARNING,
522                             "WARNING: vmcore may be incomplete");
523                         nerr++;
524                         goto closeall;
525                 }
526                 if (verbose) {
527                         dmpcnt += wl;
528                         printf("%llu\r", (unsigned long long)dmpcnt);
529                         fflush(stdout);
530                 }
531                 dumpsize -= wl;
532         }
533         if (verbose)
534                 printf("\n");
535
536         if (fclose(fp) < 0) {
537                 syslog(LOG_ERR, "error on vmcore.%d: %m", bounds);
538                 nerr++;
539                 goto closeall;
540         }
541         nsaved++;
542
543         if (verbose)
544                 printf("dump saved\n");
545
546 nuke:
547         if (clear || !keep) {
548                 if (verbose)
549                         printf("clearing dump header\n");
550                 memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof kdhl.magic);
551                 lseek(fd, lasthd, SEEK_SET);
552                 error = write(fd, &kdhl, sizeof kdhl);
553                 if (error != sizeof kdhl)
554                         syslog(LOG_ERR,
555                             "error while clearing the dump header: %m");
556         }
557         close(fd);
558         return;
559
560 closeall:
561         fclose(fp);
562
563 closefd:
564         close(fd);
565 }
566
567 static void
568 usage(void)
569 {
570         fprintf(stderr, "%s\n%s\n%s\n",
571             "usage: savecore -c",
572             "       savecore -C [-v] [directory device]",
573             "       savecore [-fkvz] [directory [device ...]]");
574         exit (1);
575 }
576
577 int
578 main(int argc, char **argv)
579 {
580         const char *savedir = ".";
581         struct fstab *fsp;
582         int i, ch, error;
583
584         checkfor = compress = clear = force = keep = verbose = 0;
585         nfound = nsaved = nerr = 0;
586
587         openlog("savecore", LOG_PERROR, LOG_DAEMON);
588
589         while ((ch = getopt(argc, argv, "Ccfkvz")) != -1)
590                 switch(ch) {
591                 case 'C':
592                         checkfor = 1;
593                         break;
594                 case 'c':
595                         clear = 1;
596                         break;
597                 case 'k':
598                         keep = 1;
599                         break;
600                 case 'v':
601                         verbose++;
602                         break;
603                 case 'f':
604                         force = 1;
605                         break;
606                 case 'z':
607                         compress = 1;
608                         break;
609                 case '?':
610                 default:
611                         usage();
612                 }
613         if (checkfor && (clear || force || keep))
614                 usage();
615         argc -= optind;
616         argv += optind;
617         if (argc >= 1) {
618                 error = chdir(argv[0]);
619                 if (error) {
620                         syslog(LOG_ERR, "chdir(%s): %m", argv[0]);
621                         exit(1);
622                 }
623                 savedir = argv[0];
624                 argc--;
625                 argv++;
626         }
627         if (argc == 0) {
628                 for (;;) {
629                         fsp = getfsent();
630                         if (fsp == NULL)
631                                 break;
632                         if (strcmp(fsp->fs_vfstype, "swap") &&
633                             strcmp(fsp->fs_vfstype, "dump"))
634                                 continue;
635                         DoFile(savedir, fsp->fs_spec);
636                 }
637         } else {
638                 for (i = 0; i < argc; i++)
639                         DoFile(savedir, argv[i]);
640         }
641
642         /* Emit minimal output. */
643         if (nfound == 0) {
644                 if (checkfor) {
645                         printf("No dump exists\n");
646                         exit(1);
647                 }
648                 syslog(LOG_WARNING, "no dumps found");
649         }
650         else if (nsaved == 0) {
651                 if (nerr != 0)
652                         syslog(LOG_WARNING, "unsaved dumps found but not saved");
653                 else
654                         syslog(LOG_WARNING, "no unsaved dumps found");
655         }
656
657         return (0);
658 }