tar.c 22 KB

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