]> git.lizzy.rs Git - plan9front.git/blob - sys/src/cmd/tar.c
tar, tarfs: implement longname support
[plan9front.git] / sys / src / cmd / tar.c
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  */
8
9 #include <u.h>
10 #include <libc.h>
11 #include <ctype.h>
12 #include <fcall.h>              /* for %M */
13 #include <String.h>
14
15 /*
16  * modified versions of those in libc.h; scans only the first arg for
17  * keyletters and options.
18  */
19 #define TARGBEGIN {\
20         (argv0 || (argv0 = *argv)), argv++, argc--;\
21         if (argv[0]) {\
22                 char *_args, *_argt;\
23                 Rune _argc;\
24                 _args = &argv[0][0];\
25                 _argc = 0;\
26                 while(*_args && (_args += chartorune(&_argc, _args)))\
27                         switch(_argc)
28 #define TARGEND SET(_argt); USED(_argt);USED(_argc);USED(_args); \
29         argc--, argv++; } \
30         USED(argv); USED(argc); }
31 #define TARGC() (_argc)
32
33 #define ROUNDUP(a, b)   (((a) + (b) - 1)/(b))
34 #define BYTES2TBLKS(bytes) ROUNDUP(bytes, Tblock)
35
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))
41
42 typedef vlong Off;
43 typedef char *(*Refill)(int ar, char *bufs, int justhdr);
44
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 };
50 enum {
51         Tblock = 512,
52         Namsiz = 100,
53         Maxpfx = 155,           /* from POSIX */
54         Maxname = Namsiz + 1 + Maxpfx,
55         Maxlongname = 65535,
56         Binsize = 0x80,         /* flag in size[0], from gnu: positive binary size */
57         Binnegsz = 0xff,        /* flag in size[0]: negative binary size */
58
59         Nblock = 40,            /* maximum blocksize */
60         Dblock = 20,            /* default blocksize */
61         Debug = 0,
62 };
63
64 /* POSIX link flags */
65 enum {
66         LF_PLAIN1 =     '\0',
67         LF_PLAIN2 =     '0',
68         LF_LINK =       '1',
69         LF_SYMLINK1 =   '2',
70         LF_SYMLINK2 =   's',            /* 4BSD used this */
71         LF_CHR =        '3',
72         LF_BLK =        '4',
73         LF_DIR =        '5',
74         LF_FIFO =       '6',
75         LF_CONTIG =     '7',
76
77         /* 'A' - 'Z' are reserved for custom implementations */
78
79         LF_LONGNAME =   'L',            /* GNU extenstion */
80         LF_LONGLINK =   'K',
81 };
82
83 #define islink(lf)      (isreallink(lf) || issymlink(lf))
84 #define isreallink(lf)  ((lf) == LF_LINK)
85 #define issymlink(lf)   ((lf) == LF_SYMLINK1 || (lf) == LF_SYMLINK2)
86
87 typedef union {
88         uchar   data[Tblock];
89         struct {
90                 char    name[Namsiz];
91                 char    mode[8];
92                 char    uid[8];
93                 char    gid[8];
94                 char    size[12];
95                 char    mtime[12];
96                 char    chksum[8];
97                 char    linkflag;
98                 char    linkname[Namsiz];
99
100                 /* rest are defined by POSIX's ustar format; see p1003.2b */
101                 char    magic[6];       /* "ustar" */
102                 char    version[2];
103                 char    uname[32];
104                 char    gname[32];
105                 char    devmajor[8];
106                 char    devminor[8];
107                 char    prefix[Maxpfx]; /* if non-null, path= prefix "/" name */
108         };
109 } Hdr;
110
111 typedef struct {
112         char    *comp;
113         char    *decomp;
114         char    *sfx[4];
115 } Compress;
116
117 static Compress comps[] = {
118         "gzip",         "gunzip",       { ".tar.gz", ".tgz" },  /* default */
119         "compress",     "uncompress",   { ".tar.Z",  ".tz" },
120         "bzip2",        "bunzip2",      { ".tar.bz", ".tbz",
121                                           ".tar.bz2",".tbz2" },
122 };
123
124 typedef struct {
125         int     kid;
126         int     fd;     /* original fd */
127         int     rfd;    /* replacement fd */
128         int     input;
129         int     open;
130 } Pushstate;
131
132 #define OTHER(rdwr) ((rdwr) == Rd? Wr: Rd)
133
134 static int debug;
135 static int fixednblock;
136 static int verb;
137 static int posix = 1;
138 static int docreate;
139 static int aruid;
140 static int argid;
141 static int relative = 1;
142 static int settime;
143 static int verbose;
144 static int docompress;
145 static int keepexisting;
146 static int ignerrs;             /* flag: ignore i/o errors if possible */
147 static Off blkoff;              /* offset of the current archive block (not Tblock) */
148 static Off nexthdr;
149
150 static int nblock = Dblock;
151 static int resync;
152 static char *usefile, *arname = "archive";
153 static char origdir[Maxlongname+1];
154 static Hdr *tpblk, *endblk;
155 static Hdr *curblk;
156
157 static void
158 usage(void)
159 {
160         fprint(2, "usage: %s {crtx}[PRTfgikmpsuvz] [archive] [file1 file2...]\n",
161                 argv0);
162         exits("usage");
163 }
164
165 /* I/O, with error retry or exit */
166
167 static int
168 cope(char *name, int fd, void *buf, long len, Off off)
169 {
170         fprint(2, "%s: %serror reading %s: %r\n", argv0,
171                 (ignerrs? "ignoring ": ""), name);
172         if (!ignerrs)
173                 exits("read error");
174
175         /* pretend we read len bytes of zeroes */
176         memset(buf, 0, len);
177         if (off >= 0)                   /* seekable? */
178                 seek(fd, off + len, 0);
179         return len;
180 }
181
182 static int
183 eread(char *name, int fd, void *buf, long len)
184 {
185         int rd;
186         Off off;
187
188         off = seek(fd, 0, 1);           /* for coping with errors */
189         rd = read(fd, buf, len);
190         if (rd < 0)
191                 rd = cope(name, fd, buf, len, off);
192         return rd;
193 }
194
195 static int
196 ereadn(char *name, int fd, void *buf, long len)
197 {
198         int rd;
199         Off off;
200
201         off = seek(fd, 0, 1);
202         rd = readn(fd, buf, len);
203         if (rd < 0)
204                 rd = cope(name, fd, buf, len, off);
205         return rd;
206 }
207
208 static int
209 ewrite(char *name, int fd, void *buf, long len)
210 {
211         int rd;
212
213         werrstr("");
214         rd = write(fd, buf, len);
215         if (rd != len)
216                 sysfatal("error writing %s: %r", name);
217         return rd;
218 }
219
220 /* compression */
221
222 static Compress *
223 compmethod(char *name)
224 {
225         int i, nmlen = strlen(name), sfxlen;
226         Compress *cp;
227
228         for (cp = comps; cp < comps + nelem(comps); cp++)
229                 for (i = 0; i < nelem(cp->sfx) && cp->sfx[i]; i++) {
230                         sfxlen = strlen(cp->sfx[i]);
231                         if (nmlen > sfxlen &&
232                             strcmp(cp->sfx[i], name + nmlen - sfxlen) == 0)
233                                 return cp;
234                 }
235         return docompress? comps: nil;
236 }
237
238 /*
239  * push a filter, cmd, onto fd.  if input, it's an input descriptor.
240  * returns a descriptor to replace fd, or -1 on error.
241  */
242 static int
243 push(int fd, char *cmd, int input, Pushstate *ps)
244 {
245         int nfd, pifds[2];
246         String *s;
247
248         ps->open = 0;
249         ps->fd = fd;
250         ps->input = input;
251         if (fd < 0 || pipe(pifds) < 0)
252                 return -1;
253         ps->kid = fork();
254         switch (ps->kid) {
255         case -1:
256                 return -1;
257         case 0:
258                 if (input)
259                         dup(pifds[Wr], Stdout);
260                 else
261                         dup(pifds[Rd], Stdin);
262                 close(pifds[input? Rd: Wr]);
263                 dup(fd, (input? Stdin: Stdout));
264                 s = s_new();
265                 if (cmd[0] != '/')
266                         s_append(s, "/bin/");
267                 s_append(s, cmd);
268                 execl(s_to_c(s), cmd, nil);
269                 sysfatal("can't exec %s: %r", cmd);
270         default:
271                 nfd = pifds[input? Rd: Wr];
272                 close(pifds[input? Wr: Rd]);
273                 break;
274         }
275         ps->rfd = nfd;
276         ps->open = 1;
277         return nfd;
278 }
279
280 static char *
281 pushclose(Pushstate *ps)
282 {
283         Waitmsg *wm;
284
285         if (ps->fd < 0 || ps->rfd < 0 || !ps->open)
286                 return "not open";
287         close(ps->rfd);
288         ps->rfd = -1;
289         ps->open = 0;
290         while ((wm = wait()) != nil && wm->pid != ps->kid)
291                 continue;
292         return wm? wm->msg: nil;
293 }
294
295 /*
296  * block-buffer management
297  */
298
299 static void
300 initblks(void)
301 {
302         free(tpblk);
303         tpblk = malloc(Tblock * nblock);
304         assert(tpblk != nil);
305         endblk = tpblk + nblock;
306 }
307
308 /*
309  * (re)fill block buffers from archive.  `justhdr' means we don't care
310  * about the data before the next header block.
311  */
312 static char *
313 refill(int ar, char *bufs, int justhdr)
314 {
315         int i, n;
316         unsigned bytes = Tblock * nblock;
317         static int done, first = 1, seekable;
318
319         if (done)
320                 return nil;
321
322         blkoff = seek(ar, 0, 1);                /* note position for `tar r' */
323         if (first)
324                 seekable = blkoff >= 0;
325         /* try to size non-pipe input at first read */
326         if (first && usefile && !fixednblock) {
327                 n = eread(arname, ar, bufs, bytes);
328                 if (n == 0)
329                         sysfatal("EOF reading archive %s: %r", arname);
330                 i = n;
331                 if (i % Tblock != 0)
332                         sysfatal("%s: archive block size (%d) error", arname, i);
333                 i /= Tblock;
334                 if (i != nblock) {
335                         nblock = i;
336                         fprint(2, "%s: blocking = %d\n", argv0, nblock);
337                         endblk = (Hdr *)bufs + nblock;
338                         bytes = n;
339                 }
340         } else if (justhdr && seekable && nexthdr - blkoff >= bytes) {
341                 /* optimisation for huge archive members on seekable media */
342                 if (seek(ar, bytes, 1) < 0)
343                         sysfatal("can't seek on archive %s: %r", arname);
344                 n = bytes;
345         } else
346                 n = ereadn(arname, ar, bufs, bytes);
347         first = 0;
348
349         if (n == 0)
350                 sysfatal("unexpected EOF reading archive %s", arname);
351         if (n % Tblock != 0)
352                 sysfatal("partial block read from archive %s", arname);
353         if (n != bytes) {
354                 done = 1;
355                 memset(bufs + n, 0, bytes - n);
356         }
357         return bufs;
358 }
359
360 static Hdr *
361 getblk(int ar, Refill rfp, int justhdr)
362 {
363         if (curblk == nil || curblk >= endblk) {  /* input block exhausted? */
364                 if (rfp != nil && (*rfp)(ar, (char *)tpblk, justhdr) == nil)
365                         return nil;
366                 curblk = tpblk;
367         }
368         return curblk++;
369 }
370
371 static Hdr *
372 getblkrd(int ar, int justhdr)
373 {
374         return getblk(ar, refill, justhdr);
375 }
376
377 static Hdr *
378 getblke(int ar)
379 {
380         return getblk(ar, nil, Alldata);
381 }
382
383 static Hdr *
384 getblkz(int ar)
385 {
386         Hdr *hp = getblke(ar);
387
388         if (hp != nil)
389                 memset(hp->data, 0, Tblock);
390         return hp;
391 }
392
393 /*
394  * how many block buffers are available, starting at the address
395  * just returned by getblk*?
396  */
397 static int
398 gothowmany(int max)
399 {
400         int n = endblk - (curblk - 1);
401
402         return n > max? max: n;
403 }
404
405 /*
406  * indicate that one is done with the last block obtained from getblke
407  * and it is now available to be written into the archive.
408  */
409 static void
410 putlastblk(int ar)
411 {
412         unsigned bytes = Tblock * nblock;
413
414         /* if writing end-of-archive, aid compression (good hygiene too) */
415         if (curblk < endblk)
416                 memset(curblk, 0, (char *)endblk - (char *)curblk);
417         ewrite(arname, ar, tpblk, bytes);
418 }
419
420 static void
421 putblk(int ar)
422 {
423         if (curblk >= endblk)
424                 putlastblk(ar);
425 }
426
427 static void
428 putbackblk(int ar)
429 {
430         curblk--;
431         USED(ar);
432 }
433
434 static void
435 putreadblks(int ar, int blks)
436 {
437         curblk += blks - 1;
438         USED(ar);
439 }
440
441 static void
442 putblkmany(int ar, int blks)
443 {
444         assert(blks > 0);
445         curblk += blks - 1;
446         putblk(ar);
447 }
448
449 /*
450  * common routines
451  */
452
453 /*
454  * modifies hp->chksum but restores it; important for the last block of the
455  * old archive when updating with `tar rf archive'
456  */
457 static long
458 chksum(Hdr *hp)
459 {
460         int n = Tblock;
461         long i = 0;
462         uchar *cp = hp->data;
463         char oldsum[sizeof hp->chksum];
464
465         memmove(oldsum, hp->chksum, sizeof oldsum);
466         memset(hp->chksum, ' ', sizeof hp->chksum);
467         while (n-- > 0)
468                 i += *cp++;
469         memmove(hp->chksum, oldsum, sizeof oldsum);
470         return i;
471 }
472
473 static int
474 isustar(Hdr *hp)
475 {
476         return strcmp(hp->magic, "ustar") == 0;
477 }
478
479 /*
480  * s is at most n bytes long, but need not be NUL-terminated.
481  * if shorter than n bytes, all bytes after the first NUL must also
482  * be NUL.
483  */
484 static int
485 strnlen(char *s, int n)
486 {
487         return s[n - 1] != '\0'? n: strlen(s);
488 }
489
490 /* set fullname from header */
491 static char *
492 name(Hdr *hp)
493 {
494         int pfxlen, namlen;
495         char *fullname;
496         static char fullnamebuf[2+Maxname+1];  /* 2+ for ./ on relative names */
497
498         fullname = fullnamebuf+2;
499         namlen = strnlen(hp->name, sizeof hp->name);
500         if (hp->prefix[0] == '\0' || !isustar(hp)) {    /* old-style name? */
501                 memmove(fullname, hp->name, namlen);
502                 fullname[namlen] = '\0';
503                 return fullname;
504         }
505
506         /* name is in two pieces */
507         pfxlen = strnlen(hp->prefix, sizeof hp->prefix);
508         memmove(fullname, hp->prefix, pfxlen);
509         fullname[pfxlen] = '/';
510         memmove(fullname + pfxlen + 1, hp->name, namlen);
511         fullname[pfxlen + 1 + namlen] = '\0';
512         return fullname;
513 }
514
515 static int
516 isdir(Hdr *hp)
517 {
518         /* the mode test is ugly but sometimes necessary */
519         return hp->linkflag == LF_DIR ||
520                 strrchr(name(hp), '\0')[-1] == '/' ||
521                 (strtoul(hp->mode, nil, 8)&0170000) == 040000;
522 }
523
524 static int
525 eotar(Hdr *hp)
526 {
527         return name(hp)[0] == '\0';
528 }
529
530 /*
531 static uvlong
532 getbe(uchar *src, int size)
533 {
534         uvlong vl = 0;
535
536         while (size-- > 0) {
537                 vl <<= 8;
538                 vl |= *src++;
539         }
540         return vl;
541 }
542  */
543
544 static void
545 putbe(uchar *dest, uvlong vl, int size)
546 {
547         for (dest += size; size-- > 0; vl >>= 8)
548                 *--dest = vl;
549 }
550
551 /*
552  * cautious parsing of octal numbers as ascii strings in
553  * a tar header block.  this is particularly important for
554  * trusting the checksum when trying to resync.
555  */
556 static uvlong
557 hdrotoull(char *st, char *end, uvlong errval, char *name, char *field)
558 {
559         char *numb;
560
561         for (numb = st; (*numb == ' ' || *numb == '\0') && numb < end; numb++)
562                 ;
563         if (numb < end && isascii(*numb) && isdigit(*numb))
564                 return strtoull(numb, nil, 8);
565         else if (numb >= end)
566                 fprint(2, "%s: %s: empty %s in header\n", argv0, name, field);
567         else
568                 fprint(2, "%s: %s: %s: non-numeric %s in header\n",
569                         argv0, name, numb, field);
570         return errval;
571 }
572
573 /*
574  * return the nominal size from the header block, which is not always the
575  * size in the archive (the archive size may be zero for some file types
576  * regardless of the nominal size).
577  *
578  * gnu and freebsd tars are now recording vlongs as big-endian binary
579  * with a flag in byte 0 to indicate this, which permits file sizes up to
580  * 2^64-1 (actually 2^80-1 but our file sizes are vlongs) rather than 2^33-1.
581  */
582 static Off
583 hdrsize(Hdr *hp)
584 {
585         uchar *p;
586
587         if((uchar)hp->size[0] == Binnegsz) {
588                 fprint(2, "%s: %s: negative length, which is insane\n",
589                         argv0, name(hp));
590                 return 0;
591         } else if((uchar)hp->size[0] == Binsize) {
592                 p = (uchar *)hp->size + sizeof hp->size - 1 -
593                         sizeof(vlong);          /* -1 for terminating space */
594                 return G8BEBYTE(p);
595         }
596
597         return hdrotoull(hp->size, hp->size + sizeof hp->size, 0,
598                 name(hp), "size");
599 }
600
601 /*
602  * return the number of bytes recorded in the archive.
603  */
604 static Off
605 arsize(Hdr *hp)
606 {
607         if(isdir(hp) || islink(hp->linkflag))
608                 return 0;
609         return hdrsize(hp);
610 }
611
612 static long
613 parsecksum(char *cksum, char *name)
614 {
615         Hdr *hp;
616
617         return hdrotoull(cksum, cksum + sizeof hp->chksum, (uvlong)-1LL,
618                 name, "checksum");
619 }
620
621 static Hdr *
622 readhdr(int ar)
623 {
624         long hdrcksum;
625         Hdr *hp;
626
627         hp = getblkrd(ar, Alldata);
628         if (hp == nil)
629                 sysfatal("unexpected EOF instead of archive header in %s",
630                         arname);
631         if (eotar(hp))                  /* end-of-archive block? */
632                 return nil;
633
634         hdrcksum = parsecksum(hp->chksum, name(hp));
635         if (hdrcksum == -1 || chksum(hp) != hdrcksum) {
636                 if (!resync)
637                         sysfatal("bad archive header checksum in %s: "
638                                 "name %.100s...; expected %#luo got %#luo",
639                                 arname, hp->name, hdrcksum, chksum(hp));
640                 fprint(2, "%s: skipping past archive header with bad checksum in %s...",
641                         argv0, arname);
642                 do {
643                         hp = getblkrd(ar, Alldata);
644                         if (hp == nil)
645                                 sysfatal("unexpected EOF looking for archive header in %s",
646                                         arname);
647                         hdrcksum = parsecksum(hp->chksum, name(hp));
648                 } while (hdrcksum == -1 || chksum(hp) != hdrcksum);
649                 fprint(2, "found %s\n", name(hp));
650         }
651         nexthdr += Tblock*(1 + BYTES2TBLKS(arsize(hp)));
652         return hp;
653 }
654
655 /*
656  * tar r[c]
657  */
658
659 /*
660  * if name is longer than Namsiz bytes, try to split it at a slash and fit the
661  * pieces into hp->prefix and hp->name.
662  */
663 static int
664 putfullname(Hdr *hp, char *name)
665 {
666         int namlen, pfxlen;
667         char *sl, *osl;
668         String *slname = nil;
669
670         if (isdir(hp)) {
671                 slname = s_new();
672                 s_append(slname, name);
673                 s_append(slname, "/");          /* posix requires this */
674                 name = s_to_c(slname);
675         }
676
677         namlen = strlen(name);
678         if (namlen <= Namsiz) {
679                 strncpy(hp->name, name, Namsiz);
680                 hp->prefix[0] = '\0';           /* ustar paranoia */
681                 return 0;
682         }
683
684         if (!posix || namlen > Maxname) {
685                 fprint(2, "%s: name too long for tar header: %s\n",
686                         argv0, name);
687                 return -1;
688         }
689         /*
690          * try various splits until one results in pieces that fit into the
691          * appropriate fields of the header.  look for slashes from right
692          * to left, in the hopes of putting the largest part of the name into
693          * hp->prefix, which is larger than hp->name.
694          */
695         sl = strrchr(name, '/');
696         while (sl != nil) {
697                 pfxlen = sl - name;
698                 if (pfxlen <= sizeof hp->prefix && namlen-1 - pfxlen <= Namsiz)
699                         break;
700                 osl = sl;
701                 *osl = '\0';
702                 sl = strrchr(name, '/');
703                 *osl = '/';
704         }
705         if (sl == nil) {
706                 fprint(2, "%s: name can't be split to fit tar header: %s\n",
707                         argv0, name);
708                 return -1;
709         }
710         *sl = '\0';
711         strncpy(hp->prefix, name, sizeof hp->prefix);
712         *sl++ = '/';
713         strncpy(hp->name, sl, sizeof hp->name);
714         if (slname)
715                 s_free(slname);
716         return 0;
717 }
718
719 static int
720 mkhdr(Hdr *hp, Dir *dir, char *file)
721 {
722         int r;
723
724         /*
725          * some of these fields run together, so we format them left-to-right
726          * and don't use snprint.
727          */
728         sprint(hp->mode, "%6lo ", dir->mode & 0777);
729         sprint(hp->uid, "%6o ", aruid);
730         sprint(hp->gid, "%6o ", argid);
731         if (dir->length >= (Off)1<<32) {
732                 static int printed;
733
734                 if (!printed) {
735                         printed = 1;
736                         fprint(2, "%s: storing large sizes in \"base 256\"\n", argv0);
737                 }
738                 hp->size[0] = Binsize;
739                 /* emit so-called `base 256' representation of size */
740                 putbe((uchar *)hp->size+1, dir->length, sizeof hp->size - 2);
741                 hp->size[sizeof hp->size - 1] = ' ';
742         } else
743                 sprint(hp->size, "%11lluo ", dir->length);
744         sprint(hp->mtime, "%11luo ", dir->mtime);
745         hp->linkflag = (dir->mode&DMDIR? LF_DIR: LF_PLAIN1);
746         r = putfullname(hp, file);
747         if (posix) {
748                 strncpy(hp->magic, "ustar", sizeof hp->magic);
749                 strncpy(hp->version, "00", sizeof hp->version);
750                 strncpy(hp->uname, dir->uid, sizeof hp->uname);
751                 strncpy(hp->gname, dir->gid, sizeof hp->gname);
752         }
753         sprint(hp->chksum, "%6luo", chksum(hp));
754         return r;
755 }
756
757 static void addtoar(int ar, char *file, char *shortf);
758
759 static void
760 addtreetoar(int ar, char *file, char *shortf, int fd)
761 {
762         int n;
763         Dir *dent, *dirents;
764         String *name = s_new();
765
766         n = dirreadall(fd, &dirents);
767         if (n < 0)
768                 fprint(2, "%s: dirreadall %s: %r\n", argv0, file);
769         close(fd);
770         if (n <= 0)
771                 return;
772
773         if (chdir(shortf) < 0)
774                 sysfatal("chdir %s: %r", file);
775         if (Debug)
776                 fprint(2, "chdir %s\t# %s\n", shortf, file);
777
778         for (dent = dirents; dent < dirents + n; dent++) {
779                 s_reset(name);
780                 s_append(name, file);
781                 s_append(name, "/");
782                 s_append(name, dent->name);
783                 addtoar(ar, s_to_c(name), dent->name);
784         }
785         s_free(name);
786         free(dirents);
787
788         /*
789          * this assumes that shortf is just one component, which is true
790          * during directory descent, but not necessarily true of command-line
791          * arguments.  Our caller (or addtoar's) must reset the working
792          * directory if necessary.
793          */
794         if (chdir("..") < 0)
795                 sysfatal("chdir %s/..: %r", file);
796         if (Debug)
797                 fprint(2, "chdir ..\n");
798 }
799
800 static void
801 addtoar(int ar, char *file, char *shortf)
802 {
803         int n, fd, isdir;
804         long bytes, blksread;
805         ulong blksleft;
806         Hdr *hbp;
807         Dir *dir;
808         String *name = nil;
809
810         if (shortf[0] == '#') {
811                 name = s_new();
812                 s_append(name, "./");
813                 s_append(name, shortf);
814                 shortf = s_to_c(name);
815         }
816
817         if (Debug)
818                 fprint(2, "opening %s   # %s\n", shortf, file);
819         fd = open(shortf, OREAD);
820         if (fd < 0) {
821                 fprint(2, "%s: can't open %s: %r\n", argv0, file);
822                 if (name)
823                         s_free(name);
824                 return;
825         }
826         dir = dirfstat(fd);
827         if (dir == nil)
828                 sysfatal("can't fstat %s: %r", file);
829
830         hbp = getblkz(ar);
831         isdir = (dir->qid.type & QTDIR) != 0;
832         if (mkhdr(hbp, dir, file) < 0) {
833                 putbackblk(ar);
834                 free(dir);
835                 close(fd);
836                 if (name)
837                         s_free(name);
838                 return;
839         }
840         putblk(ar);
841
842         blksleft = BYTES2TBLKS(dir->length);
843         free(dir);
844
845         if (isdir)
846                 addtreetoar(ar, file, shortf, fd);
847         else {
848                 for (; blksleft > 0; blksleft -= blksread) {
849                         hbp = getblke(ar);
850                         blksread = gothowmany(blksleft);
851                         assert(blksread >= 0);
852                         bytes = blksread * Tblock;
853                         n = ereadn(file, fd, hbp->data, bytes);
854                         assert(n >= 0);
855                         /*
856                          * ignore EOF.  zero any partial block to aid
857                          * compression and emergency recovery of data.
858                          */
859                         if (n < Tblock)
860                                 memset(hbp->data + n, 0, bytes - n);
861                         putblkmany(ar, blksread);
862                 }
863                 close(fd);
864                 if (verbose)
865                         fprint(2, "%s\n", file);
866         }
867         if (name)
868                 s_free(name);
869 }
870
871 static char *
872 replace(char **argv)
873 {
874         int i, ar;
875         ulong blksleft, blksread;
876         Off bytes;
877         Hdr *hp;
878         Compress *comp = nil;
879         Pushstate ps;
880
881         if (usefile && docreate) {
882                 ar = create(usefile, OWRITE, 0666);
883                 if (docompress)
884                         comp = compmethod(usefile);
885         } else if (usefile)
886                 ar = open(usefile, ORDWR);
887         else
888                 ar = Stdout;
889         if (comp)
890                 ar = push(ar, comp->comp, Output, &ps);
891         if (ar < 0)
892                 sysfatal("can't open archive %s: %r", usefile);
893
894         if (usefile && !docreate) {
895                 /* skip quickly to the end */
896                 while ((hp = readhdr(ar)) != nil) {
897                         bytes = arsize(hp);
898                         for (blksleft = BYTES2TBLKS(bytes);
899                              blksleft > 0 && getblkrd(ar, Justnxthdr) != nil;
900                              blksleft -= blksread) {
901                                 blksread = gothowmany(blksleft);
902                                 putreadblks(ar, blksread);
903                         }
904                 }
905                 /*
906                  * we have just read the end-of-archive Tblock.
907                  * now seek back over the (big) archive block containing it,
908                  * and back up curblk ptr over end-of-archive Tblock in memory.
909                  */
910                 if (seek(ar, blkoff, 0) < 0)
911                         sysfatal("can't seek back over end-of-archive in %s: %r",
912                                 arname);
913                 curblk--;
914         }
915
916         for (i = 0; argv[i] != nil; i++) {
917                 addtoar(ar, argv[i], argv[i]);
918                 chdir(origdir);         /* for correctness & profiling */
919         }
920
921         /* write end-of-archive marker */
922         getblkz(ar);
923         putblk(ar);
924         getblkz(ar);
925         putlastblk(ar);
926
927         if (comp)
928                 return pushclose(&ps);
929         if (ar > Stderr)
930                 close(ar);
931         return nil;
932 }
933
934 /*
935  * tar [xt]
936  */
937
938 /* is pfx a file-name prefix of name? */
939 static int
940 prefix(char *name, char *pfx)
941 {
942         char clpfx[Maxlongname+1];
943         int pfxlen = strlen(pfx);
944
945         clpfx[Maxlongname] = '\0';
946         strncpy(clpfx, pfx, Maxlongname);
947         cleanname(clpfx);
948         return strncmp(clpfx, name, pfxlen) == 0 &&
949                 (name[pfxlen] == '\0' || name[pfxlen] == '/');
950 }
951
952 static int
953 match(char *name, char **argv)
954 {
955         char clname[Maxlongname+1];
956         int i;
957
958         if (argv[0] == nil)
959                 return 1;
960         clname[Maxlongname] = '\0';
961         strncpy(clname, name, Maxlongname);
962         cleanname(clname);
963         for (i = 0; argv[i] != nil; i++)
964                 if (prefix(clname, argv[i]))
965                         return 1;
966         return 0;
967 }
968
969 static void
970 cantcreate(char *s, int mode)
971 {
972         int len;
973         static char *last;
974
975         /*
976          * Always print about files.  Only print about directories
977          * we haven't printed about.  (Assumes archive is ordered
978          * nicely.)
979          */
980         if(mode&DMDIR){
981                 if(last){
982                         /* already printed this directory */
983                         if(strcmp(s, last) == 0)
984                                 return;
985                         /* printed a higher directory, so printed this one */
986                         len = strlen(s);
987                         if(memcmp(s, last, len) == 0 && last[len] == '/')
988                                 return;
989                 }
990                 /* save */
991                 free(last);
992                 last = strdup(s);
993         }
994         fprint(2, "%s: can't create %s: %r\n", argv0, s);
995 }
996
997 static int
998 makedir(char *s)
999 {
1000         int f;
1001
1002         if (access(s, AEXIST) == 0)
1003                 return -1;
1004         f = create(s, OREAD, DMDIR | 0777);
1005         if (f >= 0)
1006                 close(f);
1007         else
1008                 cantcreate(s, DMDIR);
1009         return f;
1010 }
1011
1012 static int
1013 mkpdirs(char *s)
1014 {
1015         int err;
1016         char *p;
1017
1018         p = s;
1019         err = 0;
1020         while (!err && (p = strchr(p+1, '/')) != nil) {
1021                 *p = '\0';
1022                 err = (access(s, AEXIST) < 0 && makedir(s) < 0);
1023                 *p = '/';
1024         }
1025         return -err;
1026 }
1027
1028 /* Call access but preserve the error string. */
1029 static int
1030 xaccess(char *name, int mode)
1031 {
1032         char err[ERRMAX];
1033         int rv;
1034
1035         err[0] = 0;
1036         errstr(err, sizeof err);
1037         rv = access(name, mode);
1038         errstr(err, sizeof err);
1039         return rv;
1040 }
1041
1042 static int
1043 openfname(Hdr *hp, char *fname, int dir, int mode)
1044 {
1045         int fd;
1046
1047         fd = -1;
1048         cleanname(fname);
1049         switch (hp->linkflag) {
1050         case LF_LINK:
1051         case LF_SYMLINK1:
1052         case LF_SYMLINK2:
1053         case LF_LONGLINK:
1054                 fprint(2, "%s: can't make (sym)link %s\n",
1055                         argv0, fname);
1056                 break;
1057         case LF_FIFO:
1058                 fprint(2, "%s: can't make fifo %s\n", argv0, fname);
1059                 break;
1060         default:
1061                 if (!keepexisting || access(fname, AEXIST) < 0) {
1062                         int rw = (dir? OREAD: OWRITE);
1063
1064                         fd = create(fname, rw, mode);
1065                         if (fd < 0) {
1066                                 mkpdirs(fname);
1067                                 fd = create(fname, rw, mode);
1068                         }
1069                         if (fd < 0 && (!dir || xaccess(fname, AEXIST) < 0))
1070                                 cantcreate(fname, mode);
1071                 }
1072                 if (fd >= 0 && verbose)
1073                         fprint(2, "%s\n", fname);
1074                 break;
1075         }
1076         return fd;
1077 }
1078
1079 /* copy from archive to file system (or nowhere for table-of-contents) */
1080 static void
1081 copyfromar(int ar, int fd, char *fname, ulong blksleft, Off bytes)
1082 {
1083         int wrbytes;
1084         ulong blksread;
1085         Hdr *hbp;
1086
1087         if (blksleft == 0 || bytes < 0)
1088                 bytes = 0;
1089         for (; blksleft > 0; blksleft -= blksread) {
1090                 hbp = getblkrd(ar, (fd >= 0? Alldata: Justnxthdr));
1091                 if (hbp == nil)
1092                         sysfatal("unexpected EOF on archive extracting %s from %s",
1093                                 fname, arname);
1094                 blksread = gothowmany(blksleft);
1095                 if (blksread <= 0) {
1096                         fprint(2, "%s: got %ld blocks reading %s!\n",
1097                                 argv0, blksread, fname);
1098                         blksread = 0;
1099                 }
1100                 wrbytes = Tblock*blksread;
1101                 assert(bytes >= 0);
1102                 if(wrbytes > bytes)
1103                         wrbytes = bytes;
1104                 assert(wrbytes >= 0);
1105                 if (fd >= 0)
1106                         ewrite(fname, fd, hbp->data, wrbytes);
1107                 putreadblks(ar, blksread);
1108                 bytes -= wrbytes;
1109                 assert(bytes >= 0);
1110         }
1111         if (bytes > 0)
1112                 fprint(2, "%s: %lld bytes uncopied at EOF on archive %s; "
1113                         "%s not fully extracted\n", argv0, bytes, arname, fname);
1114 }
1115
1116 static void
1117 wrmeta(int fd, Hdr *hp, long mtime, int mode)           /* update metadata */
1118 {
1119         Dir nd;
1120
1121         nulldir(&nd);
1122         nd.mtime = mtime;
1123         nd.mode = mode;
1124         dirfwstat(fd, &nd);
1125         if (isustar(hp)) {
1126                 nulldir(&nd);
1127                 nd.gid = hp->gname;
1128                 dirfwstat(fd, &nd);
1129                 nulldir(&nd);
1130                 nd.uid = hp->uname;
1131                 dirfwstat(fd, &nd);
1132         }
1133 }
1134
1135 /*
1136  * copy a file from the archive into the filesystem.
1137  * fname is result of name(), so has two extra bytes at beginning.
1138  */
1139 static void
1140 extract1(int ar, Hdr *hp, char *fname)
1141 {
1142         int fd = -1, dir = 0;
1143         long mtime = strtol(hp->mtime, nil, 8);
1144         ulong mode = strtoul(hp->mode, nil, 8) & 0777;
1145         Off bytes = hdrsize(hp);                /* for printing */
1146         ulong blksleft = BYTES2TBLKS(arsize(hp));
1147
1148         /* fiddle name, figure out mode and blocks */
1149         if (isdir(hp)) {
1150                 mode |= DMDIR|0700;
1151                 dir = 1;
1152         }
1153         switch (hp->linkflag) {
1154         case LF_LINK:
1155         case LF_SYMLINK1:
1156         case LF_SYMLINK2:
1157         case LF_FIFO:
1158                 blksleft = 0;
1159                 break;
1160         }
1161         if (relative)
1162                 if(fname[0] == '/')
1163                         *--fname = '.';
1164                 else if(fname[0] == '#'){
1165                         *--fname = '/';
1166                         *--fname = '.';
1167                 }
1168
1169         if (verb == Xtract)
1170                 fd = openfname(hp, fname, dir, mode);
1171         else if (verbose) {
1172                 char *cp = ctime(mtime);
1173
1174                 print("%M %8lld %-12.12s %-4.4s %s\n",
1175                         mode, bytes, cp+4, cp+24, fname);
1176         } else
1177                 print("%s\n", fname);
1178
1179         copyfromar(ar, fd, fname, blksleft, bytes);
1180
1181         /* touch up meta data and close */
1182         if (fd >= 0) {
1183                 /*
1184                  * directories should be wstated *after* we're done
1185                  * creating files in them, but we don't do that.
1186                  */
1187                 if (settime)
1188                         wrmeta(fd, hp, mtime, mode);
1189                 close(fd);
1190         }
1191 }
1192
1193 static void
1194 skip(int ar, Hdr *hp, char *fname)
1195 {
1196         ulong blksleft, blksread;
1197         Hdr *hbp;
1198
1199         for (blksleft = BYTES2TBLKS(arsize(hp)); blksleft > 0;
1200              blksleft -= blksread) {
1201                 hbp = getblkrd(ar, Justnxthdr);
1202                 if (hbp == nil)
1203                         sysfatal("unexpected EOF on archive extracting %s from %s",
1204                                 fname, arname);
1205                 blksread = gothowmany(blksleft);
1206                 putreadblks(ar, blksread);
1207         }
1208 }
1209
1210 static char*
1211 getname(int ar, Hdr *hp)
1212 {
1213         static char namebuf[Maxlongname+1], *nextname = nil;
1214         ulong blksleft, blksread;
1215         char *fname, *p;
1216         int n;
1217
1218         if(nextname != nil && nextname[0] != '\0'){
1219                 fname = nextname, nextname = nil;
1220                 return fname;
1221         }
1222         fname = name(hp);
1223         if(hp->linkflag == LF_LONGNAME){
1224                 p = namebuf;
1225                 for (blksleft = BYTES2TBLKS(arsize(hp)); blksleft > 0;
1226                      blksleft -= blksread) {
1227                         hp = getblkrd(ar, Alldata);
1228                         if (hp == nil)
1229                                 sysfatal("unexpected EOF on archive reading %s from %s",
1230                                         fname, arname);
1231                         blksread = gothowmany(blksleft);
1232                         n = &namebuf[Maxlongname] - p;
1233                         if(Tblock*blksread < n)
1234                                 n = Tblock*blksread;
1235                         memmove(p, hp->data, n);
1236                         p += n;
1237                         putreadblks(ar, blksread);
1238                 }
1239                 *p = '\0';
1240                 fname = nil;
1241                 nextname = namebuf;
1242         } else {
1243                 namebuf[Maxlongname] = '\0';
1244                 strncpy(namebuf, fname, Maxlongname);
1245                 fname = namebuf;
1246         }
1247         return fname;
1248 }
1249
1250 static char *
1251 extract(char **argv)
1252 {
1253         int ar;
1254         char *longname;
1255         Hdr *hp;
1256         Compress *comp = nil;
1257         Pushstate ps;
1258
1259         if (usefile) {
1260                 ar = open(usefile, OREAD);
1261                 comp = compmethod(usefile);
1262         } else
1263                 ar = Stdin;
1264         if (comp)
1265                 ar = push(ar, comp->decomp, Input, &ps);
1266         if (ar < 0)
1267                 sysfatal("can't open archive %s: %r", usefile);
1268
1269         while ((hp = readhdr(ar)) != nil) {
1270                 longname = getname(ar, hp);
1271                 if(longname == nil)
1272                         continue;
1273                 if (match(longname, argv))
1274                         extract1(ar, hp, longname);
1275                 else
1276                         skip(ar, hp, longname);
1277         }
1278
1279         if (comp)
1280                 return pushclose(&ps);
1281         if (ar > Stderr)
1282                 close(ar);
1283         return nil;
1284 }
1285
1286 void
1287 main(int argc, char *argv[])
1288 {
1289         int errflg = 0;
1290         char *ret = nil;
1291
1292         fmtinstall('M', dirmodefmt);
1293
1294         TARGBEGIN {
1295         case 'c':
1296                 docreate++;
1297                 verb = Replace;
1298                 break;
1299         case 'f':
1300                 usefile = arname = EARGF(usage());
1301                 break;
1302         case 'g':
1303                 argid = strtoul(EARGF(usage()), 0, 0);
1304                 break;
1305         case 'i':
1306                 ignerrs = 1;
1307                 break;
1308         case 'k':
1309                 keepexisting++;
1310                 break;
1311         case 'm':       /* compatibility */
1312                 settime = 0;
1313                 break;
1314         case 'p':
1315                 posix++;
1316                 break;
1317         case 'P':
1318                 posix = 0;
1319                 break;
1320         case 'r':
1321                 verb = Replace;
1322                 break;
1323         case 'R':
1324                 relative = 0;
1325                 break;
1326         case 's':
1327                 resync++;
1328                 break;
1329         case 't':
1330                 verb = Toc;
1331                 break;
1332         case 'T':
1333                 settime++;
1334                 break;
1335         case 'u':
1336                 aruid = strtoul(EARGF(usage()), 0, 0);
1337                 break;
1338         case 'v':
1339                 verbose++;
1340                 break;
1341         case 'x':
1342                 verb = Xtract;
1343                 break;
1344         case 'z':
1345                 docompress++;
1346                 break;
1347         case '-':
1348                 break;
1349         default:
1350                 fprint(2, "tar: unknown letter %C\n", TARGC());
1351                 errflg++;
1352                 break;
1353         } TARGEND
1354
1355         if (argc < 0 || errflg)
1356                 usage();
1357
1358         initblks();
1359         switch (verb) {
1360         case Toc:
1361         case Xtract:
1362                 ret = extract(argv);
1363                 break;
1364         case Replace:
1365                 if (getwd(origdir, sizeof origdir) == nil)
1366                         strcpy(origdir, "/tmp");
1367                 ret = replace(argv);
1368                 break;
1369         default:
1370                 usage();
1371                 break;
1372         }
1373         exits(ret);
1374 }