Blob


1 /*
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
6 * around internally.
7 */
9 #include <u.h>
10 #include <libc.h>
11 #include <fcall.h> /* for %M */
12 #include <libString.h>
14 /*
15 * modified versions of those in libc.h; scans only the first arg for
16 * keyletters and options.
17 */
18 #define TARGBEGIN {\
19 if (argv0 == nil)\
20 argv0 = *argv;\
21 argv++, argc--;\
22 if (argv[0]) {\
23 char *_args, *_argt;\
24 Rune _argc;\
25 _args = &argv[0][0];\
26 _argc = 0;\
27 while(*_args && (_args += chartorune(&_argc, _args)))\
28 switch(_argc)
29 #define TARGEND SET(_argt); USED(_argt);USED(_argc);USED(_args); \
30 argc--, argv++; } \
31 USED(argv); USED(argc); }
32 #define TARGC() (_argc)
34 #define ROUNDUP(a, b) (((a) + (b) - 1)/(b))
35 #define BYTES2TBLKS(bytes) ROUNDUP(bytes, Tblock)
37 typedef vlong Off;
38 typedef char *(*Refill)(int ar, char *bufs, int justhdr);
40 enum { Stdin, Stdout, Stderr };
41 enum { Rd, Wr }; /* pipe fd-array indices */
42 enum { Output, Input };
43 enum { None, Toc, Xtract, Replace };
44 enum { Alldata, Justnxthdr };
45 enum {
46 Tblock = 512,
47 Nblock = 40, /* maximum blocksize */
48 Dblock = 20, /* default blocksize */
49 Namsiz = 100,
50 Maxpfx = 155, /* from POSIX */
51 Maxname = Namsiz + 1 + Maxpfx,
52 DEBUG = 0,
53 };
55 /* POSIX link flags */
56 enum {
57 LF_PLAIN1 = '\0',
58 LF_PLAIN2 = '0',
59 LF_LINK = '1',
60 LF_SYMLINK1 = '2',
61 LF_SYMLINK2 = 's',
62 LF_CHR = '3',
63 LF_BLK = '4',
64 LF_DIR = '5',
65 LF_FIFO = '6',
66 LF_CONTIG = '7',
67 /* 'A' - 'Z' are reserved for custom implementations */
68 };
70 #define islink(lf) (isreallink(lf) || issymlink(lf))
71 #define isreallink(lf) ((lf) == LF_LINK)
72 #define issymlink(lf) ((lf) == LF_SYMLINK1 || (lf) == LF_SYMLINK2)
74 typedef struct {
75 char name[Namsiz];
76 char mode[8];
77 char uid[8];
78 char gid[8];
79 char size[12];
80 char mtime[12];
81 char chksum[8];
82 char linkflag;
83 char linkname[Namsiz];
85 /* rest are defined by POSIX's ustar format; see p1003.2b */
86 char magic[6]; /* "ustar" */
87 char version[2];
88 char uname[32];
89 char gname[32];
90 char devmajor[8];
91 char devminor[8];
92 char prefix[Maxpfx]; /* if non-null, path= prefix "/" name */
93 } Hdr;
95 typedef struct {
96 char *comp;
97 char *decomp;
98 char *sfx[4];
99 } Compress;
101 static Compress comps[] = {
102 "gzip", "gunzip", { ".tar.gz", ".tgz" }, /* default */
103 "compress", "uncompress", { ".tar.Z", ".tz" },
104 "bzip2", "bunzip2", { ".tar.bz", ".tbz",
105 ".tar.bz2",".tbz2" },
106 };
108 typedef struct {
109 int kid;
110 int fd; /* original fd */
111 int rfd; /* replacement fd */
112 int input;
113 int open;
114 } Pushstate;
116 #define OTHER(rdwr) (rdwr == Rd? Wr: Rd)
118 /* static int debug; */
119 static int verb;
120 static int posix = 1;
121 static int docreate;
122 static int aruid;
123 static int argid;
124 static int relative = 1;
125 static int settime;
126 static int verbose;
127 static int docompress;
128 static int keepexisting;
129 static Off blkoff; /* offset of the current archive block (not Tblock) */
130 static Off nexthdr;
132 static int nblock = Dblock;
133 static char *usefile;
134 static char origdir[Maxname*2];
135 static Hdr *tpblk, *endblk;
136 static Hdr *curblk;
138 static void
139 usage(void)
141 fprint(2, "usage: %s {crtx}[PRTfgkmpuvz] [archive] file1 file2...\n",
142 argv0);
143 exits("usage");
146 /* compression */
148 static Compress *
149 compmethod(char *name)
151 int i, nmlen = strlen(name), sfxlen;
152 Compress *cp;
154 for (cp = comps; cp < comps + nelem(comps); cp++)
155 for (i = 0; i < nelem(cp->sfx) && cp->sfx[i]; i++) {
156 sfxlen = strlen(cp->sfx[i]);
157 if (nmlen > sfxlen &&
158 strcmp(cp->sfx[i], name + nmlen - sfxlen) == 0)
159 return cp;
161 return docompress? comps: nil;
164 /*
165 * push a filter, cmd, onto fd. if input, it's an input descriptor.
166 * returns a descriptor to replace fd, or -1 on error.
167 */
168 static int
169 push(int fd, char *cmd, int input, Pushstate *ps)
171 int nfd, pifds[2];
172 String *s;
174 ps->open = 0;
175 ps->fd = fd;
176 ps->input = input;
177 if (fd < 0 || pipe(pifds) < 0)
178 return -1;
179 ps->kid = fork();
180 switch (ps->kid) {
181 case -1:
182 return -1;
183 case 0:
184 if (input)
185 dup(pifds[Wr], Stdout);
186 else
187 dup(pifds[Rd], Stdin);
188 close(pifds[input? Rd: Wr]);
189 dup(fd, (input? Stdin: Stdout));
190 s = s_new();
191 if (cmd[0] != '/')
192 s_append(s, "/bin/");
193 s_append(s, cmd);
194 execl(s_to_c(s), cmd, nil);
195 sysfatal("can't exec %s: %r", cmd);
196 default:
197 nfd = pifds[input? Rd: Wr];
198 close(pifds[input? Wr: Rd]);
199 break;
201 ps->rfd = nfd;
202 ps->open = 1;
203 return nfd;
206 static char *
207 pushclose(Pushstate *ps)
209 Waitmsg *wm;
211 if (ps->fd < 0 || ps->rfd < 0 || !ps->open)
212 return "not open";
213 close(ps->rfd);
214 ps->rfd = -1;
215 ps->open = 0;
216 while ((wm = wait()) != nil && wm->pid != ps->kid)
217 continue;
218 return wm? wm->msg: nil;
221 /*
222 * block-buffer management
223 */
225 static void
226 initblks(void)
228 free(tpblk);
229 tpblk = malloc(Tblock * nblock);
230 assert(tpblk != nil);
231 endblk = tpblk + nblock;
234 /*
235 * (re)fill block buffers from archive. `justhdr' means we don't care
236 * about the data before the next header block.
237 */
238 static char *
239 refill(int ar, char *bufs, int justhdr)
241 int i, n;
242 unsigned bytes = Tblock * nblock;
243 static int done, first = 1, seekable;
245 if (done)
246 return nil;
248 if (first)
249 seekable = seek(ar, 0, 1) >= 0;
250 /* try to size non-pipe input at first read */
251 if (first && usefile) {
252 blkoff = seek(ar, 0, 1); /* note position */
253 n = read(ar, bufs, bytes);
254 if (n <= 0)
255 sysfatal("error reading archive: %r");
256 i = n;
257 if (i % Tblock != 0) {
258 fprint(2, "%s: archive block size (%d) error\n",
259 argv0, i);
260 exits("blocksize");
262 i /= Tblock;
263 if (i != nblock) {
264 nblock = i;
265 fprint(2, "%s: blocking = %d\n", argv0, nblock);
266 endblk = (Hdr *)bufs + nblock;
267 bytes = n;
269 } else if (justhdr && seekable && nexthdr - seek(ar, 0, 1) >= bytes) {
270 /* optimisation for huge archive members on seekable media */
271 if (seek(ar, bytes, 1) < 0)
272 sysfatal("can't seek on archive: %r");
273 n = bytes;
274 } else
275 n = readn(ar, bufs, bytes);
276 first = 0;
278 if (n == 0)
279 sysfatal("unexpected EOF reading archive");
280 else if (n < 0)
281 sysfatal("error reading archive: %r");
282 else if (n%Tblock != 0)
283 sysfatal("partial block read from archive");
284 if (n != bytes) {
285 done = 1;
286 memset(bufs + n, 0, bytes - n);
288 return bufs;
291 static Hdr *
292 getblk(int ar, Refill rfp, int justhdr)
294 if (curblk == nil || curblk >= endblk) { /* input block exhausted? */
295 if (rfp != nil && (*rfp)(ar, (char *)tpblk, justhdr) == nil)
296 return nil;
297 curblk = tpblk;
299 return curblk++;
302 static Hdr *
303 getblkrd(int ar, int justhdr)
305 return getblk(ar, refill, justhdr);
308 static Hdr *
309 getblke(int ar)
311 return getblk(ar, nil, Alldata);
314 static Hdr *
315 getblkz(int ar)
317 Hdr *hp = getblke(ar);
319 if (hp != nil)
320 memset(hp, 0, Tblock);
321 return hp;
324 /*
325 * how many block buffers are available, starting at the address
326 * just returned by getblk*?
327 */
328 static int
329 gothowmany(int max)
331 int n = endblk - (curblk - 1);
333 return n > max? max: n;
336 /*
337 * indicate that one is done with the last block obtained from getblke
338 * and it is now available to be written into the archive.
339 */
340 static void
341 putlastblk(int ar)
343 unsigned bytes = Tblock * nblock;
345 /* if writing end-of-archive, aid compression (good hygiene too) */
346 if (curblk < endblk)
347 memset(curblk, 0, (char *)endblk - (char *)curblk);
348 if (write(ar, tpblk, bytes) != bytes)
349 sysfatal("error writing archive: %r");
352 static void
353 putblk(int ar)
355 if (curblk >= endblk)
356 putlastblk(ar);
359 static void
360 putbackblk(int ar)
362 curblk--;
363 USED(ar);
366 static void
367 putreadblks(int ar, int blks)
369 curblk += blks - 1;
370 USED(ar);
373 static void
374 putblkmany(int ar, int blks)
376 curblk += blks - 1;
377 putblk(ar);
380 /*
381 * common routines
382 */
384 /*
385 * modifies hp->chksum but restores it; important for the last block of the
386 * old archive when updating with `tar rf archive'
387 */
388 long
389 chksum(Hdr *hp)
391 int n = Tblock;
392 long i = 0;
393 uchar *cp = (uchar*)hp;
394 char oldsum[sizeof hp->chksum];
396 memmove(oldsum, hp->chksum, sizeof oldsum);
397 memset(hp->chksum, ' ', sizeof hp->chksum);
398 while (n-- > 0)
399 i += *cp++;
400 memmove(hp->chksum, oldsum, sizeof oldsum);
401 return i;
404 static int
405 isustar(Hdr *hp)
407 return strcmp(hp->magic, "ustar") == 0;
410 /*
411 * s is at most n bytes long, but need not be NUL-terminated.
412 * if shorter than n bytes, all bytes after the first NUL must also
413 * be NUL.
414 */
415 static int
416 strnlen(char *s, int n)
418 return s[n - 1] != '\0'? n: strlen(s);
421 /* set fullname from header */
422 static char *
423 name(Hdr *hp)
425 int pfxlen, namlen;
426 static char fullnamebuf[2 + Maxname + 1]; /* 2 at beginning for ./ on relative names */
427 char *fullname;
429 fullname = fullnamebuf+2;
430 namlen = strnlen(hp->name, sizeof hp->name);
431 if (hp->prefix[0] == '\0' || !isustar(hp)) { /* old-style name? */
432 memmove(fullname, hp->name, namlen);
433 fullname[namlen] = '\0';
434 return fullname;
437 /* name is in two pieces */
438 pfxlen = strnlen(hp->prefix, sizeof hp->prefix);
439 memmove(fullname, hp->prefix, pfxlen);
440 fullname[pfxlen] = '/';
441 memmove(fullname + pfxlen + 1, hp->name, namlen);
442 fullname[pfxlen + 1 + namlen] = '\0';
443 return fullname;
446 static int
447 isdir(Hdr *hp)
449 /* the mode test is ugly but sometimes necessary */
450 return hp->linkflag == LF_DIR ||
451 strrchr(name(hp), '\0')[-1] == '/' ||
452 (strtoul(hp->mode, nil, 8)&0170000) == 040000;
455 static int
456 eotar(Hdr *hp)
458 return name(hp)[0] == '\0';
461 Off
462 hdrsize(Hdr *hp)
464 Off bytes = strtoull(hp->size, nil, 8);
466 if(isdir(hp))
467 bytes = 0;
468 return bytes;
471 static Hdr *
472 readhdr(int ar)
474 long hdrcksum;
475 Hdr *hp;
477 hp = getblkrd(ar, Alldata);
478 if (hp == nil)
479 sysfatal("unexpected EOF instead of archive header");
480 if (eotar(hp)) /* end-of-archive block? */
481 return nil;
482 hdrcksum = strtoul(hp->chksum, nil, 8);
483 if (chksum(hp) != hdrcksum)
484 sysfatal("bad archive header checksum: name %.64s...",
485 hp->name);
486 nexthdr += Tblock*(1 + BYTES2TBLKS(hdrsize(hp)));
487 return hp;
490 /*
491 * tar r[c]
492 */
494 /*
495 * if name is longer than Namsiz bytes, try to split it at a slash and fit the
496 * pieces into hp->prefix and hp->name.
497 */
498 static int
499 putfullname(Hdr *hp, char *name)
501 int namlen, pfxlen;
502 char *sl, *osl;
503 String *slname = nil;
505 if (isdir(hp)) {
506 slname = s_new();
507 s_append(slname, name);
508 s_append(slname, "/"); /* posix requires this */
509 name = s_to_c(slname);
512 namlen = strlen(name);
513 if (namlen <= Namsiz) {
514 strncpy(hp->name, name, Namsiz);
515 hp->prefix[0] = '\0'; /* ustar paranoia */
516 return 0;
519 if (!posix || namlen > Maxname) {
520 fprint(2, "%s: name too long for tar header: %s\n",
521 argv0, name);
522 return -1;
524 /*
525 * try various splits until one results in pieces that fit into the
526 * appropriate fields of the header. look for slashes from right
527 * to left, in the hopes of putting the largest part of the name into
528 * hp->prefix, which is larger than hp->name.
529 */
530 sl = strrchr(name, '/');
531 while (sl != nil) {
532 pfxlen = sl - name;
533 if (pfxlen <= sizeof hp->prefix && namlen-1 - pfxlen <= Namsiz)
534 break;
535 osl = sl;
536 *osl = '\0';
537 sl = strrchr(name, '/');
538 *osl = '/';
540 if (sl == nil) {
541 fprint(2, "%s: name can't be split to fit tar header: %s\n",
542 argv0, name);
543 return -1;
545 *sl = '\0';
546 strncpy(hp->prefix, name, sizeof hp->prefix);
547 *sl++ = '/';
548 strncpy(hp->name, sl, sizeof hp->name);
549 if (slname)
550 s_free(slname);
551 return 0;
554 static int
555 mkhdr(Hdr *hp, Dir *dir, char *file)
557 /*
558 * these fields run together, so we format them in order and don't use
559 * snprint.
560 */
561 sprint(hp->mode, "%6lo ", dir->mode & 0777);
562 sprint(hp->uid, "%6o ", aruid);
563 sprint(hp->gid, "%6o ", argid);
564 /*
565 * files > 2⁳⁳ bytes can't be described
566 * (unless we resort to xustar or exustar formats).
567 */
568 if (dir->length >= (Off)1<<33) {
569 fprint(2, "%s: %s: too large for tar header format\n",
570 argv0, file);
571 return -1;
573 sprint(hp->size, "%11lluo ", dir->length);
574 sprint(hp->mtime, "%11luo ", dir->mtime);
575 hp->linkflag = (dir->mode&DMDIR? LF_DIR: LF_PLAIN1);
576 putfullname(hp, file);
577 if (posix) {
578 strncpy(hp->magic, "ustar", sizeof hp->magic);
579 strncpy(hp->version, "00", sizeof hp->version);
580 strncpy(hp->uname, dir->uid, sizeof hp->uname);
581 strncpy(hp->gname, dir->gid, sizeof hp->gname);
583 sprint(hp->chksum, "%6luo", chksum(hp));
584 return 0;
587 static void addtoar(int ar, char *file, char *shortf);
589 static void
590 addtreetoar(int ar, char *file, char *shortf, int fd)
592 int n;
593 Dir *dent, *dirents;
594 String *name = s_new();
596 n = dirreadall(fd, &dirents);
597 close(fd);
598 if (n == 0)
599 return;
601 if (chdir(shortf) < 0)
602 sysfatal("chdir %s: %r", file);
603 if (DEBUG)
604 fprint(2, "chdir %s\t# %s\n", shortf, file);
606 for (dent = dirents; dent < dirents + n; dent++) {
607 s_reset(name);
608 s_append(name, file);
609 s_append(name, "/");
610 s_append(name, dent->name);
611 addtoar(ar, s_to_c(name), dent->name);
613 s_free(name);
614 free(dirents);
616 /*
617 * this assumes that shortf is just one component, which is true
618 * during directory descent, but not necessarily true of command-line
619 * arguments. Our caller (or addtoar's) must reset the working
620 * directory if necessary.
621 */
622 if (chdir("..") < 0)
623 sysfatal("chdir %s/..: %r", file);
624 if (DEBUG)
625 fprint(2, "chdir ..\n");
628 static void
629 addtoar(int ar, char *file, char *shortf)
631 int n, fd, isdir;
632 long bytes;
633 ulong blksleft, blksread;
634 Hdr *hbp;
635 Dir *dir;
637 fd = open(shortf, OREAD);
638 if (fd < 0) {
639 fprint(2, "%s: can't open %s: %r\n", argv0, file);
640 return;
642 dir = dirfstat(fd);
643 if (dir == nil)
644 sysfatal("can't fstat %s: %r", file);
646 hbp = getblkz(ar);
647 isdir = !!(dir->qid.type&QTDIR);
648 if (mkhdr(hbp, dir, file) < 0) {
649 putbackblk(ar);
650 free(dir);
651 close(fd);
652 return;
654 putblk(ar);
656 blksleft = BYTES2TBLKS(dir->length);
657 free(dir);
659 if (isdir)
660 addtreetoar(ar, file, shortf, fd);
661 else {
662 for (; blksleft > 0; blksleft -= blksread) {
663 hbp = getblke(ar);
664 blksread = gothowmany(blksleft);
665 bytes = blksread * Tblock;
666 n = readn(fd, hbp, bytes);
667 if (n < 0)
668 sysfatal("error reading %s: %r", file);
669 /*
670 * ignore EOF. zero any partial block to aid
671 * compression and emergency recovery of data.
672 */
673 if (n < Tblock)
674 memset((uchar*)hbp + n, 0, bytes - n);
675 putblkmany(ar, blksread);
677 close(fd);
678 if (verbose)
679 fprint(2, "%s\n", file);
683 static char *
684 replace(char **argv)
686 int i, ar;
687 ulong blksleft, blksread;
688 Off bytes;
689 Hdr *hp;
690 Compress *comp = nil;
691 Pushstate ps;
693 if (usefile && docreate) {
694 ar = create(usefile, OWRITE, 0666);
695 if (docompress)
696 comp = compmethod(usefile);
697 } else if (usefile)
698 ar = open(usefile, ORDWR);
699 else
700 ar = Stdout;
701 if (comp)
702 ar = push(ar, comp->comp, Output, &ps);
703 if (ar < 0)
704 sysfatal("can't open archive %s: %r", usefile);
706 if (usefile && !docreate) {
707 /* skip quickly to the end */
708 while ((hp = readhdr(ar)) != nil) {
709 bytes = hdrsize(hp);
710 for (blksleft = BYTES2TBLKS(bytes);
711 blksleft > 0 && getblkrd(ar, Justnxthdr) != nil;
712 blksleft -= blksread) {
713 blksread = gothowmany(blksleft);
714 putreadblks(ar, blksread);
717 /*
718 * we have just read the end-of-archive Tblock.
719 * now seek back over the (big) archive block containing it,
720 * and back up curblk ptr over end-of-archive Tblock in memory.
721 */
722 if (seek(ar, blkoff, 0) < 0)
723 sysfatal("can't seek back over end-of-archive: %r");
724 curblk--;
727 for (i = 0; argv[i] != nil; i++) {
728 addtoar(ar, argv[i], argv[i]);
729 chdir(origdir); /* for correctness & profiling */
732 /* write end-of-archive marker */
733 getblkz(ar);
734 putblk(ar);
735 getblkz(ar);
736 putlastblk(ar);
738 if (comp)
739 return pushclose(&ps);
740 if (ar > Stderr)
741 close(ar);
742 return nil;
745 /*
746 * tar [xt]
747 */
749 /* is pfx a file-name prefix of name? */
750 static int
751 prefix(char *name, char *pfx)
753 int pfxlen = strlen(pfx);
754 char clpfx[Maxname+1];
756 if (pfxlen > Maxname)
757 return 0;
758 strcpy(clpfx, pfx);
759 cleanname(clpfx);
760 return strncmp(pfx, name, pfxlen) == 0 &&
761 (name[pfxlen] == '\0' || name[pfxlen] == '/');
764 static int
765 match(char *name, char **argv)
767 int i;
768 char clname[Maxname+1];
770 if (argv[0] == nil)
771 return 1;
772 strcpy(clname, name);
773 cleanname(clname);
774 for (i = 0; argv[i] != nil; i++)
775 if (prefix(clname, argv[i]))
776 return 1;
777 return 0;
780 static int
781 makedir(char *s)
783 int f;
785 if (access(s, AEXIST) == 0)
786 return -1;
787 f = create(s, OREAD, DMDIR | 0777);
788 if (f >= 0)
789 close(f);
790 return f;
793 static void
794 mkpdirs(char *s)
796 int done = 0;
797 char *p = s;
799 while (!done && (p = strchr(p + 1, '/')) != nil) {
800 *p = '\0';
801 done = (access(s, AEXIST) < 0 && makedir(s) < 0);
802 *p = '/';
806 /* copy a file from the archive into the filesystem */
807 /* fname is result of name(), so has two extra bytes at beginning */
808 static void
809 extract1(int ar, Hdr *hp, char *fname)
811 int wrbytes, fd = -1, dir = 0;
812 long mtime = strtol(hp->mtime, nil, 8);
813 ulong mode = strtoul(hp->mode, nil, 8) & 0777;
814 Off bytes = strtoll(hp->size, nil, 8); /* for printing */
815 ulong blksread, blksleft = BYTES2TBLKS(hdrsize(hp));
816 Hdr *hbp;
818 if (isdir(hp)) {
819 mode |= DMDIR|0700;
820 dir = 1;
822 switch (hp->linkflag) {
823 case LF_LINK:
824 case LF_SYMLINK1:
825 case LF_SYMLINK2:
826 case LF_FIFO:
827 blksleft = 0;
828 break;
830 if (relative) {
831 if(fname[0] == '/')
832 *--fname = '.';
833 else if(fname[0] == '#'){
834 *--fname = '/';
835 *--fname = '.';
838 if (verb == Xtract) {
839 cleanname(fname);
840 switch (hp->linkflag) {
841 case LF_LINK:
842 case LF_SYMLINK1:
843 case LF_SYMLINK2:
844 fprint(2, "%s: can't make (sym)link %s\n",
845 argv0, fname);
846 break;
847 case LF_FIFO:
848 fprint(2, "%s: can't make fifo %s\n", argv0, fname);
849 break;
850 default:
851 if (!keepexisting || access(fname, AEXIST) < 0) {
852 int rw = (dir? OREAD: OWRITE);
854 fd = create(fname, rw, mode);
855 if (fd < 0) {
856 mkpdirs(fname);
857 fd = create(fname, rw, mode);
859 if (fd < 0 &&
860 (!dir || access(fname, AEXIST) < 0))
861 fprint(2, "%s: can't create %s: %r\n",
862 argv0, fname);
864 if (fd >= 0 && verbose)
865 fprint(2, "%s\n", fname);
866 break;
868 } else if (verbose) {
869 char *cp = ctime(mtime);
871 print("%M %8lld %-12.12s %-4.4s %s\n",
872 mode, bytes, cp+4, cp+24, fname);
873 } else
874 print("%s\n", fname);
876 for (; blksleft > 0; blksleft -= blksread) {
877 hbp = getblkrd(ar, (fd >= 0? Alldata: Justnxthdr));
878 if (hbp == nil)
879 sysfatal("unexpected EOF on archive extracting %s",
880 fname);
881 blksread = gothowmany(blksleft);
882 wrbytes = Tblock*blksread;
883 if(wrbytes > bytes)
884 wrbytes = bytes;
885 if (fd >= 0 && write(fd, hbp, wrbytes) != wrbytes)
886 sysfatal("write error on %s: %r", fname);
887 putreadblks(ar, blksread);
888 bytes -= wrbytes;
890 if (fd >= 0) {
891 /*
892 * directories should be wstated after we're done
893 * creating files in them.
894 */
895 if (settime) {
896 Dir nd;
898 nulldir(&nd);
899 nd.mtime = mtime;
900 if (isustar(hp))
901 nd.gid = hp->gname;
902 dirfwstat(fd, &nd);
904 close(fd);
908 static void
909 skip(int ar, Hdr *hp, char *fname)
911 ulong blksleft, blksread;
912 Hdr *hbp;
914 for (blksleft = BYTES2TBLKS(hdrsize(hp)); blksleft > 0;
915 blksleft -= blksread) {
916 hbp = getblkrd(ar, Justnxthdr);
917 if (hbp == nil)
918 sysfatal("unexpected EOF on archive extracting %s",
919 fname);
920 blksread = gothowmany(blksleft);
921 putreadblks(ar, blksread);
925 static char *
926 extract(char **argv)
928 int ar;
929 char *longname;
930 Hdr *hp;
931 Compress *comp = nil;
932 Pushstate ps;
934 if (usefile) {
935 ar = open(usefile, OREAD);
936 comp = compmethod(usefile);
937 } else
938 ar = Stdin;
939 if (comp)
940 ar = push(ar, comp->decomp, Input, &ps);
941 if (ar < 0)
942 sysfatal("can't open archive %s: %r", usefile);
944 while ((hp = readhdr(ar)) != nil) {
945 longname = name(hp);
946 if (match(longname, argv))
947 extract1(ar, hp, longname);
948 else
949 skip(ar, hp, longname);
952 if (comp)
953 return pushclose(&ps);
954 if (ar > Stderr)
955 close(ar);
956 return nil;
959 void
960 main(int argc, char *argv[])
962 int errflg = 0;
963 char *ret = nil;
965 quotefmtinstall();
966 fmtinstall('M', dirmodefmt);
968 TARGBEGIN {
969 case 'c':
970 docreate++;
971 verb = Replace;
972 break;
973 case 'f':
974 usefile = EARGF(usage());
975 break;
976 case 'g':
977 argid = strtoul(EARGF(usage()), 0, 0);
978 break;
979 case 'k':
980 keepexisting++;
981 break;
982 case 'm': /* compatibility */
983 settime = 0;
984 break;
985 case 'p':
986 posix++;
987 break;
988 case 'P':
989 posix = 0;
990 break;
991 case 'r':
992 verb = Replace;
993 break;
994 case 'R':
995 relative = 0;
996 break;
997 case 't':
998 verb = Toc;
999 break;
1000 case 'T':
1001 settime++;
1002 break;
1003 case 'u':
1004 aruid = strtoul(EARGF(usage()), 0, 0);
1005 break;
1006 case 'v':
1007 verbose++;
1008 break;
1009 case 'x':
1010 verb = Xtract;
1011 break;
1012 case 'z':
1013 docompress++;
1014 break;
1015 case '-':
1016 break;
1017 default:
1018 fprint(2, "tar: unknown letter %C\n", TARGC());
1019 errflg++;
1020 break;
1021 } TARGEND
1023 if (argc < 0 || errflg)
1024 usage();
1026 initblks();
1027 switch (verb) {
1028 case Toc:
1029 case Xtract:
1030 ret = extract(argv);
1031 break;
1032 case Replace:
1033 if (getwd(origdir, sizeof origdir) == nil)
1034 strcpy(origdir, "/tmp");
1035 ret = replace(argv);
1036 break;
1037 default:
1038 usage();
1039 break;
1041 exits(ret);