]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sbin/restore/tape.c
MFC r241848:
[FreeBSD/stable/8.git] / sbin / restore / tape.c
1 /*
2  * Copyright (c) 1983, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 #ifndef lint
36 #if 0
37 static char sccsid[] = "@(#)tape.c      8.9 (Berkeley) 5/1/95";
38 #endif
39 #endif /* not lint */
40
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43
44 #include <sys/param.h>
45 #include <sys/file.h>
46 #include <sys/mtio.h>
47 #include <sys/stat.h>
48 #include <sys/time.h>
49 #include <sys/extattr.h>
50 #include <sys/acl.h>
51
52 #include <ufs/ufs/extattr.h>
53 #include <ufs/ufs/dinode.h>
54 #include <protocols/dumprestore.h>
55
56 #include <errno.h>
57 #include <limits.h>
58 #include <paths.h>
59 #include <setjmp.h>
60 #include <stdint.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <time.h>
65 #include <timeconv.h>
66 #include <unistd.h>
67
68 #include "restore.h"
69 #include "extern.h"
70
71 static long     fssize = MAXBSIZE;
72 static int      mt = -1;
73 static int      pipein = 0;
74 static int      pipecmdin = 0;
75 static FILE     *popenfp = NULL;
76 static char     *magtape;
77 static int      blkcnt;
78 static int      numtrec;
79 static char     *tapebuf;
80 static union    u_spcl endoftapemark;
81 static long     byteslide = 0;
82 static long     blksread;               /* blocks read since last header */
83 static int64_t  tapeaddr = 0;           /* current TP_BSIZE tape record */
84 static long     tapesread;
85 static jmp_buf  restart;
86 static int      gettingfile = 0;        /* restart has a valid frame */
87 static char     *host = NULL;
88 static int      readmapflag;
89
90 static int      ofile;
91 static char     *map;
92 static char     lnkbuf[MAXPATHLEN + 1];
93 static int      pathlen;
94
95 int             Bcvt;           /* Swap Bytes */
96 int             oldinofmt;      /* FreeBSD 1 inode format needs cvt */
97
98 #define FLUSHTAPEBUF()  blkcnt = ntrec + 1
99
100 char *namespace_names[] = EXTATTR_NAMESPACE_NAMES;
101
102 static void      accthdr(struct s_spcl *);
103 static int       checksum(int *);
104 static void      findinode(struct s_spcl *);
105 static void      findtapeblksize(void);
106 static char     *setupextattr(int);
107 static void      xtrattr(char *, long);
108 static void      set_extattr_link(char *, void *, int);
109 static void      set_extattr_fd(int, char *, void *, int);
110 static int       gethead(struct s_spcl *);
111 static void      readtape(char *);
112 static void      setdumpnum(void);
113 static u_long    swabl(u_long);
114 static u_char   *swablong(u_char *, int);
115 static u_char   *swabshort(u_char *, int);
116 static void      terminateinput(void);
117 static void      xtrfile(char *, long);
118 static void      xtrlnkfile(char *, long);
119 static void      xtrlnkskip(char *, long);
120 static void      xtrmap(char *, long);
121 static void      xtrmapskip(char *, long);
122 static void      xtrskip(char *, long);
123
124 /*
125  * Set up an input source
126  */
127 void
128 setinput(char *source, int ispipecommand)
129 {
130         FLUSHTAPEBUF();
131         if (bflag)
132                 newtapebuf(ntrec);
133         else
134                 newtapebuf(NTREC > HIGHDENSITYTREC ? NTREC : HIGHDENSITYTREC);
135         terminal = stdin;
136
137         if (ispipecommand)
138                 pipecmdin++;
139         else
140 #ifdef RRESTORE
141         if (strchr(source, ':')) {
142                 host = source;
143                 source = strchr(host, ':');
144                 *source++ = '\0';
145                 if (rmthost(host) == 0)
146                         done(1);
147         } else
148 #endif
149         if (strcmp(source, "-") == 0) {
150                 /*
151                  * Since input is coming from a pipe we must establish
152                  * our own connection to the terminal.
153                  */
154                 terminal = fopen(_PATH_TTY, "r");
155                 if (terminal == NULL) {
156                         (void)fprintf(stderr, "cannot open %s: %s\n",
157                             _PATH_TTY, strerror(errno));
158                         terminal = fopen(_PATH_DEVNULL, "r");
159                         if (terminal == NULL) {
160                                 (void)fprintf(stderr, "cannot open %s: %s\n",
161                                     _PATH_DEVNULL, strerror(errno));
162                                 done(1);
163                         }
164                 }
165                 pipein++;
166         }
167         /* no longer need or want root privileges */
168         if (setuid(getuid()) != 0) {
169                 fprintf(stderr, "setuid failed\n");
170                 done(1);
171         }
172         magtape = strdup(source);
173         if (magtape == NULL) {
174                 fprintf(stderr, "Cannot allocate space for magtape buffer\n");
175                 done(1);
176         }
177 }
178
179 void
180 newtapebuf(long size)
181 {
182         static int tapebufsize = -1;
183
184         ntrec = size;
185         if (size <= tapebufsize)
186                 return;
187         if (tapebuf != NULL)
188                 free(tapebuf - TP_BSIZE);
189         tapebuf = malloc((size+1) * TP_BSIZE);
190         if (tapebuf == NULL) {
191                 fprintf(stderr, "Cannot allocate space for tape buffer\n");
192                 done(1);
193         }
194         tapebuf += TP_BSIZE;
195         tapebufsize = size;
196 }
197
198 /*
199  * Verify that the tape drive can be accessed and
200  * that it actually is a dump tape.
201  */
202 void
203 setup(void)
204 {
205         int i, j, *ip;
206         struct stat stbuf;
207
208         vprintf(stdout, "Verify tape and initialize maps\n");
209         if (pipecmdin) {
210                 if (setenv("RESTORE_VOLUME", "1", 1) == -1) {
211                         fprintf(stderr, "Cannot set $RESTORE_VOLUME: %s\n",
212                             strerror(errno));
213                         done(1);
214                 }
215                 popenfp = popen(magtape, "r");
216                 mt = popenfp ? fileno(popenfp) : -1;
217         } else
218 #ifdef RRESTORE
219         if (host)
220                 mt = rmtopen(magtape, 0);
221         else
222 #endif
223         if (pipein)
224                 mt = 0;
225         else
226                 mt = open(magtape, O_RDONLY, 0);
227         if (mt < 0) {
228                 fprintf(stderr, "%s: %s\n", magtape, strerror(errno));
229                 done(1);
230         }
231         volno = 1;
232         setdumpnum();
233         FLUSHTAPEBUF();
234         if (!pipein && !pipecmdin && !bflag)
235                 findtapeblksize();
236         if (gethead(&spcl) == FAIL) {
237                 fprintf(stderr, "Tape is not a dump tape\n");
238                 done(1);
239         }
240         if (pipein) {
241                 endoftapemark.s_spcl.c_magic = FS_UFS2_MAGIC;
242                 endoftapemark.s_spcl.c_type = TS_END;
243                 ip = (int *)&endoftapemark;
244                 j = sizeof(union u_spcl) / sizeof(int);
245                 i = 0;
246                 do
247                         i += *ip++;
248                 while (--j);
249                 endoftapemark.s_spcl.c_checksum = CHECKSUM - i;
250         }
251         if (vflag || command == 't')
252                 printdumpinfo();
253         dumptime = _time64_to_time(spcl.c_ddate);
254         dumpdate = _time64_to_time(spcl.c_date);
255         if (stat(".", &stbuf) < 0) {
256                 fprintf(stderr, "cannot stat .: %s\n", strerror(errno));
257                 done(1);
258         }
259         if (stbuf.st_blksize > 0 && stbuf.st_blksize < TP_BSIZE )
260                 fssize = TP_BSIZE;
261         if (stbuf.st_blksize >= TP_BSIZE && stbuf.st_blksize <= MAXBSIZE)
262                 fssize = stbuf.st_blksize;
263         if (((fssize - 1) & fssize) != 0) {
264                 fprintf(stderr, "bad block size %ld\n", fssize);
265                 done(1);
266         }
267         if (spcl.c_volume != 1) {
268                 fprintf(stderr, "Tape is not volume 1 of the dump\n");
269                 done(1);
270         }
271         if (gethead(&spcl) == FAIL) {
272                 dprintf(stdout, "header read failed at %ld blocks\n", blksread);
273                 panic("no header after volume mark!\n");
274         }
275         findinode(&spcl);
276         if (spcl.c_type != TS_CLRI) {
277                 fprintf(stderr, "Cannot find file removal list\n");
278                 done(1);
279         }
280         maxino = (spcl.c_count * TP_BSIZE * NBBY) + 1;
281         dprintf(stdout, "maxino = %d\n", maxino);
282         map = calloc((unsigned)1, (unsigned)howmany(maxino, NBBY));
283         if (map == NULL)
284                 panic("no memory for active inode map\n");
285         usedinomap = map;
286         curfile.action = USING;
287         getfile(xtrmap, xtrmapskip, xtrmapskip);
288         if (spcl.c_type != TS_BITS) {
289                 fprintf(stderr, "Cannot find file dump list\n");
290                 done(1);
291         }
292         map = calloc((unsigned)1, (unsigned)howmany(maxino, NBBY));
293         if (map == (char *)NULL)
294                 panic("no memory for file dump list\n");
295         dumpmap = map;
296         curfile.action = USING;
297         getfile(xtrmap, xtrmapskip, xtrmapskip);
298         /*
299          * If there may be whiteout entries on the tape, pretend that the
300          * whiteout inode exists, so that the whiteout entries can be
301          * extracted.
302          */
303         SETINO(WINO, dumpmap);
304         /* 'r' restores don't call getvol() for tape 1, so mark it as read. */
305         if (command == 'r')
306                 tapesread = 1;
307 }
308
309 /*
310  * Prompt user to load a new dump volume.
311  * "Nextvol" is the next suggested volume to use.
312  * This suggested volume is enforced when doing full
313  * or incremental restores, but can be overridden by
314  * the user when only extracting a subset of the files.
315  */
316 void
317 getvol(long nextvol)
318 {
319         int64_t prevtapea;
320         long i, newvol, savecnt;
321         union u_spcl tmpspcl;
322 #       define tmpbuf tmpspcl.s_spcl
323         char buf[TP_BSIZE];
324
325         if (nextvol == 1) {
326                 tapesread = 0;
327                 gettingfile = 0;
328         }
329         prevtapea = tapeaddr;
330         savecnt = blksread;
331         if (pipein) {
332                 if (nextvol != 1) {
333                         panic("Changing volumes on pipe input?\n");
334                         /* Avoid looping if we couldn't ask the user. */
335                         if (yflag || ferror(terminal) || feof(terminal))
336                                 done(1);
337                 }
338                 if (volno == 1)
339                         return;
340                 goto gethdr;
341         }
342 again:
343         if (pipein)
344                 done(1); /* pipes do not get a second chance */
345         if (command == 'R' || command == 'r' || curfile.action != SKIP)
346                 newvol = nextvol;
347         else
348                 newvol = 0;
349         while (newvol <= 0) {
350                 if (tapesread == 0) {
351                         fprintf(stderr, "%s%s%s%s%s%s%s",
352                             "You have not read any tapes yet.\n",
353                             "If you are extracting just a few files,",
354                             " start with the last volume\n",
355                             "and work towards the first; restore",
356                             " can quickly skip tapes that\n",
357                             "have no further files to extract.",
358                             " Otherwise, begin with volume 1.\n");
359                 } else {
360                         fprintf(stderr, "You have read volumes");
361                         strcpy(buf, ": ");
362                         for (i = 0; i < 32; i++)
363                                 if (tapesread & (1 << i)) {
364                                         fprintf(stderr, "%s%ld", buf, i + 1);
365                                         strcpy(buf, ", ");
366                                 }
367                         fprintf(stderr, "\n");
368                 }
369                 do      {
370                         fprintf(stderr, "Specify next volume #: ");
371                         (void) fflush(stderr);
372                         if (fgets(buf, BUFSIZ, terminal) == NULL)
373                                 done(1);
374                 } while (buf[0] == '\n');
375                 newvol = atoi(buf);
376                 if (newvol <= 0) {
377                         fprintf(stderr,
378                             "Volume numbers are positive numerics\n");
379                 }
380         }
381         if (newvol == volno) {
382                 tapesread |= 1 << (volno - 1);
383                 return;
384         }
385         closemt();
386         fprintf(stderr, "Mount tape volume %ld\n", newvol);
387         fprintf(stderr, "Enter ``none'' if there are no more tapes\n");
388         fprintf(stderr, "otherwise enter tape name (default: %s) ", magtape);
389         (void) fflush(stderr);
390         if (fgets(buf, BUFSIZ, terminal) == NULL)
391                 done(1);
392         if (!strcmp(buf, "none\n")) {
393                 terminateinput();
394                 return;
395         }
396         if (buf[0] != '\n') {
397                 (void) strcpy(magtape, buf);
398                 magtape[strlen(magtape) - 1] = '\0';
399         }
400         if (pipecmdin) {
401                 char volno[sizeof("2147483647")];
402
403                 (void)sprintf(volno, "%d", newvol);
404                 if (setenv("RESTORE_VOLUME", volno, 1) == -1) {
405                         fprintf(stderr, "Cannot set $RESTORE_VOLUME: %s\n",
406                             strerror(errno));
407                         done(1);
408                 }
409                 popenfp = popen(magtape, "r");
410                 mt = popenfp ? fileno(popenfp) : -1;
411         } else
412 #ifdef RRESTORE
413         if (host)
414                 mt = rmtopen(magtape, 0);
415         else
416 #endif
417                 mt = open(magtape, O_RDONLY, 0);
418
419         if (mt == -1) {
420                 fprintf(stderr, "Cannot open %s\n", magtape);
421                 volno = -1;
422                 goto again;
423         }
424 gethdr:
425         volno = newvol;
426         setdumpnum();
427         FLUSHTAPEBUF();
428         if (gethead(&tmpbuf) == FAIL) {
429                 dprintf(stdout, "header read failed at %ld blocks\n", blksread);
430                 fprintf(stderr, "tape is not dump tape\n");
431                 volno = 0;
432                 goto again;
433         }
434         if (tmpbuf.c_volume != volno) {
435                 fprintf(stderr, "Wrong volume (%ld)\n", tmpbuf.c_volume);
436                 volno = 0;
437                 goto again;
438         }
439         if (_time64_to_time(tmpbuf.c_date) != dumpdate ||
440             _time64_to_time(tmpbuf.c_ddate) != dumptime) {
441                 time_t t = _time64_to_time(tmpbuf.c_date);
442                 fprintf(stderr, "Wrong dump date\n\tgot: %s", ctime(&t));
443                 fprintf(stderr, "\twanted: %s", ctime(&dumpdate));
444                 volno = 0;
445                 goto again;
446         }
447         tapesread |= 1 << (volno - 1);
448         blksread = savecnt;
449         /*
450          * If continuing from the previous volume, skip over any
451          * blocks read already at the end of the previous volume.
452          *
453          * If coming to this volume at random, skip to the beginning
454          * of the next record.
455          */
456         dprintf(stdout, "last rec %qd, tape starts with %qd\n", prevtapea,
457             tmpbuf.c_tapea);
458         if (tmpbuf.c_type == TS_TAPE) {
459                 if (curfile.action != USING) {
460                         /*
461                          * XXX Dump incorrectly sets c_count to 1 in the
462                          * volume header of the first tape, so ignore
463                          * c_count when volno == 1.
464                          */
465                         if (volno != 1)
466                                 for (i = tmpbuf.c_count; i > 0; i--)
467                                         readtape(buf);
468                 } else if (tmpbuf.c_tapea <= prevtapea) {
469                         /*
470                          * Normally the value of c_tapea in the volume
471                          * header is the record number of the header itself.
472                          * However in the volume header following an EOT-
473                          * terminated tape, it is the record number of the
474                          * first continuation data block (dump bug?).
475                          *
476                          * The next record we want is `prevtapea + 1'.
477                          */
478                         i = prevtapea + 1 - tmpbuf.c_tapea;
479                         dprintf(stderr, "Skipping %ld duplicate record%s.\n",
480                                 i, i > 1 ? "s" : "");
481                         while (--i >= 0)
482                                 readtape(buf);
483                 }
484         }
485         if (curfile.action == USING) {
486                 if (volno == 1)
487                         panic("active file into volume 1\n");
488                 return;
489         }
490         (void) gethead(&spcl);
491         findinode(&spcl);
492         if (gettingfile) {
493                 gettingfile = 0;
494                 longjmp(restart, 1);
495         }
496 }
497
498 /*
499  * Handle unexpected EOF.
500  */
501 static void
502 terminateinput(void)
503 {
504
505         if (gettingfile && curfile.action == USING) {
506                 printf("Warning: %s %s\n",
507                     "End-of-input encountered while extracting", curfile.name);
508         }
509         curfile.name = "<name unknown>";
510         curfile.action = UNKNOWN;
511         curfile.mode = 0;
512         curfile.ino = maxino;
513         if (gettingfile) {
514                 gettingfile = 0;
515                 longjmp(restart, 1);
516         }
517 }
518
519 /*
520  * handle multiple dumps per tape by skipping forward to the
521  * appropriate one.
522  */
523 static void
524 setdumpnum(void)
525 {
526         struct mtop tcom;
527
528         if (dumpnum == 1 || volno != 1)
529                 return;
530         if (pipein) {
531                 fprintf(stderr, "Cannot have multiple dumps on pipe input\n");
532                 done(1);
533         }
534         tcom.mt_op = MTFSF;
535         tcom.mt_count = dumpnum - 1;
536 #ifdef RRESTORE
537         if (host)
538                 rmtioctl(MTFSF, dumpnum - 1);
539         else
540 #endif
541                 if (!pipecmdin && ioctl(mt, MTIOCTOP, (char *)&tcom) < 0)
542                         fprintf(stderr, "ioctl MTFSF: %s\n", strerror(errno));
543 }
544
545 void
546 printdumpinfo(void)
547 {
548         time_t t;
549         t = _time64_to_time(spcl.c_date);
550         fprintf(stdout, "Dump   date: %s", ctime(&t));
551         t = _time64_to_time(spcl.c_ddate);
552         fprintf(stdout, "Dumped from: %s",
553             (spcl.c_ddate == 0) ? "the epoch\n" : ctime(&t));
554         if (spcl.c_host[0] == '\0')
555                 return;
556         fprintf(stderr, "Level %ld dump of %s on %s:%s\n",
557                 spcl.c_level, spcl.c_filesys, spcl.c_host, spcl.c_dev);
558         fprintf(stderr, "Label: %s\n", spcl.c_label);
559 }
560
561 int
562 extractfile(char *name)
563 {
564         int flags;
565         uid_t uid;
566         gid_t gid;
567         mode_t mode;
568         int extsize;
569         struct timeval mtimep[2], ctimep[2];
570         struct entry *ep;
571         char *buf;
572
573         curfile.name = name;
574         curfile.action = USING;
575         mtimep[0].tv_sec = curfile.atime_sec;
576         mtimep[0].tv_usec = curfile.atime_nsec / 1000;
577         mtimep[1].tv_sec = curfile.mtime_sec;
578         mtimep[1].tv_usec = curfile.mtime_nsec / 1000;
579         ctimep[0].tv_sec = curfile.atime_sec;
580         ctimep[0].tv_usec = curfile.atime_nsec / 1000;
581         ctimep[1].tv_sec = curfile.birthtime_sec;
582         ctimep[1].tv_usec = curfile.birthtime_nsec / 1000;
583         extsize = curfile.extsize;
584         uid = getuid();
585         if (uid == 0)
586                 uid = curfile.uid;
587         gid = curfile.gid;
588         mode = curfile.mode;
589         flags = curfile.file_flags;
590         switch (mode & IFMT) {
591
592         default:
593                 fprintf(stderr, "%s: unknown file mode 0%o\n", name, mode);
594                 skipfile();
595                 return (FAIL);
596
597         case IFSOCK:
598                 vprintf(stdout, "skipped socket %s\n", name);
599                 skipfile();
600                 return (GOOD);
601
602         case IFDIR:
603                 if (mflag) {
604                         ep = lookupname(name);
605                         if (ep == NULL || ep->e_flags & EXTRACT)
606                                 panic("unextracted directory %s\n", name);
607                         skipfile();
608                         return (GOOD);
609                 }
610                 vprintf(stdout, "extract file %s\n", name);
611                 return (genliteraldir(name, curfile.ino));
612
613         case IFLNK:
614                 lnkbuf[0] = '\0';
615                 pathlen = 0;
616                 buf = setupextattr(extsize);
617                 getfile(xtrlnkfile, xtrattr, xtrlnkskip);
618                 if (pathlen == 0) {
619                         vprintf(stdout,
620                             "%s: zero length symbolic link (ignored)\n", name);
621                         return (GOOD);
622                 }
623                 if (linkit(lnkbuf, name, SYMLINK) == GOOD) {
624                         if (extsize > 0)
625                                 set_extattr_link(name, buf, extsize);
626                         (void) lchown(name, uid, gid);
627                         (void) lchmod(name, mode);
628                         (void) lutimes(name, ctimep);
629                         (void) lutimes(name, mtimep);
630                         (void) lchflags(name, flags);
631                         return (GOOD);
632                 }
633                 return (FAIL);
634
635         case IFIFO:
636                 vprintf(stdout, "extract fifo %s\n", name);
637                 if (Nflag) {
638                         skipfile();
639                         return (GOOD);
640                 }
641                 if (uflag)
642                         (void) unlink(name);
643                 if (mkfifo(name, 0600) < 0) {
644                         fprintf(stderr, "%s: cannot create fifo: %s\n",
645                             name, strerror(errno));
646                         skipfile();
647                         return (FAIL);
648                 }
649                 if (extsize == 0) {
650                         skipfile();
651                 } else {
652                         buf = setupextattr(extsize);
653                         getfile(xtrnull, xtrattr, xtrnull);
654                         set_extattr_file(name, buf, extsize);
655                 }
656                 (void) chown(name, uid, gid);
657                 (void) chmod(name, mode);
658                 (void) utimes(name, ctimep);
659                 (void) utimes(name, mtimep);
660                 (void) chflags(name, flags);
661                 return (GOOD);
662
663         case IFCHR:
664         case IFBLK:
665                 vprintf(stdout, "extract special file %s\n", name);
666                 if (Nflag) {
667                         skipfile();
668                         return (GOOD);
669                 }
670                 if (uflag)
671                         (void) unlink(name);
672                 if (mknod(name, (mode & (IFCHR | IFBLK)) | 0600,
673                     (int)curfile.rdev) < 0) {
674                         fprintf(stderr, "%s: cannot create special file: %s\n",
675                             name, strerror(errno));
676                         skipfile();
677                         return (FAIL);
678                 }
679                 if (extsize == 0) {
680                         skipfile();
681                 } else {
682                         buf = setupextattr(extsize);
683                         getfile(xtrnull, xtrattr, xtrnull);
684                         set_extattr_file(name, buf, extsize);
685                 }
686                 (void) chown(name, uid, gid);
687                 (void) chmod(name, mode);
688                 (void) utimes(name, ctimep);
689                 (void) utimes(name, mtimep);
690                 (void) chflags(name, flags);
691                 return (GOOD);
692
693         case IFREG:
694                 vprintf(stdout, "extract file %s\n", name);
695                 if (Nflag) {
696                         skipfile();
697                         return (GOOD);
698                 }
699                 if (uflag)
700                         (void) unlink(name);
701                 if ((ofile = open(name, O_WRONLY | O_CREAT | O_TRUNC,
702                     0600)) < 0) {
703                         fprintf(stderr, "%s: cannot create file: %s\n",
704                             name, strerror(errno));
705                         skipfile();
706                         return (FAIL);
707                 }
708                 buf = setupextattr(extsize);
709                 getfile(xtrfile, xtrattr, xtrskip);
710                 if (extsize > 0)
711                         set_extattr_fd(ofile, name, buf, extsize);
712                 (void) fchown(ofile, uid, gid);
713                 (void) fchmod(ofile, mode);
714                 (void) futimes(ofile, ctimep);
715                 (void) futimes(ofile, mtimep);
716                 (void) fchflags(ofile, flags);
717                 (void) close(ofile);
718                 return (GOOD);
719         }
720         /* NOTREACHED */
721 }
722
723 /*
724  * Set attributes for a file.
725  */
726 void
727 set_extattr_file(char *name, void *buf, int size)
728 {
729         struct extattr *eap, *eaend;
730
731         vprintf(stdout, "Set attributes for %s:", name);
732         eaend = buf + size;
733         for (eap = buf; eap < eaend; eap = EXTATTR_NEXT(eap)) {
734                 /*
735                  * Make sure this entry is complete.
736                  */
737                 if (EXTATTR_NEXT(eap) > eaend || eap->ea_length <= 0) {
738                         dprintf(stdout, "\n\t%scorrupted",
739                                 eap == buf ? "" : "remainder ");
740                         break;
741                 }
742                 if (eap->ea_namespace == EXTATTR_NAMESPACE_EMPTY)
743                         continue;
744                 vprintf(stdout, "\n\t%s, (%d bytes), %*s",
745                         namespace_names[eap->ea_namespace], eap->ea_length,
746                         eap->ea_namelength, eap->ea_name);
747                 /*
748                  * First we try the general attribute setting interface.
749                  * However, some attributes can only be set by root or
750                  * by using special interfaces (for example, ACLs).
751                  */
752                 if (extattr_set_file(name, eap->ea_namespace, eap->ea_name,
753                     EXTATTR_CONTENT(eap), EXTATTR_CONTENT_SIZE(eap)) != -1) {
754                         dprintf(stdout, " (set using extattr_set_file)");
755                         continue;
756                 }
757                 /*
758                  * If the general interface refuses to set the attribute,
759                  * then we try all the specialized interfaces that we
760                  * know about.
761                  */
762                 if (eap->ea_namespace == EXTATTR_NAMESPACE_SYSTEM &&
763                     !strcmp(eap->ea_name, POSIX1E_ACL_ACCESS_EXTATTR_NAME)) {
764                         if (acl_set_file(name, ACL_TYPE_ACCESS,
765                             EXTATTR_CONTENT(eap)) != -1) {
766                                 dprintf(stdout, " (set using acl_set_file)");
767                                 continue;
768                         }
769                 }
770                 if (eap->ea_namespace == EXTATTR_NAMESPACE_SYSTEM &&
771                     !strcmp(eap->ea_name, POSIX1E_ACL_DEFAULT_EXTATTR_NAME)) {
772                         if (acl_set_file(name, ACL_TYPE_DEFAULT,
773                             EXTATTR_CONTENT(eap)) != -1) {
774                                 dprintf(stdout, " (set using acl_set_file)");
775                                 continue;
776                         }
777                 }
778                 vprintf(stdout, " (unable to set)");
779         }
780         vprintf(stdout, "\n");
781 }
782
783 /*
784  * Set attributes for a symbolic link.
785  */
786 static void
787 set_extattr_link(char *name, void *buf, int size)
788 {
789         struct extattr *eap, *eaend;
790
791         vprintf(stdout, "Set attributes for %s:", name);
792         eaend = buf + size;
793         for (eap = buf; eap < eaend; eap = EXTATTR_NEXT(eap)) {
794                 /*
795                  * Make sure this entry is complete.
796                  */
797                 if (EXTATTR_NEXT(eap) > eaend || eap->ea_length <= 0) {
798                         dprintf(stdout, "\n\t%scorrupted",
799                                 eap == buf ? "" : "remainder ");
800                         break;
801                 }
802                 if (eap->ea_namespace == EXTATTR_NAMESPACE_EMPTY)
803                         continue;
804                 vprintf(stdout, "\n\t%s, (%d bytes), %*s",
805                         namespace_names[eap->ea_namespace], eap->ea_length,
806                         eap->ea_namelength, eap->ea_name);
807                 /*
808                  * First we try the general attribute setting interface.
809                  * However, some attributes can only be set by root or
810                  * by using special interfaces (for example, ACLs).
811                  */
812                 if (extattr_set_link(name, eap->ea_namespace, eap->ea_name,
813                     EXTATTR_CONTENT(eap), EXTATTR_CONTENT_SIZE(eap)) != -1) {
814                         dprintf(stdout, " (set using extattr_set_link)");
815                         continue;
816                 }
817                 /*
818                  * If the general interface refuses to set the attribute,
819                  * then we try all the specialized interfaces that we
820                  * know about.
821                  */
822                 if (eap->ea_namespace == EXTATTR_NAMESPACE_SYSTEM &&
823                     !strcmp(eap->ea_name, POSIX1E_ACL_ACCESS_EXTATTR_NAME)) {
824                         if (acl_set_link_np(name, ACL_TYPE_ACCESS,
825                             EXTATTR_CONTENT(eap)) != -1) {
826                                 dprintf(stdout, " (set using acl_set_link_np)");
827                                 continue;
828                         }
829                 }
830                 if (eap->ea_namespace == EXTATTR_NAMESPACE_SYSTEM &&
831                     !strcmp(eap->ea_name, POSIX1E_ACL_DEFAULT_EXTATTR_NAME)) {
832                         if (acl_set_link_np(name, ACL_TYPE_DEFAULT,
833                             EXTATTR_CONTENT(eap)) != -1) {
834                                 dprintf(stdout, " (set using acl_set_link_np)");
835                                 continue;
836                         }
837                 }
838                 vprintf(stdout, " (unable to set)");
839         }
840         vprintf(stdout, "\n");
841 }
842
843 /*
844  * Set attributes on a file descriptor.
845  */
846 static void
847 set_extattr_fd(int fd, char *name, void *buf, int size)
848 {
849         struct extattr *eap, *eaend;
850
851         vprintf(stdout, "Set attributes for %s:", name);
852         eaend = buf + size;
853         for (eap = buf; eap < eaend; eap = EXTATTR_NEXT(eap)) {
854                 /*
855                  * Make sure this entry is complete.
856                  */
857                 if (EXTATTR_NEXT(eap) > eaend || eap->ea_length <= 0) {
858                         dprintf(stdout, "\n\t%scorrupted",
859                                 eap == buf ? "" : "remainder ");
860                         break;
861                 }
862                 if (eap->ea_namespace == EXTATTR_NAMESPACE_EMPTY)
863                         continue;
864                 vprintf(stdout, "\n\t%s, (%d bytes), %*s",
865                         namespace_names[eap->ea_namespace], eap->ea_length,
866                         eap->ea_namelength, eap->ea_name);
867                 /*
868                  * First we try the general attribute setting interface.
869                  * However, some attributes can only be set by root or
870                  * by using special interfaces (for example, ACLs).
871                  */
872                 if (extattr_set_fd(fd, eap->ea_namespace, eap->ea_name,
873                     EXTATTR_CONTENT(eap), EXTATTR_CONTENT_SIZE(eap)) != -1) {
874                         dprintf(stdout, " (set using extattr_set_fd)");
875                         continue;
876                 }
877                 /*
878                  * If the general interface refuses to set the attribute,
879                  * then we try all the specialized interfaces that we
880                  * know about.
881                  */
882                 if (eap->ea_namespace == EXTATTR_NAMESPACE_SYSTEM &&
883                     !strcmp(eap->ea_name, POSIX1E_ACL_ACCESS_EXTATTR_NAME)) {
884                         if (acl_set_fd(fd, EXTATTR_CONTENT(eap)) != -1) {
885                                 dprintf(stdout, " (set using acl_set_fd)");
886                                 continue;
887                         }
888                 }
889                 if (eap->ea_namespace == EXTATTR_NAMESPACE_SYSTEM &&
890                     !strcmp(eap->ea_name, POSIX1E_ACL_DEFAULT_EXTATTR_NAME)) {
891                         if (acl_set_file(name, ACL_TYPE_DEFAULT,
892                             EXTATTR_CONTENT(eap)) != -1) {
893                                 dprintf(stdout, " (set using acl_set_file)");
894                                 continue;
895                         }
896                 }
897                 vprintf(stdout, " (unable to set)");
898         }
899         vprintf(stdout, "\n");
900 }
901
902 /*
903  * skip over bit maps on the tape
904  */
905 void
906 skipmaps(void)
907 {
908
909         while (spcl.c_type == TS_BITS || spcl.c_type == TS_CLRI)
910                 skipfile();
911 }
912
913 /*
914  * skip over a file on the tape
915  */
916 void
917 skipfile(void)
918 {
919
920         curfile.action = SKIP;
921         getfile(xtrnull, xtrnull, xtrnull);
922 }
923
924 /*
925  * Extract a file from the tape.
926  * When an allocated block is found it is passed to the fill function;
927  * when an unallocated block (hole) is found, a zeroed buffer is passed
928  * to the skip function.
929  */
930 void
931 getfile(void (*datafill)(char *, long), void (*attrfill)(char *, long),
932         void (*skip)(char *, long))
933 {
934         int i;
935         off_t size;
936         int curblk, attrsize;
937         void (*fillit)(char *, long);
938         static char clearedbuf[MAXBSIZE];
939         char buf[MAXBSIZE / TP_BSIZE][TP_BSIZE];
940         char junk[TP_BSIZE];
941
942         curblk = 0;
943         size = spcl.c_size;
944         attrsize = spcl.c_extsize;
945         if (spcl.c_type == TS_END)
946                 panic("ran off end of tape\n");
947         if (spcl.c_magic != FS_UFS2_MAGIC)
948                 panic("not at beginning of a file\n");
949         if (!gettingfile && setjmp(restart) != 0)
950                 return;
951         gettingfile++;
952         fillit = datafill;
953         if (size == 0 && attrsize > 0) {
954                 fillit = attrfill;
955                 size = attrsize;
956                 attrsize = 0;
957         }
958 loop:
959         for (i = 0; i < spcl.c_count; i++) {
960                 if (!readmapflag && i > TP_NINDIR) {
961                         if (Dflag) {
962                                 fprintf(stderr, "spcl.c_count = %jd\n",
963                                     (intmax_t)spcl.c_count);
964                                 break;
965                         } else
966                                 panic("spcl.c_count = %jd\n",
967                                     (intmax_t)spcl.c_count);
968                 }
969                 if (readmapflag || spcl.c_addr[i]) {
970                         readtape(&buf[curblk++][0]);
971                         if (curblk == fssize / TP_BSIZE) {
972                                 (*fillit)((char *)buf, (long)(size > TP_BSIZE ?
973                                      fssize : (curblk - 1) * TP_BSIZE + size));
974                                 curblk = 0;
975                         }
976                 } else {
977                         if (curblk > 0) {
978                                 (*fillit)((char *)buf, (long)(size > TP_BSIZE ?
979                                      curblk * TP_BSIZE :
980                                      (curblk - 1) * TP_BSIZE + size));
981                                 curblk = 0;
982                         }
983                         (*skip)(clearedbuf, (long)(size > TP_BSIZE ?
984                                 TP_BSIZE : size));
985                 }
986                 if ((size -= TP_BSIZE) <= 0) {
987                         if (size > -TP_BSIZE && curblk > 0) {
988                                 (*fillit)((char *)buf,
989                                         (long)((curblk * TP_BSIZE) + size));
990                                 curblk = 0;
991                         }
992                         if (attrsize > 0) {
993                                 fillit = attrfill;
994                                 size = attrsize;
995                                 attrsize = 0;
996                                 continue;
997                         }
998                         if (spcl.c_count - i > 1)
999                                 dprintf(stdout, "skipping %d junk block(s)\n",
1000                                         spcl.c_count - i - 1);
1001                         for (i++; i < spcl.c_count; i++) {
1002                                 if (!readmapflag && i > TP_NINDIR) {
1003                                         if (Dflag) {
1004                                                 fprintf(stderr,
1005                                                     "spcl.c_count = %jd\n",
1006                                                     (intmax_t)spcl.c_count);
1007                                                 break;
1008                                         } else 
1009                                                 panic("spcl.c_count = %jd\n",
1010                                                     (intmax_t)spcl.c_count);
1011                                 }
1012                                 if (readmapflag || spcl.c_addr[i])
1013                                         readtape(junk);
1014                         }
1015                         break;
1016                 }
1017         }
1018         if (gethead(&spcl) == GOOD && size > 0) {
1019                 if (spcl.c_type == TS_ADDR)
1020                         goto loop;
1021                 dprintf(stdout,
1022                         "Missing address (header) block for %s at %ld blocks\n",
1023                         curfile.name, blksread);
1024         }
1025         if (curblk > 0)
1026                 panic("getfile: lost data\n");
1027         findinode(&spcl);
1028         gettingfile = 0;
1029 }
1030
1031 /*
1032  * These variables are shared between the next two functions.
1033  */
1034 static int extbufsize = 0;
1035 static char *extbuf;
1036 static int extloc;
1037
1038 /*
1039  * Allocate a buffer into which to extract extended attributes.
1040  */
1041 static char *
1042 setupextattr(int extsize)
1043 {
1044
1045         extloc = 0;
1046         if (extsize <= extbufsize)
1047                 return (extbuf);
1048         if (extbufsize > 0)
1049                 free(extbuf);
1050         if ((extbuf = malloc(extsize)) != NULL) {
1051                 extbufsize = extsize;
1052                 return (extbuf);
1053         }
1054         extbufsize = 0;
1055         extbuf = NULL;
1056         fprintf(stderr, "Cannot extract %d bytes %s for inode %d, name %s\n",
1057             extsize, "of extended attributes", curfile.ino, curfile.name);
1058         return (NULL);
1059 }
1060
1061 /*
1062  * Extract the next block of extended attributes.
1063  */
1064 static void
1065 xtrattr(char *buf, long size)
1066 {
1067
1068         if (extloc + size > extbufsize)
1069                 panic("overrun attribute buffer\n");
1070         memmove(&extbuf[extloc], buf, size);
1071         extloc += size;
1072 }
1073
1074 /*
1075  * Write out the next block of a file.
1076  */
1077 static void
1078 xtrfile(char *buf, long size)
1079 {
1080
1081         if (Nflag)
1082                 return;
1083         if (write(ofile, buf, (int) size) == -1) {
1084                 fprintf(stderr,
1085                     "write error extracting inode %d, name %s\nwrite: %s\n",
1086                         curfile.ino, curfile.name, strerror(errno));
1087         }
1088 }
1089
1090 /*
1091  * Skip over a hole in a file.
1092  */
1093 /* ARGSUSED */
1094 static void
1095 xtrskip(char *buf, long size)
1096 {
1097
1098         if (lseek(ofile, size, SEEK_CUR) == -1) {
1099                 fprintf(stderr,
1100                     "seek error extracting inode %d, name %s\nlseek: %s\n",
1101                         curfile.ino, curfile.name, strerror(errno));
1102                 done(1);
1103         }
1104 }
1105
1106 /*
1107  * Collect the next block of a symbolic link.
1108  */
1109 static void
1110 xtrlnkfile(char *buf, long size)
1111 {
1112
1113         pathlen += size;
1114         if (pathlen > MAXPATHLEN) {
1115                 fprintf(stderr, "symbolic link name: %s->%s%s; too long %d\n",
1116                     curfile.name, lnkbuf, buf, pathlen);
1117                 done(1);
1118         }
1119         (void) strcat(lnkbuf, buf);
1120 }
1121
1122 /*
1123  * Skip over a hole in a symbolic link (should never happen).
1124  */
1125 /* ARGSUSED */
1126 static void
1127 xtrlnkskip(char *buf, long size)
1128 {
1129
1130         fprintf(stderr, "unallocated block in symbolic link %s\n",
1131                 curfile.name);
1132         done(1);
1133 }
1134
1135 /*
1136  * Collect the next block of a bit map.
1137  */
1138 static void
1139 xtrmap(char *buf, long size)
1140 {
1141
1142         memmove(map, buf, size);
1143         map += size;
1144 }
1145
1146 /*
1147  * Skip over a hole in a bit map (should never happen).
1148  */
1149 /* ARGSUSED */
1150 static void
1151 xtrmapskip(char *buf, long size)
1152 {
1153
1154         panic("hole in map\n");
1155         map += size;
1156 }
1157
1158 /*
1159  * Noop, when an extraction function is not needed.
1160  */
1161 /* ARGSUSED */
1162 void
1163 xtrnull(char *buf, long size)
1164 {
1165
1166         return;
1167 }
1168
1169 /*
1170  * Read TP_BSIZE blocks from the input.
1171  * Handle read errors, and end of media.
1172  */
1173 static void
1174 readtape(char *buf)
1175 {
1176         long rd, newvol, i, oldnumtrec;
1177         int cnt, seek_failed;
1178
1179         if (blkcnt + (byteslide > 0) < numtrec) {
1180                 memmove(buf, &tapebuf[(blkcnt++ * TP_BSIZE) + byteslide], (long)TP_BSIZE);
1181                 blksread++;
1182                 tapeaddr++;
1183                 return;
1184         }
1185         if (numtrec > 0)
1186                 memmove(&tapebuf[-TP_BSIZE],
1187                     &tapebuf[(numtrec-1) * TP_BSIZE], (long)TP_BSIZE);
1188         oldnumtrec = numtrec;
1189         for (i = 0; i < ntrec; i++)
1190                 ((struct s_spcl *)&tapebuf[i * TP_BSIZE])->c_magic = 0;
1191         if (numtrec == 0)
1192                 numtrec = ntrec;
1193         cnt = ntrec * TP_BSIZE;
1194         rd = 0;
1195 getmore:
1196 #ifdef RRESTORE
1197         if (host)
1198                 i = rmtread(&tapebuf[rd], cnt);
1199         else
1200 #endif
1201                 i = read(mt, &tapebuf[rd], cnt);
1202         /*
1203          * Check for mid-tape short read error.
1204          * If found, skip rest of buffer and start with the next.
1205          */
1206         if (!pipein && !pipecmdin && numtrec < ntrec && i > 0) {
1207                 dprintf(stdout, "mid-media short read error.\n");
1208                 numtrec = ntrec;
1209         }
1210         /*
1211          * Handle partial block read.
1212          */
1213         if ((pipein || pipecmdin) && i == 0 && rd > 0)
1214                 i = rd;
1215         else if (i > 0 && i != ntrec * TP_BSIZE) {
1216                 if (pipein || pipecmdin) {
1217                         rd += i;
1218                         cnt -= i;
1219                         if (cnt > 0)
1220                                 goto getmore;
1221                         i = rd;
1222                 } else {
1223                         /*
1224                          * Short read. Process the blocks read.
1225                          */
1226                         if (i % TP_BSIZE != 0)
1227                                 vprintf(stdout,
1228                                     "partial block read: %ld should be %ld\n",
1229                                     i, ntrec * TP_BSIZE);
1230                         numtrec = i / TP_BSIZE;
1231                 }
1232         }
1233         /*
1234          * Handle read error.
1235          */
1236         if (i < 0) {
1237                 fprintf(stderr, "Tape read error while ");
1238                 switch (curfile.action) {
1239                 default:
1240                         fprintf(stderr, "trying to set up tape\n");
1241                         break;
1242                 case UNKNOWN:
1243                         fprintf(stderr, "trying to resynchronize\n");
1244                         break;
1245                 case USING:
1246                         fprintf(stderr, "restoring %s\n", curfile.name);
1247                         break;
1248                 case SKIP:
1249                         fprintf(stderr, "skipping over inode %d\n",
1250                                 curfile.ino);
1251                         break;
1252                 }
1253                 if (!yflag && !reply("continue"))
1254                         done(1);
1255                 i = ntrec * TP_BSIZE;
1256                 memset(tapebuf, 0, i);
1257 #ifdef RRESTORE
1258                 if (host)
1259                         seek_failed = (rmtseek(i, 1) < 0);
1260                 else
1261 #endif
1262                         seek_failed = (lseek(mt, i, SEEK_CUR) == (off_t)-1);
1263
1264                 if (seek_failed) {
1265                         fprintf(stderr,
1266                             "continuation failed: %s\n", strerror(errno));
1267                         done(1);
1268                 }
1269         }
1270         /*
1271          * Handle end of tape.
1272          */
1273         if (i == 0) {
1274                 vprintf(stdout, "End-of-tape encountered\n");
1275                 if (!pipein) {
1276                         newvol = volno + 1;
1277                         volno = 0;
1278                         numtrec = 0;
1279                         getvol(newvol);
1280                         readtape(buf);
1281                         return;
1282                 }
1283                 if (rd % TP_BSIZE != 0)
1284                         panic("partial block read: %d should be %d\n",
1285                                 rd, ntrec * TP_BSIZE);
1286                 terminateinput();
1287                 memmove(&tapebuf[rd], &endoftapemark, (long)TP_BSIZE);
1288         }
1289         if (oldnumtrec == 0)
1290                 blkcnt = 0;
1291         else
1292                 blkcnt -= oldnumtrec;
1293         memmove(buf,
1294             &tapebuf[(blkcnt++ * TP_BSIZE) + byteslide], (long)TP_BSIZE);
1295         blksread++;
1296         tapeaddr++;
1297 }
1298
1299 static void
1300 findtapeblksize(void)
1301 {
1302         long i;
1303
1304         for (i = 0; i < ntrec; i++)
1305                 ((struct s_spcl *)&tapebuf[i * TP_BSIZE])->c_magic = 0;
1306         blkcnt = 0;
1307 #ifdef RRESTORE
1308         if (host)
1309                 i = rmtread(tapebuf, ntrec * TP_BSIZE);
1310         else
1311 #endif
1312                 i = read(mt, tapebuf, ntrec * TP_BSIZE);
1313
1314         if (i <= 0) {
1315                 fprintf(stderr, "tape read error: %s\n", strerror(errno));
1316                 done(1);
1317         }
1318         if (i % TP_BSIZE != 0) {
1319                 fprintf(stderr, "Tape block size (%ld) %s (%d)\n",
1320                         i, "is not a multiple of dump block size", TP_BSIZE);
1321                 done(1);
1322         }
1323         ntrec = i / TP_BSIZE;
1324         numtrec = ntrec;
1325         vprintf(stdout, "Tape block size is %ld\n", ntrec);
1326 }
1327
1328 void
1329 closemt(void)
1330 {
1331
1332         if (mt < 0)
1333                 return;
1334         if (pipecmdin) {
1335                 pclose(popenfp);
1336                 popenfp = NULL;
1337         } else
1338 #ifdef RRESTORE
1339         if (host)
1340                 rmtclose();
1341         else
1342 #endif
1343                 (void) close(mt);
1344 }
1345
1346 /*
1347  * Read the next block from the tape.
1348  * If it is not any valid header, return an error.
1349  */
1350 static int
1351 gethead(struct s_spcl *buf)
1352 {
1353         long i;
1354
1355         readtape((char *)buf);
1356         if (buf->c_magic != FS_UFS2_MAGIC && buf->c_magic != NFS_MAGIC) {
1357                 if (buf->c_magic == OFS_MAGIC) {
1358                         fprintf(stderr,
1359                             "Format of dump tape is too old. Must use\n");
1360                         fprintf(stderr,
1361                             "a version of restore from before 2002.\n");
1362                         return (FAIL);
1363                 }
1364                 if (swabl(buf->c_magic) != FS_UFS2_MAGIC &&
1365                     buf->c_magic != NFS_MAGIC) {
1366                         if (buf->c_magic == OFS_MAGIC) {
1367                                 fprintf(stderr,
1368                                   "Format of dump tape is too old. Must use\n");
1369                                 fprintf(stderr,
1370                                   "a version of restore from before 2002.\n");
1371                         }
1372                         return (FAIL);
1373                 }
1374                 if (!Bcvt) {
1375                         vprintf(stdout, "Note: Doing Byte swapping\n");
1376                         Bcvt = 1;
1377                 }
1378         }
1379         if (checksum((int *)buf) == FAIL)
1380                 return (FAIL);
1381         if (Bcvt) {
1382                 swabst((u_char *)"8l4s1q8l2q17l", (u_char *)buf);
1383                 swabst((u_char *)"l",(u_char *) &buf->c_level);
1384                 swabst((u_char *)"2l4q",(u_char *) &buf->c_flags);
1385         }
1386         readmapflag = 0;
1387
1388         switch (buf->c_type) {
1389
1390         case TS_CLRI:
1391         case TS_BITS:
1392                 /*
1393                  * Have to patch up missing information in bit map headers
1394                  */
1395                 buf->c_size = buf->c_count * TP_BSIZE;
1396                 if (buf->c_count > TP_NINDIR)
1397                         readmapflag = 1;
1398                 else 
1399                         for (i = 0; i < buf->c_count; i++)
1400                                 buf->c_addr[i]++;
1401                 /* FALL THROUGH */
1402
1403         case TS_TAPE:
1404                 if (buf->c_magic == NFS_MAGIC &&
1405                     (buf->c_flags & NFS_DR_NEWINODEFMT) == 0)
1406                         oldinofmt = 1;
1407                 /* FALL THROUGH */
1408
1409         case TS_END:
1410                 buf->c_inumber = 0;
1411                 /* FALL THROUGH */
1412
1413         case TS_ADDR:
1414         case TS_INODE:
1415                 /*
1416                  * For old dump tapes, have to copy up old fields to
1417                  * new locations.
1418                  */
1419                 if (buf->c_magic == NFS_MAGIC) {
1420                         buf->c_tapea = buf->c_old_tapea;
1421                         buf->c_firstrec = buf->c_old_firstrec;
1422                         buf->c_date = _time32_to_time(buf->c_old_date);
1423                         buf->c_ddate = _time32_to_time(buf->c_old_ddate);
1424                         buf->c_atime = _time32_to_time(buf->c_old_atime);
1425                         buf->c_mtime = _time32_to_time(buf->c_old_mtime);
1426                         buf->c_birthtime = 0;
1427                         buf->c_birthtimensec = 0;
1428                         buf->c_extsize = 0;
1429                 }
1430                 break;
1431
1432         default:
1433                 panic("gethead: unknown inode type %d\n", buf->c_type);
1434                 break;
1435         }
1436         if (dumpdate != 0 && _time64_to_time(buf->c_date) != dumpdate)
1437                 fprintf(stderr, "Header with wrong dumpdate.\n");
1438         /*
1439          * If we're restoring a filesystem with the old (FreeBSD 1)
1440          * format inodes, copy the uid/gid to the new location
1441          */
1442         if (oldinofmt) {
1443                 buf->c_uid = buf->c_spare1[1];
1444                 buf->c_gid = buf->c_spare1[2];
1445         }
1446         buf->c_magic = FS_UFS2_MAGIC;
1447         tapeaddr = buf->c_tapea;
1448         if (dflag)
1449                 accthdr(buf);
1450         return(GOOD);
1451 }
1452
1453 /*
1454  * Check that a header is where it belongs and predict the next header
1455  */
1456 static void
1457 accthdr(struct s_spcl *header)
1458 {
1459         static ino_t previno = 0x7fffffff;
1460         static int prevtype;
1461         static long predict;
1462         long blks, i;
1463
1464         if (header->c_type == TS_TAPE) {
1465                 fprintf(stderr, "Volume header ");
1466                 if (header->c_firstrec)
1467                         fprintf(stderr, "begins with record %qd",
1468                                 header->c_firstrec);
1469                 fprintf(stderr, "\n");
1470                 previno = 0x7fffffff;
1471                 return;
1472         }
1473         if (previno == 0x7fffffff)
1474                 goto newcalc;
1475         switch (prevtype) {
1476         case TS_BITS:
1477                 fprintf(stderr, "Dumped inodes map header");
1478                 break;
1479         case TS_CLRI:
1480                 fprintf(stderr, "Used inodes map header");
1481                 break;
1482         case TS_INODE:
1483                 fprintf(stderr, "File header, ino %d", previno);
1484                 break;
1485         case TS_ADDR:
1486                 fprintf(stderr, "File continuation header, ino %d", previno);
1487                 break;
1488         case TS_END:
1489                 fprintf(stderr, "End of tape header");
1490                 break;
1491         }
1492         if (predict != blksread - 1)
1493                 fprintf(stderr, "; predicted %ld blocks, got %ld blocks",
1494                         predict, blksread - 1);
1495         fprintf(stderr, "\n");
1496 newcalc:
1497         blks = 0;
1498         if (header->c_type != TS_END)
1499                 for (i = 0; i < header->c_count; i++)
1500                         if (readmapflag || header->c_addr[i] != 0)
1501                                 blks++;
1502         predict = blks;
1503         blksread = 0;
1504         prevtype = header->c_type;
1505         previno = header->c_inumber;
1506 }
1507
1508 /*
1509  * Find an inode header.
1510  * Complain if had to skip.
1511  */
1512 static void
1513 findinode(struct s_spcl *header)
1514 {
1515         static long skipcnt = 0;
1516         long i;
1517         char buf[TP_BSIZE];
1518         int htype;
1519
1520         curfile.name = "<name unknown>";
1521         curfile.action = UNKNOWN;
1522         curfile.mode = 0;
1523         curfile.ino = 0;
1524         do {
1525                 htype = header->c_type;
1526                 switch (htype) {
1527
1528                 case TS_ADDR:
1529                         /*
1530                          * Skip up to the beginning of the next record
1531                          */
1532                         for (i = 0; i < header->c_count; i++)
1533                                 if (header->c_addr[i])
1534                                         readtape(buf);
1535                         while (gethead(header) == FAIL ||
1536                             _time64_to_time(header->c_date) != dumpdate) {
1537                                 skipcnt++;
1538                                 if (Dflag) {
1539                                         byteslide++;
1540                                         if (byteslide < TP_BSIZE) {
1541                                                 blkcnt--;
1542                                                 blksread--;
1543                                         } else 
1544                                                 byteslide = 0;
1545                                 }
1546                         }
1547                         break;
1548
1549                 case TS_INODE:
1550                         curfile.mode = header->c_mode;
1551                         curfile.uid = header->c_uid;
1552                         curfile.gid = header->c_gid;
1553                         curfile.file_flags = header->c_file_flags;
1554                         curfile.rdev = header->c_rdev;
1555                         curfile.atime_sec = header->c_atime;
1556                         curfile.atime_nsec = header->c_atimensec;
1557                         curfile.mtime_sec = header->c_mtime;
1558                         curfile.mtime_nsec = header->c_mtimensec;
1559                         curfile.birthtime_sec = header->c_birthtime;
1560                         curfile.birthtime_nsec = header->c_birthtimensec;
1561                         curfile.extsize = header->c_extsize;
1562                         curfile.size = header->c_size;
1563                         curfile.ino = header->c_inumber;
1564                         break;
1565
1566                 case TS_END:
1567                         /* If we missed some tapes, get another volume. */
1568                         if (tapesread & (tapesread + 1)) {
1569                                 getvol(0);
1570                                 continue;
1571                         }
1572                         curfile.ino = maxino;
1573                         break;
1574
1575                 case TS_CLRI:
1576                         curfile.name = "<file removal list>";
1577                         break;
1578
1579                 case TS_BITS:
1580                         curfile.name = "<file dump list>";
1581                         break;
1582
1583                 case TS_TAPE:
1584                         if (Dflag)
1585                                 fprintf(stderr, "unexpected tape header\n");
1586                         else
1587                                 panic("unexpected tape header\n");
1588
1589                 default:
1590                         if (Dflag)
1591                                 fprintf(stderr, "unknown tape header type %d\n",
1592                                     spcl.c_type);
1593                         else
1594                                 panic("unknown tape header type %d\n",
1595                                     spcl.c_type);
1596                         while (gethead(header) == FAIL ||
1597                             _time64_to_time(header->c_date) != dumpdate) {
1598                                 skipcnt++;
1599                                 if (Dflag) {
1600                                         byteslide++;
1601                                         if (byteslide < TP_BSIZE) {
1602                                                 blkcnt--;
1603                                                 blksread--;
1604                                         } else 
1605                                                 byteslide = 0;
1606                                 }
1607                         }
1608
1609                 }
1610         } while (htype == TS_ADDR);
1611         if (skipcnt > 0)
1612                 fprintf(stderr, "resync restore, skipped %ld %s\n",
1613                     skipcnt, Dflag ? "bytes" : "blocks");
1614         skipcnt = 0;
1615 }
1616
1617 static int
1618 checksum(int *buf)
1619 {
1620         int i, j;
1621
1622         j = sizeof(union u_spcl) / sizeof(int);
1623         i = 0;
1624         if (!Bcvt) {
1625                 do
1626                         i += *buf++;
1627                 while (--j);
1628         } else {
1629                 /* What happens if we want to read restore tapes
1630                         for a 16bit int machine??? */
1631                 do
1632                         i += swabl(*buf++);
1633                 while (--j);
1634         }
1635
1636         if (i != CHECKSUM) {
1637                 fprintf(stderr, "Checksum error %o, inode %d file %s\n", i,
1638                         curfile.ino, curfile.name);
1639                 return(FAIL);
1640         }
1641         return(GOOD);
1642 }
1643
1644 #ifdef RRESTORE
1645 #include <stdarg.h>
1646
1647 void
1648 msg(const char *fmt, ...)
1649 {
1650         va_list ap;
1651         va_start(ap, fmt);
1652         (void)vfprintf(stderr, fmt, ap);
1653         va_end(ap);
1654 }
1655 #endif /* RRESTORE */
1656
1657 static u_char *
1658 swabshort(u_char *sp, int n)
1659 {
1660         char c;
1661
1662         while (--n >= 0) {
1663                 c = sp[0]; sp[0] = sp[1]; sp[1] = c;
1664                 sp += 2;
1665         }
1666         return (sp);
1667 }
1668
1669 static u_char *
1670 swablong(u_char *sp, int n)
1671 {
1672         char c;
1673
1674         while (--n >= 0) {
1675                 c = sp[0]; sp[0] = sp[3]; sp[3] = c;
1676                 c = sp[2]; sp[2] = sp[1]; sp[1] = c;
1677                 sp += 4;
1678         }
1679         return (sp);
1680 }
1681
1682 static u_char *
1683 swabquad(u_char *sp, int n)
1684 {
1685         char c;
1686
1687         while (--n >= 0) {
1688                 c = sp[0]; sp[0] = sp[7]; sp[7] = c;
1689                 c = sp[1]; sp[1] = sp[6]; sp[6] = c;
1690                 c = sp[2]; sp[2] = sp[5]; sp[5] = c;
1691                 c = sp[3]; sp[3] = sp[4]; sp[4] = c;
1692                 sp += 8;
1693         }
1694         return (sp);
1695 }
1696
1697 void
1698 swabst(u_char *cp, u_char *sp)
1699 {
1700         int n = 0;
1701
1702         while (*cp) {
1703                 switch (*cp) {
1704                 case '0': case '1': case '2': case '3': case '4':
1705                 case '5': case '6': case '7': case '8': case '9':
1706                         n = (n * 10) + (*cp++ - '0');
1707                         continue;
1708
1709                 case 's': case 'w': case 'h':
1710                         if (n == 0)
1711                                 n = 1;
1712                         sp = swabshort(sp, n);
1713                         break;
1714
1715                 case 'l':
1716                         if (n == 0)
1717                                 n = 1;
1718                         sp = swablong(sp, n);
1719                         break;
1720
1721                 case 'q':
1722                         if (n == 0)
1723                                 n = 1;
1724                         sp = swabquad(sp, n);
1725                         break;
1726
1727                 case 'b':
1728                         if (n == 0)
1729                                 n = 1;
1730                         sp += n;
1731                         break;
1732
1733                 default:
1734                         fprintf(stderr, "Unknown conversion character: %c\n",
1735                             *cp);
1736                         done(0);
1737                         break;
1738                 }
1739                 cp++;
1740                 n = 0;
1741         }
1742 }
1743
1744 static u_long
1745 swabl(u_long x)
1746 {
1747         swabst((u_char *)"l", (u_char *)&x);
1748         return (x);
1749 }