]> git.wh0rd.org Git - dump.git/blob - dump/main.c
Buffer overflow in dump, as reported from Bugtraq
[dump.git] / dump / main.c
1 /*
2  *      Ported to Linux's Second Extended File System as part of the
3  *      dump and restore backup suit
4  *      Remy Card <card@Linux.EU.Org>, 1994-1997
5  *      Stelian Pop <pop@cybercable.fr>, 1999-2000
6  */
7
8 /*-
9  * Copyright (c) 1980, 1991, 1993, 1994
10  *      The Regents of the University of California.  All rights reserved.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *      This product includes software developed by the University of
23  *      California, Berkeley and its contributors.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  */
40
41 #ifndef lint
42 static const char rcsid[] =
43         "$Id: main.c,v 1.17 2000/03/01 10:16:05 stelian Exp $";
44 #endif /* not lint */
45
46 #include <sys/param.h>
47 #include <sys/time.h>
48 #ifdef __linux__
49 #include <linux/ext2_fs.h>
50 #include <sys/stat.h>
51 #include <bsdcompat.h>
52 #else
53 #ifdef sunos
54 #include <sys/vnode.h>
55
56 #include <ufs/inode.h>
57 #include <ufs/fs.h>
58 #else
59 #include <ufs/ufs/dinode.h>
60 #include <ufs/ffs/fs.h>
61 #endif
62 #endif
63
64 #include <protocols/dumprestore.h>
65
66 #include <ctype.h>
67 #include <compaterr.h>
68 #include <fcntl.h>
69 #include <fstab.h>
70 #include <signal.h>
71 #include <stdio.h>
72 #include <stdlib.h>
73 #include <string.h>
74 #include <unistd.h>
75
76 #ifdef __linux__
77 #include <ext2fs/ext2fs.h>
78 #endif
79
80 #include "dump.h"
81 #include "pathnames.h"
82
83 #ifndef SBOFF
84 #define SBOFF (SBLOCK * DEV_BSIZE)
85 #endif
86
87 int     notify = 0;     /* notify operator flag */
88 int     blockswritten = 0;      /* number of blocks written on current tape */
89 int     tapeno = 0;     /* current tape number */
90 int     density = 0;    /* density in bytes/0.1" " <- this is for hilit19 */
91 int     ntrec = NTREC;  /* # tape blocks in each tape record */
92 int     cartridge = 0;  /* Assume non-cartridge tape */
93 int     dokerberos = 0; /* Use Kerberos authentication */
94 long    dev_bsize = 1;  /* recalculated below */
95 long    blocksperfile;  /* output blocks per file */
96 char    *host = NULL;   /* remote host (if any) */
97 int     sizest = 0;     /* return size estimate only */
98
99 #ifdef  __linux__
100 char    *__progname;
101 #endif
102
103 int     maxbsize = 64*1024;     /* XXX MAXBSIZE from sys/param.h */
104 static long numarg __P((const char *, long, long));
105 static void obsolete __P((int *, char **[]));
106 static void usage __P((void));
107
108 ino_t iexclude_list[IEXCLUDE_MAXNUM];   /* the inode exclude list */
109 int iexclude_num = 0;                   /* number of elements in the list */
110
111 int
112 main(int argc, char *argv[])
113 {
114         register ino_t ino;
115         register int dirty;
116         register struct dinode *dp;
117         register struct fstab *dt;
118         register char *map;
119         register int ch;
120         int i, anydirskipped, bflag = 0, Tflag = 0, honorlevel = 1;
121         ino_t maxino;
122 #ifdef  __linux__
123         errcode_t retval;
124         char directory[MAXPATHLEN];
125         char pathname[MAXPATHLEN];
126 #endif
127         time_t tnow;
128         char labelstr[LBLSIZE];
129
130         spcl.c_date = 0;
131 #ifdef  __linux__
132         (void)time4(&spcl.c_date);
133 #else
134         (void)time((time_t *)&spcl.c_date);
135 #endif
136
137 #ifdef __linux__
138         __progname = argv[0];
139         directory[0] = 0;
140         initialize_ext2_error_table();
141 #endif
142
143         tsize = 0;      /* Default later, based on 'c' option for cart tapes */
144         if ((tapeprefix = getenv("TAPE")) == NULL)
145                 tapeprefix = _PATH_DEFTAPE;
146         dumpdates = _PATH_DUMPDATES;
147         strcpy(labelstr, "none");       /* XXX safe strcpy. */
148         if (TP_BSIZE / DEV_BSIZE == 0 || TP_BSIZE % DEV_BSIZE != 0)
149                 quit("TP_BSIZE must be a multiple of DEV_BSIZE\n");
150         level = '0';
151
152         if (argc < 2)
153                 usage();
154
155         obsolete(&argc, &argv);
156 #ifdef KERBEROS
157 #define optstring "0123456789aB:b:cd:e:f:h:kL:Mns:ST:uWw"
158 #else
159 #define optstring "0123456789aB:b:cd:e:f:h:L:Mns:ST:uWw"
160 #endif
161         while ((ch = getopt(argc, argv, optstring)) != -1)
162 #undef optstring
163                 switch (ch) {
164                 /* dump level */
165                 case '0': case '1': case '2': case '3': case '4':
166                 case '5': case '6': case '7': case '8': case '9':
167                         level = ch;
168                         break;
169
170                 case 'a':               /* `auto-size', Write to EOM. */
171                         unlimited = 1;
172                         break;
173
174                 case 'B':               /* blocks per output file */
175                         blocksperfile = numarg("number of blocks per file",
176                             1L, 0L);
177                         break;
178
179                 case 'b':               /* blocks per tape write */
180                         ntrec = numarg("number of blocks per write",
181                             1L, 1000L);
182                         if (ntrec > maxbsize/1024) {
183                                 msg("Please choose a blocksize <= %dKB\n",
184                                         maxbsize/1024);
185                                 exit(X_STARTUP);
186                         }
187                         bflag = 1;
188                         break;
189
190                 case 'c':               /* Tape is cart. not 9-track */
191                         cartridge = 1;
192                         break;
193
194                 case 'd':               /* density, in bits per inch */
195                         density = numarg("density", 10L, 327670L) / 10;
196                         if (density >= 625 && !bflag)
197                                 ntrec = HIGHDENSITYTREC;
198                         break;
199                         
200                                         /* 04-Feb-00 ILC */
201                 case 'e':               /* exclude an inode */
202                         iexclude_list[iexclude_num++] = 
203                           numarg("inode to exclude",0L,0L);
204                         msg("Added %d to exclude list\n",
205                             iexclude_list[iexclude_num-1]);
206                         break;
207
208                 case 'f':               /* output file */
209                         tapeprefix = optarg;
210                         break;
211
212                 case 'h':
213                         honorlevel = numarg("honor level", 0L, 10L);
214                         break;
215
216 #ifdef KERBEROS
217                 case 'k':
218                         dokerberos = 1;
219                         break;
220 #endif
221
222                 case 'L':
223                         /*
224                          * Note that although there are LBLSIZE characters,
225                          * the last must be '\0', so the limit on strlen()
226                          * is really LBLSIZE-1.
227                          */
228                         strncpy(labelstr, optarg, LBLSIZE);
229                         labelstr[LBLSIZE-1] = '\0';
230                         if (strlen(optarg) > LBLSIZE-1) {
231                                 msg(
232                 "WARNING Label `%s' is larger than limit of %d characters.\n",
233                                     optarg, LBLSIZE-1);
234                                 msg("WARNING: Using truncated label `%s'.\n",
235                                     labelstr);
236                         }
237                         break;
238
239                 case 'M':               /* multi-volume flag */
240                         Mflag = 1;
241                         break;
242
243                 case 'n':               /* notify operators */
244                         notify = 1;
245                         break;
246
247                 case 's':               /* tape size, feet */
248                         tsize = numarg("tape size", 1L, 0L) * 12 * 10;
249                         break;
250
251                 case 'S':
252                         sizest = 1;     /* return size estimate only */
253                         break;
254
255                 case 'T':               /* time of last dump */
256                         spcl.c_ddate = unctime(optarg);
257                         if (spcl.c_ddate < 0) {
258                                 (void)fprintf(stderr, "bad time \"%s\"\n",
259                                     optarg);
260                                 exit(X_STARTUP);
261                         }
262                         Tflag = 1;
263                         lastlevel = '?';
264                         break;
265
266                 case 'u':               /* update dumpdates */
267                         uflag = 1;
268                         break;
269
270                 case 'W':               /* what to do */
271                 case 'w':
272                         lastdump(ch);
273                         exit(X_FINOK);  /* do nothing else */
274
275                 default:
276                         usage();
277                 }
278         argc -= optind;
279         argv += optind;
280
281         if (argc < 1) {
282                 (void)fprintf(stderr, "Must specify disk or filesystem\n");
283                 exit(X_STARTUP);
284         }
285         disk = *argv++;
286         if (strlen(disk) > MAXPATHLEN) {
287                 (void)fprintf(stderr, "Disk or filesystem name too long: %s\n", disk);
288                 exit(X_STARTUP);
289         }
290         argc--;
291         if (argc >= 1) {
292                 (void)fprintf(stderr, "Unknown arguments to dump:");
293                 while (argc--)
294                         (void)fprintf(stderr, " %s", *argv++);
295                 (void)fprintf(stderr, "\n");
296                 exit(X_STARTUP);
297         }
298         if (Tflag && uflag) {
299                 (void)fprintf(stderr,
300                     "You cannot use the T and u flags together.\n");
301                 exit(X_STARTUP);
302         }
303         if (strcmp(tapeprefix, "-") == 0) {
304                 pipeout++;
305                 tapeprefix = "standard output";
306         }
307
308         if (blocksperfile)
309                 blocksperfile = blocksperfile / ntrec * ntrec; /* round down */
310         else if (!unlimited) {
311                 /*
312                  * Determine how to default tape size and density
313                  *
314                  *              density                         tape size
315                  * 9-track      1600 bpi (160 bytes/.1")        2300 ft.
316                  * 9-track      6250 bpi (625 bytes/.1")        2300 ft.
317                  * cartridge    8000 bpi (100 bytes/.1")        1700 ft.
318                  *                                              (450*4 - slop)
319                  * hilit19 hits again: "
320                  */
321                 if (density == 0)
322                         density = cartridge ? 100 : 160;
323                 if (tsize == 0)
324                         tsize = cartridge ? 1700L*120L : 2300L*120L;
325         }
326
327         if (strchr(tapeprefix, ':')) {
328                 host = tapeprefix;
329                 tapeprefix = strchr(host, ':');
330                 *tapeprefix++ = '\0';
331 #ifdef RDUMP
332                 if (index(tapeprefix, '\n')) {
333                     (void)fprintf(stderr, "invalid characters in tape\n");
334                     exit(X_STARTUP);
335                 }
336                 if (rmthost(host) == 0)
337                         exit(X_STARTUP);
338 #else
339                 (void)fprintf(stderr, "remote dump not enabled\n");
340                 exit(X_STARTUP);
341 #endif
342         }
343         (void)setuid(getuid()); /* rmthost() is the only reason to be setuid */
344
345         if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
346                 signal(SIGHUP, sig);
347         if (signal(SIGTRAP, SIG_IGN) != SIG_IGN)
348                 signal(SIGTRAP, sig);
349         if (signal(SIGFPE, SIG_IGN) != SIG_IGN)
350                 signal(SIGFPE, sig);
351         if (signal(SIGBUS, SIG_IGN) != SIG_IGN)
352                 signal(SIGBUS, sig);
353         if (signal(SIGSEGV, SIG_IGN) != SIG_IGN)
354                 signal(SIGSEGV, sig);
355         if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
356                 signal(SIGTERM, sig);
357         if (signal(SIGINT, interrupt) == SIG_IGN)
358                 signal(SIGINT, SIG_IGN);
359         set_operators();        /* /etc/group snarfed */
360         getfstab();             /* /etc/fstab snarfed */
361         /*
362          *      disk may end in / and this can confuse
363          *      fstabsearch.
364          */
365         if (strlen(disk) > 1 && disk[strlen(disk) - 1] == '/')
366           disk[strlen(disk) - 1] = '\0';
367         /*
368          *      disk can be either the full special file name,
369          *      the suffix of the special file name,
370          *      the special name missing the leading '/',
371          *      the file system name with or without the leading '/'.
372          */
373         if ((dt = fstabsearch(disk)) != NULL) {
374                 disk = rawname(dt->fs_spec);
375                 (void)strncpy(spcl.c_dev, dt->fs_spec, NAMELEN);
376                 (void)strncpy(spcl.c_filesys, dt->fs_file, NAMELEN);
377 #ifdef  __linux__
378         } else {
379                 /*
380                  * The argument was not found in the fstab
381                  * assume that this is a subtree and search for it
382                  */
383 #ifdef  HAVE_REALPATH
384                 if (realpath(disk, pathname) == NULL)
385 #endif
386                         strcpy(pathname, disk);
387                 dt = fstabsearchdir(pathname, directory);
388                 if (dt != NULL) {
389                         char name[MAXPATHLEN];
390                         (void)strncpy(spcl.c_dev, dt->fs_spec, NAMELEN);
391                         (void)sprintf(name, "%s (dir %s)",
392                                       dt->fs_file, directory);
393                         (void)strncpy(spcl.c_filesys, name, NAMELEN);
394                         disk = rawname(dt->fs_spec);
395                 } else {
396                         (void)strncpy(spcl.c_dev, disk, NAMELEN);
397                         (void)strncpy(spcl.c_filesys, "an unlisted file system",
398                             NAMELEN);
399                 }
400         }
401 #else
402         } else {
403                 (void)strncpy(spcl.c_dev, disk, NAMELEN);
404                 (void)strncpy(spcl.c_filesys, "an unlisted file system",
405                     NAMELEN);
406         }
407 #endif
408         spcl.c_dev[NAMELEN-1]='\0';
409         spcl.c_filesys[NAMELEN-1]='\0';
410         (void)strncpy(spcl.c_label, labelstr, sizeof(spcl.c_label) - 1);
411         (void)gethostname(spcl.c_host, NAMELEN);
412         spcl.c_level = level - '0';
413         spcl.c_type = TS_TAPE;
414         if (!Tflag)
415                 getdumptime(uflag);             /* dumpdates snarfed */
416
417         if (spcl.c_ddate == 0 && spcl.c_level) {
418                 msg("WARNING: There is no inferior level dump on this filesystem\n"); 
419                 msg("WARNING: Assuming a level 0 dump by default\n");
420                 level = '0';
421                 spcl.c_level = 0;
422         }
423
424         if (Mflag)
425                 snprintf(tape, MAXPATHLEN, "%s%03d", tapeprefix, tapeno + 1);
426         else
427                 strncpy(tape, tapeprefix, MAXPATHLEN);
428         tape[MAXPATHLEN - 1] = '\0';
429
430         if (!sizest) {
431
432                 msg("Date of this level %c dump: %s", level,
433 #ifdef  __linux__
434                         spcl.c_date == 0 ? "the epoch\n" : ctime4(&spcl.c_date));
435 #else
436                         spcl.c_date == 0 ? "the epoch\n" : ctime(&spcl.c_date));
437 #endif
438                 msg("Date of last level %c dump: %s", lastlevel,
439 #ifdef  __linux__
440                         spcl.c_ddate == 0 ? "the epoch\n" : ctime4(&spcl.c_ddate));
441 #else
442                         spcl.c_ddate == 0 ? "the epoch\n" : ctime(&spcl.c_ddate));
443 #endif
444                 msg("Dumping %s (%s) ", disk, spcl.c_filesys);
445                 if (host)
446                         msgtail("to %s on host %s\n", tape, host);
447                 else
448                         msgtail("to %s\n", tape);
449                 msg("Label: %s\n", labelstr);
450
451         } /* end of size estimate */
452
453 #ifdef  __linux__
454         retval = dump_fs_open(disk, &fs);
455         if (retval) {
456                 com_err(disk, retval, "while opening filesystem");
457                 if (retval == EXT2_ET_REV_TOO_HIGH)
458                         printf ("Get a newer version of dump!\n");
459                 exit(X_STARTUP);
460         }
461         if (fs->super->s_rev_level > DUMP_CURRENT_REV) {
462                 com_err(disk, retval, "while opening filesystem");
463                 printf ("Get a newer version of dump!\n");
464                 exit(X_STARTUP);
465         }
466         if ((diskfd = open(disk, O_RDONLY)) < 0) {
467                 msg("Cannot open %s\n", disk);
468                 exit(X_STARTUP);
469         }
470         sync();
471         dev_bsize = DEV_BSIZE;
472         dev_bshift = ffs(dev_bsize) - 1;
473         if (dev_bsize != (1 << dev_bshift))
474                 quit("dev_bsize (%d) is not a power of 2", dev_bsize);
475         tp_bshift = ffs(TP_BSIZE) - 1;
476         if (TP_BSIZE != (1 << tp_bshift))
477                 quit("TP_BSIZE (%d) is not a power of 2", TP_BSIZE);
478         maxino = fs->super->s_inodes_count;
479 #if     0
480         spcl.c_flags |= DR_NEWINODEFMT;
481 #endif
482 #else   /* __linux __*/
483         if ((diskfd = open(disk, O_RDONLY)) < 0) {
484                 msg("Cannot open %s\n", disk);
485                 exit(X_STARTUP);
486         }
487         sync();
488         sblock = (struct fs *)sblock_buf;
489         bread(SBOFF, (char *) sblock, SBSIZE);
490         if (sblock->fs_magic != FS_MAGIC)
491                 quit("bad sblock magic number\n");
492         dev_bsize = sblock->fs_fsize / fsbtodb(sblock, 1);
493         dev_bshift = ffs(dev_bsize) - 1;
494         if (dev_bsize != (1 << dev_bshift))
495                 quit("dev_bsize (%d) is not a power of 2", dev_bsize);
496         tp_bshift = ffs(TP_BSIZE) - 1;
497         if (TP_BSIZE != (1 << tp_bshift))
498                 quit("TP_BSIZE (%d) is not a power of 2", TP_BSIZE);
499 #ifdef FS_44INODEFMT
500         if (sblock->fs_inodefmt >= FS_44INODEFMT)
501                 spcl.c_flags |= DR_NEWINODEFMT;
502 #endif
503         maxino = sblock->fs_ipg * sblock->fs_ncg;
504 #endif  /* __linux__ */
505         mapsize = roundup(howmany(maxino, NBBY), TP_BSIZE);
506         usedinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
507         dumpdirmap = (char *)calloc((unsigned) mapsize, sizeof(char));
508         dumpinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
509         tapesize = 3 * (howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
510
511         nonodump = spcl.c_level < honorlevel;
512
513 #if defined(SIGINFO)
514         (void)signal(SIGINFO, statussig);
515 #endif
516
517         if (!sizest)
518                 msg("mapping (Pass I) [regular files]\n");
519 #ifdef  __linux__
520         if (directory[0] == 0)
521                 anydirskipped = mapfiles(maxino, &tapesize);
522         else
523                 anydirskipped = mapfilesfromdir(maxino, &tapesize, directory);
524 #else
525         anydirskipped = mapfiles(maxino, &tapesize);
526 #endif
527
528         if (!sizest)
529                 msg("mapping (Pass II) [directories]\n");
530         while (anydirskipped) {
531                 anydirskipped = mapdirs(maxino, &tapesize);
532         }
533
534         if (sizest) {
535                 printf("%.0f\n", ((double)tapesize + 10) * TP_BSIZE);
536                 exit(X_FINOK);
537         } /* stop here for size estimate */
538
539         if (pipeout || unlimited) {
540                 tapesize += 10; /* 10 trailer blocks */
541                 msg("estimated %ld tape blocks.\n", tapesize);
542         } else {
543                 double fetapes;
544
545                 if (blocksperfile)
546                         fetapes = (double) tapesize / blocksperfile;
547                 else if (cartridge) {
548                         /* Estimate number of tapes, assuming streaming stops at
549                            the end of each block written, and not in mid-block.
550                            Assume no erroneous blocks; this can be compensated
551                            for with an artificially low tape size. */
552                         fetapes =
553                         (         (double) tapesize     /* blocks */
554                                 * TP_BSIZE      /* bytes/block */
555                                 * (1.0/density) /* 0.1" / byte " */
556                           +
557                                   (double) tapesize     /* blocks */
558                                 * (1.0/ntrec)   /* streaming-stops per block */
559                                 * 15.48         /* 0.1" / streaming-stop " */
560                         ) * (1.0 / tsize );     /* tape / 0.1" " */
561                 } else {
562                         /* Estimate number of tapes, for old fashioned 9-track
563                            tape */
564                         int tenthsperirg = (density == 625) ? 3 : 7;
565                         fetapes =
566                         (         (double) tapesize     /* blocks */
567                                 * TP_BSIZE      /* bytes / block */
568                                 * (1.0/density) /* 0.1" / byte " */
569                           +
570                                   (double) tapesize     /* blocks */
571                                 * (1.0/ntrec)   /* IRG's / block */
572                                 * tenthsperirg  /* 0.1" / IRG " */
573                         ) * (1.0 / tsize );     /* tape / 0.1" " */
574                 }
575                 etapes = fetapes;               /* truncating assignment */
576                 etapes++;
577                 /* count the dumped inodes map on each additional tape */
578                 tapesize += (etapes - 1) *
579                         (howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
580                 tapesize += etapes + 10;        /* headers + 10 trailer blks */
581                 msg("estimated %ld tape blocks on %3.2f tape(s).\n",
582                     tapesize, fetapes);
583         }
584
585         /*
586          * Allocate tape buffer.
587          */
588         if (!alloctape())
589                 quit(
590         "can't allocate tape buffers - try a smaller blocking factor.\n");
591
592         startnewtape(1);
593 #ifdef __linux__
594         (void)time4(&(tstart_writing));
595 #else
596         (void)time((time_t *)&(tstart_writing));
597 #endif
598         dumpmap(usedinomap, TS_CLRI, maxino - 1);
599
600         msg("dumping (Pass III) [directories]\n");
601         dirty = 0;              /* XXX just to get gcc to shut up */
602         for (map = dumpdirmap, ino = 1; ino < maxino; ino++) {
603                 if (((ino - 1) % NBBY) == 0)    /* map is offset by 1 */
604                         dirty = *map++;
605                 else
606                         dirty >>= 1;
607                 if ((dirty & 1) == 0)
608                         continue;
609                 /*
610                  * Skip directory inodes deleted and maybe reallocated
611                  */
612                 dp = getino(ino);
613                 if ((dp->di_mode & IFMT) != IFDIR)
614                         continue;
615 #ifdef  __linux__
616                 /*
617                  * Skip directory inodes deleted and not yes reallocated...
618                  */
619                 if (dp->di_nlink == 0 || dp->di_dtime != 0)
620                         continue;
621                 (void)dumpdirino(dp, ino);
622 #else
623                 (void)dumpino(dp, ino);
624 #endif
625         }
626
627         msg("dumping (Pass IV) [regular files]\n");
628         for (map = dumpinomap, ino = 1; ino < maxino; ino++) {
629                 if (((ino - 1) % NBBY) == 0)    /* map is offset by 1 */
630                         dirty = *map++;
631                 else
632                         dirty >>= 1;
633                 if ((dirty & 1) == 0)
634                         continue;
635                 /*
636                  * Skip inodes deleted and reallocated as directories.
637                  */
638                 dp = getino(ino);
639                 if ((dp->di_mode & IFMT) == IFDIR)
640                         continue;
641 #ifdef __linux__
642                 /*
643                  * No need to check here for deleted and not yes reallocated inodes
644                  * since this is done in dumpino().
645                  */
646 #endif
647                 (void)dumpino(dp, ino);
648         }
649
650 #ifdef __linux__
651         (void)time4(&(tend_writing));
652 #else
653         (void)time((time_t *)&(tend_writing));
654 #endif
655         spcl.c_type = TS_END;
656         for (i = 0; i < ntrec; i++)
657                 writeheader(maxino - 1);
658         if (pipeout)
659                 msg("DUMP: %ld tape blocks\n", spcl.c_tapea);
660         else
661                 msg("DUMP: %ld tape blocks on %d volumes(s)\n",
662                     spcl.c_tapea, spcl.c_volume);
663
664         /* report dump performance, avoid division through zero */
665         if (tend_writing - tstart_writing == 0)
666                 msg("finished in less than a second\n");
667         else
668                 msg("finished in %d seconds, throughput %d KBytes/sec\n",
669                     tend_writing - tstart_writing,
670                     spcl.c_tapea / (tend_writing - tstart_writing));
671
672         tnow = do_stats();
673         putdumptime();
674 #ifdef __linux__
675         msg("DUMP: Date of this level %c dump: %s", level,
676                 spcl.c_date == 0 ? "the epoch\n" : ctime4(&spcl.c_date));
677 #else
678         msg("DUMP: Date of this level %c dump: %s", level,
679                 spcl.c_date == 0 ? "the epoch\n" : ctime(&spcl.c_date));
680 #endif
681         msg("DUMP: Date this dump completed:  %s", ctime(&tnow));
682
683         msg("DUMP: Average transfer rate: %ld KB/s\n", xferrate / tapeno);
684
685         trewind();
686         broadcast("DUMP IS DONE!\7\7\n");
687         msg("DUMP IS DONE\n");
688         Exit(X_FINOK);
689         /* NOTREACHED */
690         return 0;       /* gcc - shut up */
691 }
692
693 static void
694 usage(void)
695 {
696         char white[MAXPATHLEN];
697         int i;
698         
699         strncpy(white, __progname, MAXPATHLEN-1);
700         white[MAXPATHLEN-1] = '\0';
701         for (i=0; i<MAXPATHLEN; ++i)
702                 if (white[i] != '\0') white[i] = ' ';
703
704         fprintf(stderr,
705                 "%s %s\n", __progname, _DUMP_VERSION);
706         fprintf(stderr,
707                 "usage:\t%s [-0123456789ac"
708 #ifdef KERBEROS
709                 "k"
710 #endif
711                 "MnSu] [-B records] [-b blocksize] [-d density]\n"
712                 "\t%s [-e inode#] [-f file] [-h level] [-s feet] [-T date] filesystem\n"
713                 "\t%s [-W | -w]\n", __progname, white, __progname);
714         exit(X_STARTUP);
715 }
716
717 /*
718  * Pick up a numeric argument.  It must be nonnegative and in the given
719  * range (except that a vmax of 0 means unlimited).
720  */
721 static long
722 numarg(const char *meaning, long vmin, long vmax)
723 {
724         char *p;
725         long val;
726
727         val = strtol(optarg, &p, 10);
728         if (*p)
729                 errx(X_STARTUP, "illegal %s -- %s", meaning, optarg);
730         if (val < vmin || (vmax && val > vmax))
731                 errx(X_STARTUP, "%s must be between %ld and %ld", meaning, vmin, vmax);
732         return (val);
733 }
734
735 void
736 sig(int signo)
737 {
738         switch(signo) {
739         case SIGALRM:
740         case SIGBUS:
741         case SIGFPE:
742         case SIGHUP:
743         case SIGTERM:
744         case SIGTRAP:
745                 if (pipeout)
746                         quit("Signal on pipe: cannot recover\n");
747                 msg("Rewriting attempted as response to unknown signal.\n");
748                 (void)fflush(stderr);
749                 (void)fflush(stdout);
750                 close_rewind();
751                 exit(X_REWRITE);
752                 /* NOTREACHED */
753         case SIGSEGV:
754                 msg("SIGSEGV: ABORTING!\n");
755                 (void)signal(SIGSEGV, SIG_DFL);
756                 (void)kill(0, SIGSEGV);
757                 /* NOTREACHED */
758         }
759 }
760
761 char *
762 rawname(char *cp)
763 {
764 #ifdef  __linux__
765         return cp;
766 #else   /* __linux__ */
767         static char rawbuf[MAXPATHLEN];
768         char *dp = strrchr(cp, '/');
769
770         if (dp == NULL)
771                 return (NULL);
772         *dp = '\0';
773         (void)strncpy(rawbuf, cp, MAXPATHLEN - 1);
774         rawbuf[MAXPATHLEN-1] = '\0';
775         *dp = '/';
776         (void)strncat(rawbuf, "/r", MAXPATHLEN - 1 - strlen(rawbuf));
777         (void)strncat(rawbuf, dp + 1, MAXPATHLEN - 1 - strlen(rawbuf));
778         return (rawbuf);
779 #endif  /* __linux__ */
780 }
781
782 /*
783  * obsolete --
784  *      Change set of key letters and ordered arguments into something
785  *      getopt(3) will like.
786  */
787 static void
788 obsolete(int *argcp, char **argvp[])
789 {
790         int argc, flags;
791         char *ap, **argv, *flagsp=NULL, **nargv, *p=NULL;
792
793         /* Setup. */
794         argv = *argvp;
795         argc = *argcp;
796
797         /* Return if no arguments or first argument has leading dash. */
798         ap = argv[1];
799         if (argc == 1 || *ap == '-')
800                 return;
801
802         /* Allocate space for new arguments. */
803         if ((*argvp = nargv = malloc((argc + 1) * sizeof(char *))) == NULL ||
804             (p = flagsp = malloc(strlen(ap) + 2)) == NULL)
805                 err(X_STARTUP, "malloc new args");
806
807         *nargv++ = *argv;
808         argv += 2;
809
810         for (flags = 0; *ap; ++ap) {
811                 switch (*ap) {
812                 case 'B':
813                 case 'b':
814                 case 'd':
815                 case 'f':
816                 case 'h':
817                 case 's':
818                 case 'T':
819                         if (*argv == NULL) {
820                                 warnx("option requires an argument -- %c", *ap);
821                                 usage();
822                         }
823                         if ((nargv[0] = malloc(strlen(*argv) + 2 + 1)) == NULL)
824                                 err(X_STARTUP, "malloc arg");
825                         nargv[0][0] = '-';
826                         nargv[0][1] = *ap;
827                         (void)strcpy(&nargv[0][2], *argv);
828                         ++argv;
829                         ++nargv;
830                         break;
831                 default:
832                         if (!flags) {
833                                 *p++ = '-';
834                                 flags = 1;
835                         }
836                         *p++ = *ap;
837                         break;
838                 }
839         }
840
841         /* Terminate flags. */
842         if (flags) {
843                 *p = '\0';
844                 *nargv++ = flagsp;
845         }
846
847         /* Copy remaining arguments. */
848         while ((*nargv++ = *argv++));
849
850         /* Update argument count. */
851         *argcp = nargv - *argvp - 1;
852 }