]> git.wh0rd.org Git - dump.git/blob - dump/main.c
Made dump use blkid library.
[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 <stelian@popies.net>, 1999-2000
6  *      Stelian Pop <stelian@popies.net> - AlcĂ´ve <www.alcove.com>, 2000-2002
7  */
8
9 /*-
10  * Copyright (c) 1980, 1991, 1993, 1994
11  *      The Regents of the University of California.  All rights reserved.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  */
37
38 #ifndef lint
39 static const char rcsid[] =
40         "$Id: main.c,v 1.93 2004/06/02 09:22:49 stelian Exp $";
41 #endif /* not lint */
42
43 #include <config.h>
44 #include <compatlfs.h>
45 #include <ctype.h>
46 #include <compaterr.h>
47 #include <fcntl.h>
48 #include <fstab.h>
49 #include <signal.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 #include <errno.h>
55 #include <mntent.h>
56
57 #include <sys/param.h>
58 #include <sys/time.h>
59 #include <time.h>
60 #ifdef __linux__
61 #include <linux/types.h>
62 #ifdef HAVE_EXT2FS_EXT2_FS_H
63 #include <ext2fs/ext2_fs.h>
64 #else
65 #include <linux/ext2_fs.h>
66 #endif
67 #include <ext2fs/ext2fs.h>
68 #include <sys/stat.h>
69 #include <bsdcompat.h>
70 #include <linux/fs.h>   /* for definition of BLKFLSBUF */
71 #elif defined sunos
72 #include <sys/vnode.h>
73
74 #include <ufs/inode.h>
75 #include <ufs/fs.h>
76 #else
77 #include <ufs/ufs/dinode.h>
78 #include <ufs/ffs/fs.h>
79 #endif
80
81 #include <protocols/dumprestore.h>
82
83 #include "dump.h"
84 #include "pathnames.h"
85 #include "bylabel.h"
86
87 #ifndef SBOFF
88 #define SBOFF (SBLOCK * DEV_BSIZE)
89 #endif
90
91 int abortifconnerr = 1;         /* set to 1 if lib dumprmt.o should exit on connection errors
92                                 otherwise just print a message using msg */
93 /*
94  * Dump maps used to describe what is to be dumped.
95  */
96 int     mapsize;        /* size of the state maps */
97 char    *usedinomap;    /* map of allocated inodes */
98 char    *dumpdirmap;    /* map of directories to be dumped */
99 char    *dumpinomap;    /* map of files to be dumped */
100 char    *metainomap;    /* which of the inodes in dumpinomap will get
101                            only their metadata dumped */
102
103 const char *disk;       /* name of the disk file */
104 char    tape[MAXPATHLEN];/* name of the tape file */
105 char    *tapeprefix;    /* prefix of the tape file */
106 char    *dumpdates;     /* name of the file containing dump date information*/
107 char    lastlevel[NUM_STR_SIZE];/* dump level of previous dump */
108 char    level[NUM_STR_SIZE];/* dump level of this dump */
109 int     zipflag;        /* which compression method */
110 int     Afile = -1;     /* archive file descriptor */
111 int     AfileActive = 1;/* Afile flag */
112 int     uflag;          /* update flag */
113 int     mflag;          /* dump metadata only if possible */
114 int     Mflag;          /* multi-volume flag */
115 int     qflag;          /* quit on errors flag */
116 int     vflag;          /* verbose flag */
117 int     breademax = 32; /* maximum number of bread errors before we quit */
118 char    *eot_script;    /* end of volume script fiag */
119 int     diskfd;         /* disk file descriptor */
120 int     tapefd;         /* tape file descriptor */
121 int     pipeout;        /* true => output to standard output */
122 int     fifoout;        /* true => output to fifo */
123 dump_ino_t curino;      /* current inumber; used globally */
124 int     newtape;        /* new tape flag */
125 int     density;        /* density in 0.1" units */
126 long    tapesize;       /* estimated tape size, blocks */
127 long    tsize;          /* tape size in 0.1" units */
128 long    asize;          /* number of 0.1" units written on current tape */
129 int     etapes;         /* estimated number of tapes */
130 int     nonodump;       /* if set, do not honor UF_NODUMP user flags */
131 int     unlimited;      /* if set, write to end of medium */
132 int     compressed;     /* if set, dump is to be compressed */
133 long long bytes_written;/* total bytes written to tape */
134 long    uncomprblks;    /* uncompressed blocks written to tape */
135 int     notify;         /* notify operator flag */
136 int     blockswritten;  /* number of blocks written on current tape */
137 int     tapeno;         /* current tape number */
138 time_t  tstart_writing; /* when started writing the first tape block */
139 time_t  tend_writing;   /* after writing the last tape block */
140 #ifdef __linux__
141 ext2_filsys fs;
142 #else
143 struct  fs *sblock;     /* the file system super block */
144 char    sblock_buf[MAXBSIZE];
145 #endif
146 long    xferrate;       /* averaged transfer rate of all volumes */
147 long    dev_bsize;      /* block size of underlying disk device */
148 int     dev_bshift;     /* log2(dev_bsize) */
149 int     tp_bshift;      /* log2(TP_BSIZE) */
150 dump_ino_t volinfo[TP_NINOS];/* which inode on which volume archive info */
151
152 #ifdef USE_QFA
153 int     gTapeposfd;
154 char    *gTapeposfile;
155 char    gTps[255];
156 int32_t gThisDumpDate;
157 #endif /* USE_QFA */
158
159 struct  dumptime *dthead;       /* head of the list version */
160 int     nddates;                /* number of records (might be zero) */
161 int     ddates_in;              /* we have read the increment file */
162 struct  dumpdates **ddatev;     /* the arrayfied version */
163
164 int     notify = 0;     /* notify operator flag */
165 int     blockswritten = 0;      /* number of blocks written on current tape */
166 int     tapeno = 0;     /* current tape number */
167 int     density = 0;    /* density in bytes/0.1" " <- this is for hilit19 */
168 int     ntrec = NTREC;  /* # blocks in each tape record */
169 int     cartridge = 0;  /* Assume non-cartridge tape */
170 #ifdef USE_QFA
171 int     tapepos = 0;    /* assume no QFA tapeposition needed by user */
172 #endif /* USE_QFA */
173 int     dokerberos = 0; /* Use Kerberos authentication */
174 long    dev_bsize = 1;  /* recalculated below */
175 long    *blocksperfiles = NULL; /* output blocks per file(s) */
176 char    *host = NULL;   /* remote host (if any) */
177 int     sizest = 0;     /* return size estimate only */
178 int     compressed = 0; /* use zlib to compress the output, compress level 1-9 */
179 long long bytes_written = 0; /* total bytes written */
180 long    uncomprblks = 0;/* uncompressed blocks written */
181
182 long smtc_errno;
183
184 #ifdef  __linux__
185 char    *__progname;
186 #endif
187
188 int     maxbsize = 1024*1024;     /* XXX MAXBSIZE from sys/param.h */
189 static long numarg __P((const char *, long, long));
190 static long *numlistarg __P((const char *, long, long));
191 static void obsolete __P((int *, char **[]));
192 static void usage __P((void));
193 static void do_exclude_from_file __P((char *));
194 static void do_exclude_ino_str __P((char *));
195 static void incompat_flags __P((int, char, char));
196
197 static char* iexclude_bitmap = NULL;            /* the inode exclude bitmap */
198 static unsigned int iexclude_bitmap_bytes = 0;  /* size of bitmap in bytes */
199
200 int
201 main(int argc, char *argv[])
202 {
203         dump_ino_t ino;
204         int dirty;
205         struct dinode *dp;
206         struct mntent *dt;
207         char *map;
208         int ch, pch = 0;
209         int i, anydirskipped;
210         int aflag = 0, bflag = 0, Tflag = 0, honorlevel = 1;
211         dump_ino_t maxino;
212         struct STAT statbuf;
213         dev_t filedev = 0;
214 #ifdef  __linux__
215         errcode_t retval;
216         char directory[MAXPATHLEN];
217         char pathname[MAXPATHLEN];
218 #endif
219         time_t tnow;
220         char *diskparam;
221         char *Apath = NULL;
222
223         spcl.c_label[0] = '\0';
224         spcl.c_date = time(NULL);
225
226 #ifdef __linux__
227         __progname = argv[0];
228         directory[0] = 0;
229         initialize_ext2_error_table();
230 #endif
231
232         tsize = 0;      /* Default later, based on 'c' option for cart tapes */
233         unlimited = 1;
234         eot_script = NULL;
235         if ((tapeprefix = getenv("TAPE")) == NULL)
236                 tapeprefix = _PATH_DEFTAPE;
237         dumpdates = _PATH_DUMPDATES;
238         if (TP_BSIZE / DEV_BSIZE == 0 || TP_BSIZE % DEV_BSIZE != 0)
239                 quit("TP_BSIZE must be a multiple of DEV_BSIZE\n");
240         memset(&lastlevel, 0, NUM_STR_SIZE);
241         memset(&level, 0, NUM_STR_SIZE);
242
243         if (argc < 2)
244                 usage();
245
246         obsolete(&argc, &argv);
247
248 #ifdef USE_QFA
249         gTapeposfd = -1;
250 #endif /* USE_QFA */
251
252         while ((ch = getopt(argc, argv,
253                             "0123456789A:aB:b:cd:D:e:E:f:F:h:I:"
254 #ifdef HAVE_BZLIB
255                             "j::"
256 #endif
257                             "L:"
258 #ifdef KERBEROS
259                             "k"
260 #endif
261                             "mMnq"
262 #ifdef USE_QFA
263                             "Q:"
264 #endif
265                             "s:ST:uvWw"
266 #ifdef HAVE_LZO
267                             "y"
268 #endif
269 #ifdef HAVE_ZLIB
270                             "z::"
271 #endif
272                             )) != -1)
273                 switch (ch) {
274                 /* dump level */
275                 case '0': case '1': case '2': case '3': case '4':
276                 case '5': case '6': case '7': case '8': case '9':
277                         if ((pch >= '0') && (pch <= '9') && (strlen(level) < NUM_STR_SIZE))
278                                 level[strlen(level)] = ch;
279                         else 
280                                 level[0] = ch;
281                         pch = ch;
282                         break;
283
284                 case 'A':               /* archive file */
285                         Apath = optarg;
286                         break;
287
288                 case 'a':               /* `auto-size', Write to EOM. */
289                         unlimited = 1;
290                         aflag = 1;
291                         break;
292
293                 case 'B':               /* blocks per output file */
294                         unlimited = 0;
295                         blocksperfiles = numlistarg("number of blocks per file",
296                             1L, 0L);
297                         break;
298
299                 case 'b':               /* blocks per tape write */
300                         ntrec = numarg("number of blocks per write",
301                             1L, 1048576L);
302                         if (ntrec > maxbsize/1024) {
303                                 msg("Please choose a blocksize <= %dkB\n",
304                                         maxbsize/1024);
305                                 msg("The ENTIRE dump is aborted.\n");
306                                 exit(X_STARTUP);
307                         }
308                         bflag = 1;
309                         break;
310
311                 case 'c':               /* Tape is cart. not 9-track */
312                         unlimited = 0;
313                         cartridge = 1;
314                         break;
315
316                 case 'd':               /* density, in bits per inch */
317                         unlimited = 0;
318                         density = numarg("density", 10L, 327670L) / 10;
319                         if (density >= 625 && !bflag)
320                                 ntrec = HIGHDENSITYTREC;
321                         break;
322
323                 case 'D':               /* path of dumpdates file */
324                         dumpdates = optarg;
325                         break;
326                         
327                                         /* 04-Feb-00 ILC */
328                 case 'e':               /* exclude an inode */
329                         {
330                         char *p = optarg, *q;
331                         while ((q = strchr(p, ','))) {
332                                 *q = '\0';
333                                 do_exclude_ino_str(p);
334                                 p = q + 1;
335                         }
336                         do_exclude_ino_str(p);
337                         }
338                         break;
339
340                 case 'E':               /* exclude inodes read from file */
341                         do_exclude_from_file(optarg);
342                         break;
343
344                 case 'f':               /* output file */
345                         tapeprefix = optarg;
346                         break;
347
348                 case 'F':               /* end of tape script */
349                         eot_script = optarg;
350                         break;
351
352                 case 'h':
353                         honorlevel = numarg("honor level", 0L, 10L);
354                         break;
355
356 #ifdef HAVE_BZLIB
357                 case 'j':
358                         compressed = 2;
359                         zipflag = COMPRESS_BZLIB;
360                         if (optarg)
361                                 compressed = numarg("compress level", 1L, 9L);
362                         break;
363 #endif /* HAVE_BZLIB */
364
365                 case 'I':
366                         breademax =
367                           numarg ("number of errors to ignore", 0L, 0L);
368                         break;
369
370 #ifdef KERBEROS
371                 case 'k':
372                         dokerberos = 1;
373                         break;
374 #endif
375
376                 case 'L':
377                         /*
378                          * Note that although there are LBLSIZE characters,
379                          * the last must be '\0', so the limit on strlen()
380                          * is really LBLSIZE-1.
381                          */
382                         strncpy(spcl.c_label, optarg, LBLSIZE);
383                         spcl.c_label[LBLSIZE-1] = '\0';
384                         if (strlen(optarg) > LBLSIZE-1) {
385                                 msg(
386                 "WARNING Label `%s' is larger than limit of %d characters.\n",
387                                     optarg, LBLSIZE-1);
388                                 msg("WARNING: Using truncated label `%s'.\n",
389                                     spcl.c_label);
390                         }
391                         break;
392
393                 case 'm':               /* metadata only flag */
394                         mflag = 1;
395                         break;
396
397                 case 'M':               /* multi-volume flag */
398                         Mflag = 1;
399                         break;
400
401                 case 'n':               /* notify operators */
402                         notify = 1;
403                         break;
404
405                 case 'q':
406                         qflag = 1;
407                         break;
408
409 #ifdef USE_QFA
410                 case 'Q':               /* create tapeposfile */
411                         gTapeposfile = optarg;
412                         tapepos = 1;
413                         break;
414 #endif /* USE_QFA */
415                         
416                 case 's':               /* tape size, feet */
417                         unlimited = 0;
418                         tsize = numarg("tape size", 1L, 0L) * 12 * 10;
419                         break;
420
421                 case 'S':
422                         sizest = 1;     /* return size estimate only */
423                         break;
424
425                 case 'T':               /* time of last dump */
426                         spcl.c_ddate = unctime(optarg);
427                         if (spcl.c_ddate < 0) {
428                                 msg("bad time \"%s\"\n", optarg);
429                                 msg("The ENTIRE dump is aborted.\n");
430                                 exit(X_STARTUP);
431                         }
432                         Tflag = 1;
433                         lastlevel[0] = '?'; lastlevel[1] = '\0'; 
434                         break;
435
436                 case 'u':               /* update dumpdates */
437                         uflag = 1;
438                         break;
439
440                 case 'v':               /* verbose */
441                         vflag = 1;
442                         break;
443
444                 case 'W':               /* what to do */
445                 case 'w':
446                         lastdump(ch);
447                         exit(X_FINOK);  /* do nothing else */
448 #ifdef HAVE_LZO
449                 case 'y':
450                         compressed = 2;
451                         zipflag = COMPRESS_LZO;
452                         break;
453 #endif /* HAVE_LZO */
454
455 #ifdef HAVE_ZLIB
456                 case 'z':
457                         compressed = 2;
458                         zipflag = COMPRESS_ZLIB;
459                         if (optarg)
460                                 compressed = numarg("compress level", 1L, 9L);
461                         break;
462 #endif /* HAVE_ZLIB */
463
464                 default:
465                         usage();
466                 }
467         argc -= optind;
468         argv += optind;
469
470         if (argc < 1) {
471                 msg("Must specify disk or filesystem\n");
472                 msg("The ENTIRE dump is aborted.\n");
473                 exit(X_STARTUP);
474         }
475         diskparam = *argv++;
476         if (strlen(diskparam) >= MAXPATHLEN) {
477                 msg("Disk or filesystem name too long: %s\n", diskparam);
478                 msg("The ENTIRE dump is aborted.\n");
479                 exit(X_STARTUP);
480         }
481         argc--;
482         incompat_flags(Tflag && uflag, 'T', 'u');
483         incompat_flags(aflag && blocksperfiles, 'a', 'B');
484         incompat_flags(aflag && cartridge, 'a', 'c');
485         incompat_flags(aflag && density, 'a', 'd');
486         incompat_flags(aflag && tsize, 'a', 's');
487
488         if (strcmp(tapeprefix, "-") == 0) {
489                 pipeout++;
490                 tapeprefix = "standard output";
491         }
492
493         if (blocksperfiles && !compressed)
494                 for (i = 1; i <= *blocksperfiles; i++)
495                         blocksperfiles[i] = blocksperfiles[i] / ntrec * ntrec; /* round down */
496         else if (!unlimited) {
497                 /*
498                  * Determine how to default tape size and density
499                  *
500                  *              density                         tape size
501                  * 9-track      1600 bpi (160 bytes/.1")        2300 ft.
502                  * 9-track      6250 bpi (625 bytes/.1")        2300 ft.
503                  * cartridge    8000 bpi (100 bytes/.1")        1700 ft.
504                  *                                              (450*4 - slop)
505                  * hilit19 hits again: "
506                  */
507                 if (density == 0)
508                         density = cartridge ? 100 : 160;
509                 if (tsize == 0)
510                         tsize = cartridge ? 1700L*120L : 2300L*120L;
511         }
512
513         {
514                 int i;
515                 char *n;
516
517                 if ((n = strchr(tapeprefix, ':'))) {
518                         for (i = 0; i < (n - tapeprefix); i++) {
519                                 if (tapeprefix[i] == '/')
520                                         break;
521                         }
522                         if (tapeprefix[i] != '/') {
523                                 host = tapeprefix;
524                                 tapeprefix = strchr(host, ':');
525                                 *tapeprefix++ = '\0';
526 #ifdef RDUMP
527                                 if (index(tapeprefix, '\n')) {
528                                         msg("invalid characters in tape\n");
529                                         msg("The ENTIRE dump is aborted.\n");
530                                         exit(X_STARTUP);
531                                 }
532                                 if (rmthost(host) == 0)
533                                         exit(X_STARTUP);
534 #else
535                                 msg("remote dump not enabled\n");
536                                 msg("The ENTIRE dump is aborted.\n");
537                                 exit(X_STARTUP);
538 #endif
539                         }
540                 }
541         }
542
543         (void)setuid(getuid()); /* rmthost() is the only reason to be setuid */
544         if (Apath && (Afile = open(Apath, O_WRONLY|O_CREAT|O_TRUNC,
545                                    S_IRUSR | S_IWUSR | S_IRGRP |
546                                    S_IWGRP | S_IROTH | S_IWOTH)) < 0) {
547                 msg("Cannot open %s for writing: %s\n",
548                     optarg, strerror(errno));
549                 msg("The ENTIRE dump is aborted.\n");
550                 exit(X_STARTUP);
551         }
552
553         if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
554                 signal(SIGHUP, sig);
555         if (signal(SIGTRAP, SIG_IGN) != SIG_IGN)
556                 signal(SIGTRAP, sig);
557         if (signal(SIGFPE, SIG_IGN) != SIG_IGN)
558                 signal(SIGFPE, sig);
559         if (signal(SIGBUS, SIG_IGN) != SIG_IGN)
560                 signal(SIGBUS, sig);
561         if (signal(SIGSEGV, SIG_IGN) != SIG_IGN)
562                 signal(SIGSEGV, sig);
563         if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
564                 signal(SIGTERM, sig);
565         if (signal(SIGINT, interrupt) == SIG_IGN)
566                 signal(SIGINT, SIG_IGN);
567 #ifdef SIGXCPU
568         signal(SIGXCPU, SIG_IGN);
569 #endif /* SIGXCPU */
570 #ifdef SIGXFSZ
571         signal(SIGXFSZ, SIG_IGN);
572 #endif /* SIGXFSZ */
573
574         set_operators();        /* /etc/group snarfed */
575         getfstab();             /* /etc/fstab snarfed */
576
577         /*
578          *      disk may end in / and this can confuse
579          *      fstabsearch.
580          */
581         i = strlen(diskparam) - 1;
582         if (i > 1 && diskparam[i] == '/')
583                 if (!(i == 6 && !strcmp(diskparam, "LABEL=/")))
584                         diskparam[i] = '\0';
585
586         disk = get_device_name(diskparam);
587         if (!disk) {            /* null means the disk is some form
588                                    of LABEL= or UID= but it was not
589                                    found */
590                 msg("Cannot find a disk having %s\n", diskparam);
591                 msg("The ENTIRE dump is aborted.\n");
592                 exit(X_STARTUP);
593         }
594         /*
595          *      disk can be either the full special file name,
596          *      the suffix of the special file name,
597          *      the special name missing the leading '/',
598          *      the file system name with or without the leading '/'.
599          */
600         if ((dt = fstabsearch(disk)) != NULL) {
601                 /* if found then only one parameter (i.e. partition)
602                  * is allowed */
603                 if (argc >= 1) {
604                         (void)fprintf(stderr, "Unknown arguments to dump:");
605                         while (argc--)
606                                 (void)fprintf(stderr, " %s", *argv++);
607                         (void)fprintf(stderr, "\n");
608                         msg("The ENTIRE dump is aborted.\n");
609                         exit(X_STARTUP);
610                 }
611                 disk = rawname(dt->mnt_fsname);
612                 (void)strncpy(spcl.c_dev, dt->mnt_fsname, NAMELEN);
613                 (void)strncpy(spcl.c_filesys, dt->mnt_dir, NAMELEN);
614         } else {
615 #ifdef  __linux__
616 #ifdef  HAVE_REALPATH
617                 if (realpath(disk, pathname) == NULL)
618 #endif
619                         strcpy(pathname, disk);
620                 /*
621                  * The argument could be now a mountpoint of
622                  * a filesystem specified in fstab. Search for it.
623                  */
624                 if ((dt = fstabsearch(pathname)) != NULL) {
625                         disk = rawname(dt->mnt_fsname);
626                         (void)strncpy(spcl.c_dev, dt->mnt_fsname, NAMELEN);
627                         (void)strncpy(spcl.c_filesys, dt->mnt_dir, NAMELEN);
628                 } else {
629                         /*
630                          * The argument was not found in the fstab
631                          * assume that this is a subtree and search for it
632                          */
633                         dt = fstabsearchdir(pathname, directory);
634                         if (dt != NULL) {
635                                 char name[MAXPATHLEN];
636                                 (void)strncpy(spcl.c_dev, dt->mnt_fsname, NAMELEN);
637                                 (void)snprintf(name, sizeof(name), "%s (dir %s)",
638                                               dt->mnt_dir, directory);
639                                 (void)strncpy(spcl.c_filesys, name, NAMELEN);
640                                 disk = rawname(dt->mnt_fsname);
641                         } else {
642                                 (void)strncpy(spcl.c_dev, disk, NAMELEN);
643                                 (void)strncpy(spcl.c_filesys, "an unlisted file system",
644                                     NAMELEN);
645                         }
646                 }
647 #else
648                 (void)strncpy(spcl.c_dev, disk, NAMELEN);
649                 (void)strncpy(spcl.c_filesys, "an unlisted file system",
650                     NAMELEN);
651 #endif
652         }
653
654         if (directory[0] != 0) {
655                 if (atoi(level) != 0) {
656                         msg("Only level 0 dumps are allowed on a subdirectory\n");
657                         msg("The ENTIRE dump is aborted.\n");
658                         exit(X_STARTUP);
659                 }
660                 if (uflag) {
661                         msg("You can't update the dumpdates file when dumping a subdirectory\n");
662                         msg("The ENTIRE dump is aborted.\n");
663                         exit(X_STARTUP);
664                 }
665         }
666         spcl.c_dev[NAMELEN-1] = '\0';
667         spcl.c_filesys[NAMELEN-1] = '\0';
668         (void)gethostname(spcl.c_host, NAMELEN);
669         spcl.c_host[NAMELEN-1] = '\0';
670         spcl.c_level = atoi(level);
671         spcl.c_type = TS_TAPE;
672         if (!Tflag)
673                 getdumptime(uflag);             /* dumpdates snarfed */
674
675         if (spcl.c_ddate == 0 && spcl.c_level) {
676                 msg("WARNING: There is no inferior level dump on this filesystem\n"); 
677                 msg("WARNING: Assuming a level 0 dump by default\n");
678                 level[0] = '0'; level[1] = '\0';
679                 spcl.c_level = 0;
680         }
681
682         if (Mflag)
683                 snprintf(tape, MAXPATHLEN, "%s%03d", tapeprefix, tapeno + 1);
684         else
685                 strncpy(tape, tapeprefix, MAXPATHLEN);
686         tape[MAXPATHLEN - 1] = '\0';
687
688         if (!pipeout) {
689                 if (STAT(tape, &statbuf) != -1)
690                         fifoout= statbuf.st_mode & S_IFIFO;
691         }
692
693         if (!sizest) {
694
695                 msg("Date of this level %s dump: %s", level,
696                     ctime4(&spcl.c_date));
697 #ifdef USE_QFA
698                 gThisDumpDate = spcl.c_date;
699 #endif
700                 if (spcl.c_ddate)
701                         msg("Date of last level %s dump: %s", lastlevel,
702                             ctime4(&spcl.c_ddate));
703                 msg("Dumping %s (%s) ", disk, spcl.c_filesys);
704                 if (host)
705                         msgtail("to %s on host %s\n", tape, host);
706                 else
707                         msgtail("to %s\n", tape);
708         } /* end of size estimate */
709
710 #ifdef  __linux__
711         if ((diskfd = OPEN(disk, O_RDONLY)) < 0) {
712                 msg("Cannot open %s\n", disk);
713                 msg("The ENTIRE dump is aborted.\n");
714                 exit(X_STARTUP);
715         }
716 #ifdef BLKFLSBUF
717         (void)ioctl(diskfd, BLKFLSBUF, 0);
718 #endif
719         retval = dump_fs_open(disk, &fs);
720         if (retval) {
721                 com_err(disk, retval, "while opening filesystem");
722                 if (retval == EXT2_ET_REV_TOO_HIGH)
723                         msg("Get a newer version of dump!\n");
724                 msg("The ENTIRE dump is aborted.\n");
725                 exit(X_STARTUP);
726         }
727         if (fs->super->s_rev_level > DUMP_CURRENT_REV) {
728                 com_err(disk, retval, "while opening filesystem");
729                 msg("Get a newer version of dump!\n");
730                 msg("The ENTIRE dump is aborted.\n");
731                 exit(X_STARTUP);
732         }
733         /* if no user label specified, use ext2 filesystem label if available */
734         if (spcl.c_label[0] == '\0') {
735                 const char *lbl;
736                 if ( (lbl = get_device_label(disk)) != NULL) {
737                         strncpy(spcl.c_label, lbl, LBLSIZE);
738                         spcl.c_label[LBLSIZE-1] = '\0';
739                 }
740                 else
741                         strcpy(spcl.c_label, "none");   /* safe strcpy. */
742         }
743         sync();
744         dev_bsize = DEV_BSIZE;
745         dev_bshift = ffs(dev_bsize) - 1;
746         if (dev_bsize != (1 << dev_bshift))
747                 quit("dev_bsize (%d) is not a power of 2", dev_bsize);
748         tp_bshift = ffs(TP_BSIZE) - 1;
749         if (TP_BSIZE != (1 << tp_bshift))
750                 quit("TP_BSIZE (%d) is not a power of 2", TP_BSIZE);
751         maxino = fs->super->s_inodes_count + 1;
752         spcl.c_flags |= DR_NEWINODEFMT;
753 #else   /* __linux __*/
754         if ((diskfd = open(disk, O_RDONLY)) < 0) {
755                 msg("Cannot open %s\n", disk);
756                 msg("The ENTIRE dump is aborted.\n");
757                 exit(X_STARTUP);
758         }
759         sync();
760         sblock = (struct fs *)sblock_buf;
761         bread(SBOFF, (char *) sblock, SBSIZE);
762         if (sblock->fs_magic != FS_MAGIC)
763                 quit("bad sblock magic number\n");
764         dev_bsize = sblock->fs_fsize / fsbtodb(sblock, 1);
765         dev_bshift = ffs(dev_bsize) - 1;
766         if (dev_bsize != (1 << dev_bshift))
767                 quit("dev_bsize (%d) is not a power of 2", dev_bsize);
768         tp_bshift = ffs(TP_BSIZE) - 1;
769         if (TP_BSIZE != (1 << tp_bshift))
770                 quit("TP_BSIZE (%d) is not a power of 2", TP_BSIZE);
771 #ifdef FS_44INODEFMT
772         if (sblock->fs_inodefmt >= FS_44INODEFMT)
773                 spcl.c_flags |= DR_NEWINODEFMT;
774 #endif
775         maxino = sblock->fs_ipg * sblock->fs_ncg;
776 #endif  /* __linux__ */
777         mapsize = roundup(howmany(maxino, NBBY), TP_BSIZE);
778         usedinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
779         dumpdirmap = (char *)calloc((unsigned) mapsize, sizeof(char));
780         dumpinomap = (char *)calloc((unsigned) mapsize, sizeof(char));
781         metainomap = (char *)calloc((unsigned) mapsize, sizeof(char));
782         if (usedinomap == NULL || dumpdirmap == NULL || 
783             dumpinomap == NULL || metainomap == NULL)
784                 quit("out of memory allocating inode maps\n");
785         tapesize = 2 * (howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
786
787         nonodump = spcl.c_level < honorlevel;
788
789         if (!sizest) {
790                 msg("Label: %s\n", spcl.c_label);
791                 
792                 msg("Writing %d Kilobyte records\n", ntrec);
793
794                 if (compressed) {
795                         if (zipflag == COMPRESS_LZO) 
796                                 msg("Compressing output (lzo)\n");
797                         else
798                                 msg("Compressing output at compression level %d (%s)\n", 
799                                         compressed, zipflag == COMPRESS_ZLIB ? "zlib" : "bzlib");
800                 }
801         }
802
803 #if defined(SIGINFO)
804         (void)signal(SIGINFO, statussig);
805 #endif
806
807         if (!sizest)
808                 msg("mapping (Pass I) [regular files]\n");
809 #ifdef  __linux__
810         if (directory[0] == 0)
811                 anydirskipped = mapfiles(maxino, &tapesize);
812         else {
813                 if (LSTAT(pathname, &statbuf) == -1) {
814                         msg("File cannot be accessed (%s).\n", pathname);
815                         msg("The ENTIRE dump is aborted.\n");
816                         exit(X_STARTUP);
817                 }
818                 filedev = statbuf.st_dev;
819                 if (!(statbuf.st_mode & S_IFDIR))       /* is a file */
820                         anydirskipped = maponefile(maxino, &tapesize, 
821                                                    directory);
822                 else
823                         anydirskipped = mapfilesfromdir(maxino, &tapesize, 
824                                                         directory);
825         }
826         while (argc--) {
827                 int anydirskipped2;
828                 char *p = *argv;
829                 /* check if file is available */
830                 if (LSTAT(p, &statbuf) == -1) {
831                         msg("File cannot be accessed (%s).\n", p);
832                         msg("The ENTIRE dump is aborted.\n");
833                         exit(X_STARTUP);
834                 }
835                 /* check if file is on same unix partiton as the first 
836                  * argument */
837                 if (statbuf.st_dev != filedev) {
838                         msg("Files are not on same file system (%s).\n", p);
839                         msg("The ENTIRE dump is aborted.\n");
840                         exit(X_STARTUP);
841                 }
842                 /* check if file is a directory */
843                 if (!(statbuf.st_mode & S_IFDIR))
844                         anydirskipped2 = maponefile(maxino, &tapesize, 
845                                                     p+strlen(dt->mnt_dir));
846                 else
847                         /* read directory inodes.
848                          * NOTE: nested directories are not recognized 
849                          * so inodes may be umped twice!
850                          */
851                         anydirskipped2 = mapfilesfromdir(maxino, &tapesize, 
852                                                          p+strlen(dt->mnt_dir));
853                 if (!anydirskipped)
854                         anydirskipped = anydirskipped2;
855                 argv++;
856         }               
857 #else
858         anydirskipped = mapfiles(maxino, &tapesize);
859 #endif
860
861         if (!sizest)
862                 msg("mapping (Pass II) [directories]\n");
863         while (anydirskipped) {
864                 anydirskipped = mapdirs(maxino, &tapesize);
865         }
866
867         if (sizest) {
868                 printf("%.0f\n", ((double)tapesize + 1 + ntrec) * TP_BSIZE);
869                 exit(X_FINOK);
870         } /* stop here for size estimate */
871
872         if (pipeout || unlimited) {
873                 tapesize += 1 + ntrec;  /* 1 map header + trailer blocks */
874                 msg("estimated %ld blocks.\n", tapesize);
875         } else {
876                 double fetapes;
877
878                 if (blocksperfiles) {
879                         long tapesize_left;
880
881                         tapesize_left = tapesize;
882                         fetapes = 0;
883                         for (i = 1; i < *blocksperfiles && tapesize_left; i++) {
884                                 fetapes++;
885                                 if (tapesize_left > blocksperfiles[i])
886                                         tapesize_left -= blocksperfiles[i];
887                                 else
888                                         tapesize_left = 0;
889                         }
890                         if (tapesize_left)
891                                 fetapes += (double)tapesize_left / blocksperfiles[*blocksperfiles];
892                 } else if (cartridge) {
893                         /* Estimate number of tapes, assuming streaming stops at
894                            the end of each block written, and not in mid-block.
895                            Assume no erroneous blocks; this can be compensated
896                            for with an artificially low tape size. */
897                         fetapes =
898                         (         (double) tapesize     /* blocks */
899                                 * TP_BSIZE      /* bytes/block */
900                                 * (1.0/density) /* 0.1" / byte " */
901                           +
902                                   (double) tapesize     /* blocks */
903                                 * (1.0/ntrec)   /* streaming-stops per block */
904                                 * 15.48         /* 0.1" / streaming-stop " */
905                         ) * (1.0 / tsize );     /* tape / 0.1" " */
906                 } else {
907                         /* Estimate number of tapes, for old fashioned 9-track
908                            tape */
909                         int tenthsperirg = (density == 625) ? 3 : 7;
910                         fetapes =
911                         (         (double) tapesize     /* blocks */
912                                 * TP_BSIZE      /* bytes / block */
913                                 * (1.0/density) /* 0.1" / byte " */
914                           +
915                                   (double) tapesize     /* blocks */
916                                 * (1.0/ntrec)   /* IRG's / block */
917                                 * tenthsperirg  /* 0.1" / IRG " */
918                         ) * (1.0 / tsize );     /* tape / 0.1" " */
919                 }
920                 etapes = fetapes;               /* truncating assignment */
921                 etapes++;
922                 /* count the dumped inodes map on each additional tape */
923                 tapesize += (etapes - 1) *
924                         (howmany(mapsize * sizeof(char), TP_BSIZE) + 1);
925                 tapesize += etapes + ntrec;     /* headers + trailer blks */
926                 msg("estimated %ld blocks on %3.2f tape(s).\n",
927                     tapesize, fetapes);
928         }
929
930 #ifdef USE_QFA
931         if (tapepos) {
932                 msg("writing QFA positions to %s\n", gTapeposfile);
933                 if ((gTapeposfd = open(gTapeposfile,
934                                        O_WRONLY|O_CREAT|O_TRUNC,
935                                        S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP
936                                        | S_IROTH | S_IWOTH)) < 0)
937                         quit("can't open tapeposfile\n");
938                 /* print QFA-file header */
939                 snprintf(gTps, sizeof(gTps), "%s\n%s\n%ld\n\n", QFA_MAGIC, QFA_VERSION, (unsigned long)spcl.c_date);
940                 gTps[sizeof(gTps) - 1] = '\0';
941                 if (write(gTapeposfd, gTps, strlen(gTps)) != (ssize_t)strlen(gTps))
942                         quit("can't write tapeposfile\n");
943                 sprintf(gTps, "ino\ttapeno\ttapepos\n");
944                 if (write(gTapeposfd, gTps, strlen(gTps)) != (ssize_t)strlen(gTps))
945                         quit("can't write tapeposfile\n");
946         }
947 #endif /* USE_QFA */
948
949         /*
950          * Allocate tape buffer.
951          */
952         if (!alloctape())
953                 quit(
954         "can't allocate tape buffers - try a smaller blocking factor.\n");
955
956         startnewtape(1);
957         tstart_writing = time(NULL);
958         dumpmap(usedinomap, TS_CLRI, maxino - 1);
959
960         msg("dumping (Pass III) [directories]\n");
961         dirty = 0;              /* XXX just to get gcc to shut up */
962         for (map = dumpdirmap, ino = 1; ino < maxino; ino++) {
963                 if (((ino - 1) % NBBY) == 0)    /* map is offset by 1 */
964                         dirty = *map++;
965                 else
966                         dirty >>= 1;
967                 if ((dirty & 1) == 0)
968                         continue;
969                 /*
970                  * Skip directory inodes deleted and maybe reallocated
971                  */
972                 dp = getino(ino);
973                 if ((dp->di_mode & IFMT) != IFDIR)
974                         continue;
975 #ifdef  __linux__
976                 /*
977                  * Skip directory inodes deleted and not yes reallocated...
978                  */
979                 if (dp->di_nlink == 0 || dp->di_dtime != 0)
980                         continue;
981                 if (vflag)
982                         msg("dumping directory inode %lu\n", ino);
983                 (void)dumpdirino(dp, ino);
984 #else
985                 (void)dumpino(dp, ino);
986 #endif
987         }
988
989         msg("dumping (Pass IV) [regular files]\n");
990         for (map = dumpinomap, ino = 1; ino < maxino; ino++) {
991                 if (((ino - 1) % NBBY) == 0)    /* map is offset by 1 */
992                         dirty = *map++;
993                 else
994                         dirty >>= 1;
995                 if ((dirty & 1) == 0)
996                         continue;
997                 /*
998                  * Skip inodes deleted and reallocated as directories.
999                  */
1000                 dp = getino(ino);
1001                 if ((dp->di_mode & IFMT) == IFDIR)
1002                         continue;
1003 #ifdef __linux__
1004                 /*
1005                  * No need to check here for deleted and not yet reallocated
1006                  * inodes since this is done in dumpino().
1007                  */
1008 #endif
1009                 if (vflag) {
1010                         if (mflag && TSTINO(ino, metainomap))
1011                                 msg("dumping regular inode %lu (meta only)\n", ino);
1012                         else
1013                                 msg("dumping regular inode %lu\n", ino);
1014                 }
1015                 (void)dumpino(dp, ino, mflag && TSTINO(ino, metainomap));
1016         }
1017
1018         tend_writing = time(NULL);
1019         spcl.c_type = TS_END;
1020
1021         if (Afile >= 0) {
1022                 volinfo[1] = ROOTINO;
1023                 memcpy(spcl.c_inos, volinfo, TP_NINOS * sizeof(dump_ino_t));
1024                 spcl.c_flags |= DR_INODEINFO;
1025         }
1026
1027         /*
1028          * Finish off the current tape record with trailer blocks, to ensure
1029          * at least the data in the last partial record makes it to tape.
1030          * Also make sure we write at least 1 trailer block.
1031          */
1032         for (i = ntrec - (spcl.c_tapea % ntrec); i; --i)
1033                 writeheader(maxino - 1);
1034
1035         tnow = trewind();
1036
1037         if (pipeout || fifoout)
1038                 msg("%ld blocks (%.2fMB)\n", spcl.c_tapea,
1039                         ((double)spcl.c_tapea * TP_BSIZE / 1048576));
1040         else
1041                 msg("%ld blocks (%.2fMB) on %d volume(s)\n",
1042                     spcl.c_tapea, 
1043                     ((double)spcl.c_tapea * TP_BSIZE / 1048576),
1044                     spcl.c_volume);
1045
1046         /* report dump performance, avoid division by zero */
1047         if (tend_writing - tstart_writing == 0)
1048                 msg("finished in less than a second\n");
1049         else
1050                 msg("finished in %d seconds, throughput %d kBytes/sec\n",
1051                     tend_writing - tstart_writing,
1052                     spcl.c_tapea / (tend_writing - tstart_writing));
1053
1054         putdumptime();
1055         msg("Date of this level %s dump: %s", level,
1056                 spcl.c_date == 0 ? "the epoch\n" : ctime4(&spcl.c_date));
1057         msg("Date this dump completed:  %s", ctime(&tnow));
1058
1059         msg("Average transfer rate: %ld kB/s\n", xferrate / tapeno);
1060         if (compressed) {
1061                 long tapekb = bytes_written / 1024;
1062                 double rate = .0005 + (double) spcl.c_tapea / tapekb;
1063                 msg("Wrote %ldkB uncompressed, %ldkB compressed, %1.3f:1\n",
1064                         spcl.c_tapea, tapekb, rate);
1065         }
1066
1067         if (Afile >= 0)
1068                 msg("Archiving dump to %s\n", Apath);
1069
1070         broadcast("DUMP IS DONE!\7\7\n");
1071         msg("DUMP IS DONE\n");
1072         Exit(X_FINOK);
1073         /* NOTREACHED */
1074         return 0;       /* gcc - shut up */
1075 }
1076
1077 static void
1078 usage(void)
1079 {
1080         char white[MAXPATHLEN];
1081         const char *ext2ver, *ext2date;
1082
1083         memset(white, ' ', MAXPATHLEN);
1084         white[MIN(strlen(__progname), MAXPATHLEN - 1)] = '\0';
1085
1086 #ifdef __linux__
1087         ext2fs_get_library_version(&ext2ver, &ext2date);
1088         fprintf(stderr, "%s %s (using libext2fs %s of %s)\n",
1089                 __progname, _DUMP_VERSION, ext2ver, ext2date);
1090 #else
1091         fprintf(stderr, "%s %s\n", __progname, _DUMP_VERSION);
1092 #endif
1093         fprintf(stderr,
1094                 "usage:\t%s [-level#] [-ac"
1095 #ifdef KERBEROS
1096                 "k"
1097 #endif
1098                 "mMnqSuv"
1099                 "] [-A file] [-B records] [-b blocksize]\n"
1100                 "\t%s [-d density] [-D file] [-e inode#,inode#,...] [-E file]\n"
1101                 "\t%s [-f file] [-h level] [-I nr errors] "
1102 #ifdef HAVE_BZLIB
1103                 "[-j zlevel] "
1104 #endif
1105 #ifdef USE_QFA
1106                 "[-Q file]\n"
1107 #endif
1108                 "\t%s [-s feet] "
1109                 "[-T date] "
1110 #ifdef HAVE_LZO
1111                 "[-y] "
1112 #endif
1113 #ifdef HAVE_ZLIB
1114                 "[-z zlevel] "
1115 #endif
1116                 "filesystem\n"
1117                 "\t%s [-W | -w]\n", 
1118                 __progname, white, white, white, __progname);
1119         exit(X_STARTUP);
1120 }
1121
1122 /*
1123  * Pick up a numeric argument.  It must be nonnegative and in the given
1124  * range (except that a vmax of 0 means unlimited).
1125  */
1126 static long
1127 numarg(const char *meaning, long vmin, long vmax)
1128 {
1129         char *p;
1130         long val;
1131
1132         val = strtol(optarg, &p, 10);
1133         if (*p)
1134                 errx(X_STARTUP, "illegal %s -- %s", meaning, optarg);
1135         if (val < vmin || (vmax && val > vmax))
1136                 errx(X_STARTUP, "%s must be between %ld and %ld", meaning, vmin, vmax);
1137         return (val);
1138 }
1139
1140 /*
1141  * The same as numarg, just that it expects a comma separated list of numbers
1142  * and returns an array of longs with the first element containing the number
1143  * values in that array.
1144  */
1145 static long *
1146 numlistarg(const char *meaning, long vmin, long vmax)
1147 {
1148         char *p;
1149         long *vals,*curval;
1150         long valnum;
1151
1152         p = optarg;
1153         vals = NULL;
1154         valnum = 0;
1155         do {
1156                 valnum++;
1157                 if ( !(vals = realloc(vals, (valnum + 1) * sizeof(*vals))) )
1158                         errx(X_STARTUP, "allocating memory failed");
1159                 curval = vals + valnum;
1160                 *curval = strtol(p, &p, 10);
1161                 if (*p && *p!=',')
1162                         errx(X_STARTUP, "illegal %s -- %s", meaning, optarg);
1163                 if (*curval < vmin || (vmax && *curval > vmax))
1164                         errx(X_STARTUP, "%s must be between %ld and %ld", meaning, vmin, vmax);
1165                 *vals = valnum;
1166                 if (*p) p++;
1167         } while(*p);
1168         return (vals);
1169 }
1170
1171 void
1172 sig(int signo)
1173 {
1174         switch(signo) {
1175         case SIGALRM:
1176         case SIGBUS:
1177         case SIGFPE:
1178         case SIGHUP:
1179         case SIGTERM:
1180         case SIGTRAP:
1181                 if (pipeout || fifoout)
1182                         quit("Signal on pipe: cannot recover\n");
1183                 msg("Rewriting attempted as response to unknown signal: %d.\n", signo);
1184                 (void)fflush(stderr);
1185                 (void)fflush(stdout);
1186                 close_rewind();
1187                 exit(X_REWRITE);
1188                 /* NOTREACHED */
1189         case SIGSEGV:
1190                 msg("SIGSEGV: ABORTING!\n");
1191                 (void)signal(SIGSEGV, SIG_DFL);
1192                 (void)kill(0, SIGSEGV);
1193                 /* NOTREACHED */
1194         }
1195 }
1196
1197 const char *
1198 rawname(const char *cp)
1199 {
1200 #ifdef  __linux__
1201         return cp;
1202 #else   /* __linux__ */
1203         static char rawbuf[MAXPATHLEN];
1204         char *dp = strrchr(cp, '/');
1205
1206         if (dp == NULL)
1207                 return (NULL);
1208         (void)strncpy(rawbuf, cp, min(dp-cp, MAXPATHLEN - 1));
1209         rawbuf[min(dp-cp, MAXPATHLEN-1)] = '\0';
1210         (void)strncat(rawbuf, "/r", MAXPATHLEN - 1 - strlen(rawbuf));
1211         (void)strncat(rawbuf, dp + 1, MAXPATHLEN - 1 - strlen(rawbuf));
1212         return (rawbuf);
1213 #endif  /* __linux__ */
1214 }
1215
1216 /*
1217  * obsolete --
1218  *      Change set of key letters and ordered arguments into something
1219  *      getopt(3) will like.
1220  */
1221 static void
1222 obsolete(int *argcp, char **argvp[])
1223 {
1224         int argc, flags;
1225         char *ap, **argv, *flagsp=NULL, **nargv, *p=NULL;
1226
1227         /* Setup. */
1228         argv = *argvp;
1229         argc = *argcp;
1230
1231         /* Return if no arguments or first argument has leading dash. */
1232         ap = argv[1];
1233         if (argc == 1 || *ap == '-')
1234                 return;
1235
1236         /* Allocate space for new arguments. */
1237         if ((*argvp = nargv = malloc((argc + 1) * sizeof(char *))) == NULL ||
1238             (p = flagsp = malloc(strlen(ap) + 2)) == NULL)
1239                 err(X_STARTUP, "malloc new args");
1240
1241         *nargv++ = *argv;
1242         argv += 2;
1243
1244         for (flags = 0; *ap; ++ap) {
1245                 switch (*ap) {
1246                 case 'A':
1247                 case 'B':
1248                 case 'b':
1249                 case 'd':
1250                 case 'D':
1251                 case 'e':
1252                 case 'E':
1253                 case 'f':
1254                 case 'F':
1255                 case 'h':
1256                 case 'L':
1257                 case 'Q':
1258                 case 's':
1259                 case 'T':
1260                         if (*argv == NULL) {
1261                                 warnx("option requires an argument -- %c", *ap);
1262                                 usage();
1263                         }
1264                         if ((nargv[0] = malloc(strlen(*argv) + 2 + 1)) == NULL)
1265                                 err(X_STARTUP, "malloc arg");
1266                         nargv[0][0] = '-';
1267                         nargv[0][1] = *ap;
1268                         (void)strcpy(&nargv[0][2], *argv);
1269                         ++argv;
1270                         ++nargv;
1271                         break;
1272                 default:
1273                         if (!flags) {
1274                                 *p++ = '-';
1275                                 flags = 1;
1276                         }
1277                         *p++ = *ap;
1278                         break;
1279                 }
1280         }
1281
1282         /* Terminate flags. */
1283         if (flags) {
1284                 *p = '\0';
1285                 *nargv++ = flagsp;
1286         }
1287
1288         /* Copy remaining arguments. */
1289         while ((*nargv++ = *argv++));
1290
1291         /* Update argument count. */
1292         *argcp = nargv - *argvp - 1;
1293 }
1294
1295 /*
1296  * This tests whether an inode is in the exclude bitmap
1297  */
1298 int
1299 exclude_ino(dump_ino_t ino)
1300 {
1301         /* if the inode exclude bitmap exists and covers given inode */
1302         if (iexclude_bitmap && iexclude_bitmap_bytes > ino / 8) {
1303                 /* then check this inode against it */
1304                 int idx = iexclude_bitmap[ino / 8];
1305                 if (idx & (1 << (ino % 8)))
1306                         return 1;
1307         }
1308         return 0;
1309 }
1310
1311 /*
1312  * This adds an inode to the exclusion bitmap if it isn't already there
1313  */
1314 void
1315 do_exclude_ino(dump_ino_t ino, const char *reason)
1316 {
1317         if (exclude_ino(ino))
1318                 return;
1319
1320         if (vflag) {
1321                 if (reason)
1322                         msg("Excluding inode %u (%s) from dump\n", ino, reason);
1323                 else
1324                         msg("Excluding inode %u from dump\n", ino);
1325         }
1326
1327         /* check for enough mem; initialize */
1328         if ((ino/8 + 1) > iexclude_bitmap_bytes) {
1329                 if (iexclude_bitmap_bytes == 0) {
1330                         unsigned int j;
1331                         iexclude_bitmap_bytes = 2 * (ino/8 + 1);
1332                         iexclude_bitmap = (char*) malloc(iexclude_bitmap_bytes);
1333                         if (iexclude_bitmap == NULL) {
1334                                 msg("allocating memory failed\n");
1335                                 exit(X_STARTUP);
1336                         }
1337                         for (j = 0; j < iexclude_bitmap_bytes; j++)
1338                                 iexclude_bitmap[j] = 0;
1339                 }
1340                 else {
1341                         unsigned int oldsize = iexclude_bitmap_bytes;
1342                         iexclude_bitmap_bytes *= 
1343                                 (ino / 8 + 1) / iexclude_bitmap_bytes + 1;
1344                         iexclude_bitmap = (char*) realloc(iexclude_bitmap, 
1345                                 iexclude_bitmap_bytes);
1346                         if (iexclude_bitmap == NULL) {
1347                                 msg("allocating memory failed\n");
1348                                 exit(X_STARTUP);
1349                         }
1350                         for( ; oldsize < iexclude_bitmap_bytes; oldsize++)
1351                                 iexclude_bitmap[oldsize] = 0;
1352                 }
1353         }
1354                 
1355         iexclude_bitmap[ino / 8] |= 1 << (ino % 8);
1356 }
1357
1358 static void
1359 do_exclude_ino_str(char * ino) {
1360         char *r;
1361         unsigned long inod;
1362
1363         inod = strtoul(ino, &r, 10);
1364         if (( *r != '\0' && !isspace(*r) ) || inod <= ROOTINO) {
1365                 msg("Invalid inode argument %s\n", ino);
1366                 msg("The ENTIRE dump is aborted.\n");
1367                 exit(X_STARTUP);
1368         }
1369         do_exclude_ino(inod, NULL);
1370 }
1371
1372 /*
1373  * This reads a file containing one inode number per line and exclude them all
1374  */
1375 static void 
1376 do_exclude_from_file(char *file) {
1377         FILE *f;
1378         char *p, fname[MAXPATHLEN];
1379         
1380
1381         if (!( f = fopen(file, "r")) ) {
1382                 msg("Cannot open file for reading: %s\n", file);
1383                 msg("The ENTIRE dump is aborted.\n");
1384                 exit(X_STARTUP);
1385         }
1386         while (( p = fgets(fname, MAXPATHLEN, f))) {
1387                 if ( *p && *(p + strlen(p) - 1) == '\n' ) /* possible null string */
1388                         *(p + strlen(p) - 1) = '\0';
1389                 if ( !*p ) /* skip empty lines */
1390                         continue;
1391                 do_exclude_ino_str(p);
1392         }
1393         fclose(f);
1394 }
1395
1396 static void incompat_flags(int cond, char flag1, char flag2) {
1397         if (cond) {
1398                 msg("You cannot use the %c and %c flags together.\n", 
1399                     flag1, flag2);
1400                 msg("The ENTIRE dump is aborted.\n");
1401                 exit(X_STARTUP);
1402         }
1403 }