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