2 * tar - `tape archiver', actually usable on any medium.
3 * POSIX "ustar" compliant when extracting, and by default when creating.
4 * this tar attempts to read and write multiple Tblock-byte blocks
5 * at once to and from the filesystem, and does not copy blocks
12 #include <fcall.h> /* for %M */
16 * modified versions of those in libc.h; scans only the first arg for
17 * keyletters and options.
20 (argv0 || (argv0 = *argv)), argv++, argc--;\
26 while(*_args && (_args += chartorune(&_argc, _args)))\
28 #define TARGEND SET(_argt); USED(_argt);USED(_argc);USED(_args); \
30 USED(argv); USED(argc); }
31 #define TARGC() (_argc)
33 #define ROUNDUP(a, b) (((a) + (b) - 1)/(b))
34 #define BYTES2TBLKS(bytes) ROUNDUP(bytes, Tblock)
36 /* read big-endian binary integers; args must be (uchar *) */
37 #define G2BEBYTE(x) (((x)[0]<<8) | (x)[1])
38 #define G3BEBYTE(x) (((x)[0]<<16) | ((x)[1]<<8) | (x)[2])
39 #define G4BEBYTE(x) (((x)[0]<<24) | ((x)[1]<<16) | ((x)[2]<<8) | (x)[3])
40 #define G8BEBYTE(x) (((vlong)G4BEBYTE(x)<<32) | (u32int)G4BEBYTE((x)+4))
43 typedef char *(*Refill)(int ar, char *bufs, int justhdr);
45 enum { Stdin, Stdout, Stderr };
46 enum { Rd, Wr }; /* pipe fd-array indices */
47 enum { Output, Input };
48 enum { None, Toc, Xtract, Replace };
49 enum { Alldata, Justnxthdr };
53 Maxpfx = 155, /* from POSIX */
54 Maxname = Namsiz + 1 + Maxpfx,
56 Binsize = 0x80, /* flag in size[0], from gnu: positive binary size */
57 Binnegsz = 0xff, /* flag in size[0]: negative binary size */
59 Nblock = 40, /* maximum blocksize */
60 Dblock = 20, /* default blocksize */
64 /* POSIX link flags */
70 LF_SYMLINK2 = 's', /* 4BSD used this */
77 /* 'A' - 'Z' are reserved for custom implementations */
79 LF_LONGNAME = 'L', /* GNU extenstion */
81 LF_PAXHDR = 'x', /* PAX header */
85 #define islink(lf) (isreallink(lf) || issymlink(lf))
86 #define isreallink(lf) ((lf) == LF_LINK)
87 #define issymlink(lf) ((lf) == LF_SYMLINK1 || (lf) == LF_SYMLINK2)
100 char linkname[Namsiz];
102 /* rest are defined by POSIX's ustar format; see p1003.2b */
103 char magic[6]; /* "ustar" */
109 char prefix[Maxpfx]; /* if non-null, path= prefix "/" name */
129 static Compress comps[] = {
130 "gzip", "gunzip", { ".tar.gz", ".tgz" }, /* default */
131 "compress", "uncompress", { ".tar.Z", ".tz" },
132 "bzip2", "bunzip2", { ".tar.bz", ".tbz",
133 ".tar.bz2",".tbz2" },
138 int fd; /* original fd */
139 int rfd; /* replacement fd */
144 #define OTHER(rdwr) ((rdwr) == Rd? Wr: Rd)
146 static int fixednblock;
148 static int posix = 1;
152 static int relative = 1;
155 static int docompress;
156 static int keepexisting;
157 static int ignerrs; /* flag: ignore i/o errors if possible */
158 static Off blkoff; /* offset of the current archive block (not Tblock) */
161 static int nblock = Dblock;
163 static char *usefile, *arname = "archive";
164 static char origdir[Maxlongname+1];
165 static Blk *tpblk, *endblk;
172 fprint(2, "usage: %s {crtx}[PRTfgikmpsuvz] [archive] [file1 file2...]\n",
177 /* I/O, with error retry or exit */
180 cope(char *name, int fd, void *buf, long len, Off off)
182 fprint(2, "%s: %serror reading %s: %r\n", argv0,
183 (ignerrs? "ignoring ": ""), name);
187 /* pretend we read len bytes of zeroes */
189 if (off >= 0) /* seekable? */
190 seek(fd, off + len, 0);
195 eread(char *name, int fd, void *buf, long len)
200 off = seek(fd, 0, 1); /* for coping with errors */
201 rd = read(fd, buf, len);
203 rd = cope(name, fd, buf, len, off);
208 ereadn(char *name, int fd, void *buf, long len)
213 off = seek(fd, 0, 1);
214 rd = readn(fd, buf, len);
216 rd = cope(name, fd, buf, len, off);
221 ewrite(char *name, int fd, void *buf, long len)
226 rd = write(fd, buf, len);
228 sysfatal("error writing %s: %r", name);
235 compmethod(char *name)
238 int i, nmlen, sfxlen;
241 nmlen = strlen(name);
242 for (cp = comps; cp < comps + nelem(comps); cp++) {
243 for (i = 0; i < nelem(cp->sfx) && cp->sfx[i]; i++) {
244 sfxlen = strlen(cp->sfx[i]);
245 if (nmlen > sfxlen &&
246 strcmp(cp->sfx[i], name + nmlen - sfxlen) == 0)
251 return docompress? comps: nil;
255 * push a filter, cmd, onto fd. if input, it's an input descriptor.
256 * returns a descriptor to replace fd, or -1 on error.
259 push(int fd, char *cmd, int input, Pushstate *ps)
267 if (fd < 0 || pipe(pifds) < 0)
275 dup(pifds[Wr], Stdout);
277 dup(pifds[Rd], Stdin);
278 close(pifds[input? Rd: Wr]);
279 dup(fd, (input? Stdin: Stdout));
282 s_append(s, "/bin/");
284 execl(s_to_c(s), cmd, nil);
285 sysfatal("can't exec %s: %r", cmd);
287 nfd = pifds[input? Rd: Wr];
288 close(pifds[input? Wr: Rd]);
297 pushclose(Pushstate *ps)
301 if (ps->fd < 0 || ps->rfd < 0 || !ps->open)
306 while ((wm = wait()) != nil && wm->pid != ps->kid)
308 return wm? wm->msg: nil;
312 * block-buffer management
319 tpblk = malloc(Tblock * nblock);
320 assert(tpblk != nil);
321 endblk = tpblk + nblock;
325 * (re)fill block buffers from archive. `justhdr' means we don't care
326 * about the data before the next header block.
329 refill(int ar, char *bufs, int justhdr)
332 unsigned bytes = Tblock * nblock;
333 static int done, first = 1, seekable;
338 blkoff = seek(ar, 0, 1); /* note position for `tar r' */
340 seekable = blkoff >= 0;
341 /* try to size non-pipe input at first read */
342 if (first && usefile && !fixednblock) {
343 n = eread(arname, ar, bufs, bytes);
345 sysfatal("EOF reading archive %s: %r", arname);
348 sysfatal("%s: archive block size (%d) error", arname, i);
352 fprint(2, "%s: blocking = %d\n", argv0, nblock);
353 endblk = (Blk *)bufs + nblock;
356 } else if (justhdr && seekable && nexthdr - blkoff >= bytes) {
357 /* optimisation for huge archive members on seekable media */
358 if (seek(ar, bytes, 1) < 0)
359 sysfatal("can't seek on archive %s: %r", arname);
362 n = ereadn(arname, ar, bufs, bytes);
366 sysfatal("unexpected EOF reading archive %s", arname);
368 sysfatal("partial block read from archive %s", arname);
371 memset(bufs + n, 0, bytes - n);
377 getblk(int ar, Refill rfp, int justhdr)
379 if (curblk == nil || curblk >= endblk) { /* input block exhausted? */
380 if (rfp != nil && (*rfp)(ar, (char *)tpblk, justhdr) == nil)
388 getblkrd(int ar, int justhdr)
390 return getblk(ar, refill, justhdr);
396 return getblk(ar, nil, Alldata);
402 Blk *bp = getblke(ar);
405 memset(bp->data, 0, Tblock);
410 * how many block buffers are available, starting at the address
411 * just returned by getblk*?
416 int n = endblk - (curblk - 1);
418 return n > max? max: n;
422 * indicate that one is done with the last block obtained from getblke
423 * and it is now available to be written into the archive.
428 unsigned bytes = Tblock * nblock;
430 /* if writing end-of-archive, aid compression (good hygiene too) */
432 memset(curblk, 0, (char *)endblk - (char *)curblk);
433 ewrite(arname, ar, tpblk, bytes);
439 if (curblk >= endblk)
451 putreadblks(int ar, int blks)
458 putblkmany(int ar, int blks)
470 * modifies hp->chksum but restores it; important for the last block of the
471 * old archive when updating with `tar rf archive'
478 uchar *cp = bp->data;
479 char oldsum[sizeof bp->chksum];
481 memmove(oldsum, bp->chksum, sizeof oldsum);
482 memset(bp->chksum, ' ', sizeof bp->chksum);
485 memmove(bp->chksum, oldsum, sizeof oldsum);
492 return strcmp(bp->magic, "ustar") == 0;
496 * s is at most n bytes long, but need not be NUL-terminated.
497 * if shorter than n bytes, all bytes after the first NUL must also
501 strnlen(char *s, int n)
503 return s[n - 1] != '\0'? n: strlen(s);
506 /* set fullname from header */
508 parsename(Blk *bp, char *buf, int nbuf)
512 namlen = strnlen(bp->name, sizeof bp->name);
513 if (bp->prefix[0] == '\0' || !isustar(bp)) { /* old-style name? */
514 assert(nbuf > namlen);
515 memmove(buf, bp->name, namlen);
520 /* name is in two pieces */
521 pfxlen = strnlen(bp->prefix, sizeof bp->prefix);
522 assert(nbuf > pfxlen + 1 + namlen);
523 memmove(buf, bp->prefix, pfxlen);
525 memmove(buf + pfxlen + 1, bp->name, namlen);
526 buf[pfxlen + 1 + namlen] = '\0';
531 isdir(Blk *bp, char *name)
533 /* the mode test is ugly but sometimes necessary */
534 return bp->linkflag == LF_DIR ||
535 strrchr(name, '\0')[-1] == '/' ||
536 (strtoul(bp->mode, nil, 8)&0170000) == 040000;
542 char buf[Maxname + 1];
543 return parsename(bp, buf, sizeof(buf))[0] == '\0';
548 getbe(uchar *src, int size)
561 putbe(uchar *dest, uvlong vl, int size)
563 for (dest += size; size-- > 0; vl >>= 8)
568 * cautious parsing of octal numbers as ascii strings in
569 * a tar header block. this is particularly important for
570 * trusting the checksum when trying to resync.
573 hdrotoull(char *st, char *end, uvlong errval, char *name, char *field)
577 for (numb = st; (*numb == ' ' || *numb == '\0') && numb < end; numb++)
579 if (numb < end && isascii(*numb) && isdigit(*numb))
580 return strtoull(numb, nil, 8);
581 else if (numb >= end)
582 fprint(2, "%s: %s: empty %s in header\n", argv0, name, field);
584 fprint(2, "%s: %s: %s: non-numeric %s in header\n",
585 argv0, name, numb, field);
590 * return the nominal size from the header block, which is not always the
591 * size in the archive (the archive size may be zero for some file types
592 * regardless of the nominal size).
594 * gnu and freebsd tars are now recording vlongs as big-endian binary
595 * with a flag in byte 0 to indicate this, which permits file sizes up to
596 * 2^64-1 (actually 2^80-1 but our file sizes are vlongs) rather than 2^33-1.
602 char buf[Maxname + 1];
604 if((uchar)bp->size[0] == Binnegsz) {
605 fprint(2, "%s: %s: negative length, which is insane\n",
606 argv0, parsename(bp, buf, sizeof(buf)));
608 } else if((uchar)bp->size[0] == Binsize) {
609 p = (uchar *)bp->size + sizeof bp->size - 1 -
610 sizeof(vlong); /* -1 for terminating space */
614 return hdrotoull(bp->size, bp->size + sizeof bp->size, 0,
615 parsename(bp, buf, sizeof(buf)), "size");
619 * return the number of bytes recorded in the archive.
622 arsize(Blk *bp, char *fname)
624 if(isdir(bp, fname) || islink(bp->linkflag))
630 parsecksum(char *cksum, char *name)
634 return hdrotoull(cksum, cksum + sizeof bp->chksum, (uvlong)-1LL,
641 char buf[Maxname + 1];
645 bp = getblkrd(ar, Alldata);
647 sysfatal("unexpected EOF instead of archive header in %s",
649 if (eotar(bp)) /* end-of-archive block? */
652 hdrcksum = parsecksum(bp->chksum, parsename(bp, buf, sizeof(buf)));
653 if (hdrcksum == -1 || chksum(bp) != hdrcksum) {
655 sysfatal("bad archive header checksum in %s: "
656 "name %.100s...; expected %#luo got %#luo",
657 arname, bp->name, hdrcksum, chksum(bp));
658 fprint(2, "%s: skipping past archive header with bad checksum in %s...",
661 bp = getblkrd(ar, Alldata);
663 sysfatal("unexpected EOF looking for archive header in %s",
665 hdrcksum = parsecksum(bp->chksum, parsename(bp, buf, sizeof(buf)));
666 } while (hdrcksum == -1 || chksum(bp) != hdrcksum);
667 fprint(2, "found %s\n", parsename(bp, buf, sizeof(buf)));
669 nexthdr += Tblock*(1 + BYTES2TBLKS(hdrsize(bp)));
675 getname(int ar, Blk *bp, Hdr *hdr)
677 char buf[Maxlongname+1];
678 ulong blksleft, blksread;
682 if (bp->linkflag != LF_LONGNAME){
683 /* PAX attributes take precedence */
685 hdr->name = strdup(parsename(bp, buf, sizeof(buf)));
690 for (blksleft = BYTES2TBLKS(hdrsize(bp)); blksleft > 0; blksleft -= blksread) {
691 bp = getblkrd(ar, Alldata);
693 sysfatal("unexpected EOF on archive reading from %s", arname);
694 blksread = gothowmany(blksleft);
695 n = &buf[Maxlongname] - p;
696 if(Tblock*blksread < n)
698 memmove(p, bp->data, n);
702 hdr->name = strdup(buf);
707 matchattr(char *kvp, char *k)
709 if (strncmp(kvp, k, strlen(k)) == 0)
710 return kvp + strlen(k);
715 parsepax(int ar, Blk *bp, Hdr *hdr, int paxtype)
717 char *p, *lp, *le, *e, *kvp, *val, lenbuf[16];
722 if (!isustar(bp) || bp->linkflag != paxtype)
728 le = lenbuf + sizeof(lenbuf);
729 for (blksleft = BYTES2TBLKS(hdrsize(bp)); blksleft > 0; ) {
730 b = getblkrd(ar, Alldata);
732 sysfatal("unexpected EOF on archive reading attr for %s from %s", bp->name, arname);
734 e = (char *)b->data + sizeof(b->data);
739 * Copy out the length prefix. This may span a block boundary, so be
740 * careful about when we get the next block. The length prefix includes
741 * both its own length and the trailing newline. We want to trim the
742 * length prefix, since we already consumed it.
745 while(p != e && *p >= '0' && *p <= '9'){
747 sysfatal("oversize length prefix in pax header");
750 if (p == e && blksleft > 0)
753 sysfatal("invalid delimiter in pax header: %c (%s)\n", *p, p);
755 len = atoi(lenbuf) - strlen(lenbuf) - 1;
758 if (kvp == nil && (kvp = malloc(len)) == nil)
759 sysfatal("out of memory: %r");
760 n = (len - off > e - p) ? e - p : len - off;
761 memcpy(kvp + off, p, n);
767 if ((val = matchattr(kvp, "path=")) != nil) {
769 hdr->name = strdup(val);
770 } else if ((val = matchattr(kvp, "linkpath=")) != nil) {
771 /* Mostly for better error messages. */
773 hdr->name = strdup(val);
774 } else if ((val = matchattr(kvp, "uname=")) != nil) {
776 hdr->uid = strdup(val);
777 } else if ((val = matchattr(kvp, "gname=")) != nil) {
779 hdr->gid = strdup(val);
780 } else if ((val = matchattr(kvp, "atime=")) != nil)
781 hdr->atime = strtoll(val, nil, 0);
782 else if ((val = matchattr(kvp, "mtime=")) != nil)
783 hdr->mtime = strtoll(val, nil, 0);
784 else if ((val = matchattr(kvp, "size=")) != nil)
785 hdr->size = strtoll(val, nil, 0);
787 if (matchattr(kvp, "comment=") == nil && matchattr(kvp, "ctime=") == nil)
788 fprint(2, "warning: pax attribute not supported: %s\n", kvp);
803 parsehdr(Hdr *hdr, Blk *bp)
809 hdr->mode = (strtoul(bp->mode, nil, 8) & 0777);
811 hdr->mode = globlhdr.mode;
812 if (isdir(bp, hdr->name))
814 if (hdr->atime == -1)
816 if (hdr->atime == -1)
817 hdr->atime = globlhdr.atime;
818 if (hdr->mtime == -1)
819 hdr->mtime = strtol(bp->mtime, nil, 8);
820 if (hdr->mtime == -1)
821 hdr->mtime = globlhdr.mtime;
823 hdr->size = arsize(bp, hdr->name);
824 if (ustar && hdr->uid == nil)
825 hdr->uid = strdup(bp->uname);
827 hdr->uid = (globlhdr.uid != nil) ? strdup(globlhdr.uid) : nil;
828 if (ustar && hdr->gid == nil)
829 hdr->gid = strdup(bp->uname);
831 hdr->gid = (globlhdr.gid != nil) ? strdup(globlhdr.gid) : nil;
848 readhdr(int ar, Hdr *hdr)
854 if ((bp = readhdrblk(ar)) == nil)
856 if (parsepax(ar, bp, hdr, LF_PAXHDR))
858 if (parsepax(ar, bp, &globlhdr, LF_PAXGLOBL))
860 if (getname(ar, bp, hdr))
862 if (parsehdr(hdr, bp) == -1)
863 sysfatal("could not parse header: %r");
877 * if name is longer than Namsiz bytes, try to split it at a slash and fit the
878 * pieces into bp->prefix and bp->name.
881 putfullname(Blk *bp, char *name)
885 String *slname = nil;
887 if (isdir(bp, name)) {
889 s_append(slname, name);
890 s_append(slname, "/"); /* posix requires this */
891 name = s_to_c(slname);
894 namlen = strlen(name);
895 if (namlen <= Namsiz) {
896 strncpy(bp->name, name, Namsiz);
897 bp->prefix[0] = '\0'; /* ustar paranoia */
901 if (!posix || namlen > Maxname) {
902 fprint(2, "%s: name too long for tar header: %s\n",
907 * try various splits until one results in pieces that fit into the
908 * appropriate fields of the header. look for slashes from right
909 * to left, in the hopes of putting the largest part of the name into
910 * bp->prefix, which is larger than bp->name.
912 sl = strrchr(name, '/');
915 if (pfxlen <= sizeof bp->prefix && namlen-1 - pfxlen <= Namsiz)
919 sl = strrchr(name, '/');
923 fprint(2, "%s: name can't be split to fit tar header: %s\n",
928 strncpy(bp->prefix, name, sizeof bp->prefix);
930 strncpy(bp->name, sl, sizeof bp->name);
937 mkhdr(Blk *bp, Dir *dir, char *file)
942 * some of these fields run together, so we format them left-to-right
943 * and don't use snprint.
945 sprint(bp->mode, "%6lo ", dir->mode & 0777);
946 sprint(bp->uid, "%6o ", aruid);
947 sprint(bp->gid, "%6o ", argid);
948 if (dir->length >= (Off)1<<32) {
953 fprint(2, "%s: storing large sizes in \"base 256\"\n", argv0);
955 bp->size[0] = Binsize;
956 /* emit so-called `base 256' representation of size */
957 putbe((uchar *)bp->size+1, dir->length, sizeof bp->size - 2);
958 bp->size[sizeof bp->size - 1] = ' ';
960 sprint(bp->size, "%11lluo ", dir->length);
961 sprint(bp->mtime, "%11luo ", dir->mtime);
962 bp->linkflag = (dir->mode&DMDIR? LF_DIR: LF_PLAIN1);
963 r = putfullname(bp, file);
965 strncpy(bp->magic, "ustar", sizeof bp->magic);
966 strncpy(bp->version, "00", sizeof bp->version);
967 strncpy(bp->uname, dir->uid, sizeof bp->uname);
968 strncpy(bp->gname, dir->gid, sizeof bp->gname);
970 sprint(bp->chksum, "%6luo", chksum(bp));
974 static void addtoar(int ar, char *file, char *shortf);
977 addtreetoar(int ar, char *file, char *shortf, int fd)
981 String *name = s_new();
983 n = dirreadall(fd, &dirents);
985 fprint(2, "%s: dirreadall %s: %r\n", argv0, file);
990 if (chdir(shortf) < 0)
991 sysfatal("chdir %s: %r", file);
993 fprint(2, "chdir %s\t# %s\n", shortf, file);
995 for (dent = dirents; dent < dirents + n; dent++) {
997 s_append(name, file);
999 s_append(name, dent->name);
1000 addtoar(ar, s_to_c(name), dent->name);
1006 * this assumes that shortf is just one component, which is true
1007 * during directory descent, but not necessarily true of command-line
1008 * arguments. Our caller (or addtoar's) must reset the working
1009 * directory if necessary.
1011 if (chdir("..") < 0)
1012 sysfatal("chdir %s/..: %r", file);
1014 fprint(2, "chdir ..\n");
1018 addtoar(int ar, char *file, char *shortf)
1021 long bytes, blksread;
1027 if (shortf[0] == '#') {
1029 s_append(name, "./");
1030 s_append(name, shortf);
1031 shortf = s_to_c(name);
1035 fprint(2, "opening %s # %s\n", shortf, file);
1036 fd = open(shortf, OREAD);
1038 fprint(2, "%s: can't open %s: %r\n", argv0, file);
1045 sysfatal("can't fstat %s: %r", file);
1048 isdir = (dir->qid.type & QTDIR) != 0;
1049 if (mkhdr(hbp, dir, file) < 0) {
1059 blksleft = BYTES2TBLKS(dir->length);
1063 addtreetoar(ar, file, shortf, fd);
1065 for (; blksleft > 0; blksleft -= blksread) {
1067 blksread = gothowmany(blksleft);
1068 assert(blksread >= 0);
1069 bytes = blksread * Tblock;
1070 n = ereadn(file, fd, hbp->data, bytes);
1073 * ignore EOF. zero any partial block to aid
1074 * compression and emergency recovery of data.
1077 memset(hbp->data + n, 0, bytes - n);
1078 putblkmany(ar, blksread);
1082 fprint(2, "%s\n", file);
1089 replace(char **argv)
1092 ulong blksleft, blksread;
1095 Compress *comp = nil;
1098 if (usefile && docreate)
1099 ar = create(usefile, OWRITE, 0666);
1101 ar = open(usefile, ORDWR);
1104 if (docreate && docompress) {
1105 comp = compmethod(usefile);
1107 ar = push(ar, comp->comp, Output, &ps);
1110 sysfatal("can't open archive %s: %r", usefile);
1112 if (usefile && !docreate) {
1113 /* skip quickly to the end */
1114 while ((bp = readhdrblk(ar)) != nil) {
1115 bytes = hdrsize(bp);
1116 for (blksleft = BYTES2TBLKS(bytes);
1117 blksleft > 0 && getblkrd(ar, Justnxthdr) != nil;
1118 blksleft -= blksread) {
1119 blksread = gothowmany(blksleft);
1120 putreadblks(ar, blksread);
1124 * we have just read the end-of-archive Tblock.
1125 * now seek back over the (big) archive block containing it,
1126 * and back up curblk ptr over end-of-archive Tblock in memory.
1128 if (seek(ar, blkoff, 0) < 0)
1129 sysfatal("can't seek back over end-of-archive in %s: %r",
1134 for (i = 0; argv[i] != nil; i++) {
1135 addtoar(ar, argv[i], argv[i]);
1136 chdir(origdir); /* for correctness & profiling */
1139 /* write end-of-archive marker */
1146 return pushclose(&ps);
1156 /* is pfx a file-name prefix of name? */
1158 prefix(char *name, char *pfx)
1160 char clpfx[Maxlongname+1];
1161 int pfxlen = strlen(pfx);
1163 clpfx[Maxlongname] = '\0';
1164 strncpy(clpfx, pfx, Maxlongname);
1166 return strncmp(clpfx, name, pfxlen) == 0 &&
1167 (name[pfxlen] == '\0' || name[pfxlen] == '/');
1171 match(char *name, char **argv)
1173 char clname[Maxlongname+1];
1178 clname[Maxlongname] = '\0';
1179 strncpy(clname, name, Maxlongname);
1181 for (i = 0; argv[i] != nil; i++)
1182 if (prefix(clname, argv[i]))
1188 cantcreate(char *s, int mode)
1194 * Always print about files. Only print about directories
1195 * we haven't printed about. (Assumes archive is ordered
1200 /* already printed this directory */
1201 if(strcmp(s, last) == 0)
1203 /* printed a higher directory, so printed this one */
1205 if(memcmp(s, last, len) == 0 && last[len] == '/')
1212 fprint(2, "%s: can't create %s: %r\n", argv0, s);
1220 if (access(s, AEXIST) == 0)
1222 f = create(s, OREAD, DMDIR | 0777);
1226 cantcreate(s, DMDIR);
1238 while (!err && (p = strchr(p+1, '/')) != nil) {
1240 err = (access(s, AEXIST) < 0 && makedir(s) < 0);
1246 /* Call access but preserve the error string. */
1248 xaccess(char *name, int mode)
1254 errstr(err, sizeof err);
1255 rv = access(name, mode);
1256 errstr(err, sizeof err);
1261 openfname(Blk *bp, char *fname, int mode)
1268 switch (bp->linkflag) {
1273 fprint(2, "%s: can't make (sym)link %s\n",
1277 fprint(2, "%s: can't make fifo %s\n", argv0, fname);
1280 if (!keepexisting || access(fname, AEXIST) < 0) {
1281 int rw = (dir ? OREAD: OWRITE);
1283 fd = create(fname, rw, mode);
1286 fd = create(fname, rw, mode);
1288 if (fd < 0 && (!dir || xaccess(fname, AEXIST) < 0))
1289 cantcreate(fname, mode);
1291 if (fd >= 0 && verbose)
1292 fprint(2, "%s\n", fname);
1298 /* copy from archive to file system (or nowhere for table-of-contents) */
1300 copyfromar(int ar, int fd, char *fname, ulong blksleft, Off bytes)
1306 if (blksleft == 0 || bytes < 0)
1308 for (; blksleft > 0; blksleft -= blksread) {
1309 hbp = getblkrd(ar, (fd >= 0? Alldata: Justnxthdr));
1311 sysfatal("unexpected EOF on archive extracting %s from %s",
1313 blksread = gothowmany(blksleft);
1314 if (blksread <= 0) {
1315 fprint(2, "%s: got %ld blocks reading %s!\n",
1316 argv0, blksread, fname);
1319 wrbytes = Tblock*blksread;
1323 assert(wrbytes >= 0);
1325 ewrite(fname, fd, hbp->data, wrbytes);
1326 putreadblks(ar, blksread);
1331 fprint(2, "%s: %lld bytes uncopied at EOF on archive %s; "
1332 "%s not fully extracted\n", argv0, bytes, arname, fname);
1336 wrmeta(int fd, Hdr *hdr) /* update metadata */
1341 nd.mtime = hdr->mtime;
1342 nd.mode = hdr->mode;
1357 * copy a file from the archive into the filesystem.
1358 * fname is result of getname(), so has two extra bytes at beginning.
1361 extract1(int ar, Blk *bp, Hdr *hdr)
1364 Off bytes = hdr->size; /* for printing */
1365 uvlong blksleft = BYTES2TBLKS(bytes);
1368 /* fiddle name, figure out mode and blocks */
1369 switch (bp->linkflag) {
1377 if((path = malloc(strlen(hdr->name) + 3)) == nil)
1378 sysfatal("malloc: %r");
1379 if (relative && hdr->name[0] == '/')
1381 else if(relative && hdr->name[0] == '#')
1385 strcat(path, hdr->name);
1388 fd = openfname(bp, path, hdr->mode);
1390 char *cp = ctime(hdr->mtime);
1392 print("%M %8lld %-12.12s %-4.4s %s\n",
1393 hdr->mode, bytes, cp+4, cp+24, path);
1395 print("%s\n", path);
1397 copyfromar(ar, fd, path, blksleft, hdr->size);
1399 /* touch up meta data and close */
1402 * directories should be wstated *after* we're done
1403 * creating files in them, but we don't do that.
1413 skip(int ar, Blk *bp, Hdr *hdr)
1415 ulong blksleft, blksread;
1418 for (blksleft = BYTES2TBLKS(arsize(bp, hdr->name)); blksleft > 0;
1419 blksleft -= blksread) {
1420 hbp = getblkrd(ar, Justnxthdr);
1422 sysfatal("unexpected EOF on archive extracting %s from %s",
1424 blksread = gothowmany(blksleft);
1425 putreadblks(ar, blksread);
1430 extract(char **argv)
1439 ar = open(usefile, OREAD);
1442 comp = compmethod(usefile);
1444 ar = push(ar, comp->decomp, Input, &ps);
1446 sysfatal("can't open archive %s: %r", usefile);
1448 while ((bp = readhdr(ar, &hdr)) != nil) {
1449 if (match(hdr.name, argv))
1450 extract1(ar, bp, &hdr);
1457 return pushclose(&ps);
1464 main(int argc, char *argv[])
1469 fmtinstall('M', dirmodefmt);
1477 usefile = arname = EARGF(usage());
1480 argid = strtoul(EARGF(usage()), 0, 0);
1488 case 'm': /* compatibility */
1513 aruid = strtoul(EARGF(usage()), 0, 0);
1527 fprint(2, "tar: unknown letter %C\n", TARGC());
1532 if (argc < 0 || errflg)
1540 ret = extract(argv);
1543 if (getwd(origdir, sizeof origdir) == nil)
1544 strcpy(origdir, "/tmp");
1545 ret = replace(argv);