tar.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  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. fd = open(shortf, OREAD);
  569. if (fd < 0) {
  570. fprint(2, "%s: can't open %s: %r\n", argv0, file);
  571. return;
  572. }
  573. dir = dirfstat(fd);
  574. if (dir == nil)
  575. sysfatal("can't fstat %s: %r", file);
  576. hbp = getblkz(ar);
  577. isdir = !!(dir->qid.type&QTDIR);
  578. if (mkhdr(hbp, dir, file) < 0) {
  579. putbackblk(ar);
  580. free(dir);
  581. close(fd);
  582. return;
  583. }
  584. putblk(ar);
  585. blksleft = BYTES2TBLKS(dir->length);
  586. free(dir);
  587. if (isdir)
  588. addtreetoar(ar, file, shortf, fd);
  589. else {
  590. for (; blksleft > 0; blksleft -= blksread) {
  591. hbp = getblke(ar);
  592. blksread = gothowmany(blksleft);
  593. bytes = blksread * Tblock;
  594. n = readn(fd, hbp->data, bytes);
  595. if (n < 0)
  596. sysfatal("error reading %s: %r", file);
  597. /*
  598. * ignore EOF. zero any partial block to aid
  599. * compression and emergency recovery of data.
  600. */
  601. if (n < Tblock)
  602. memset(hbp->data + n, 0, bytes - n);
  603. putblkmany(ar, blksread);
  604. }
  605. close(fd);
  606. if (verbose)
  607. fprint(2, "%s\n", file);
  608. }
  609. }
  610. static char *
  611. replace(char **argv)
  612. {
  613. int i, ar;
  614. ulong blksleft, blksread;
  615. Off bytes;
  616. Hdr *hp;
  617. Compress *comp = nil;
  618. Pushstate ps;
  619. if (usefile && docreate) {
  620. ar = create(usefile, OWRITE, 0666);
  621. if (docompress)
  622. comp = compmethod(usefile);
  623. } else if (usefile)
  624. ar = open(usefile, ORDWR);
  625. else
  626. ar = Stdout;
  627. if (comp)
  628. ar = push(ar, comp->comp, Output, &ps);
  629. if (ar < 0)
  630. sysfatal("can't open archive %s: %r", usefile);
  631. if (usefile && !docreate) {
  632. /* skip quickly to the end */
  633. while ((hp = readhdr(ar)) != nil) {
  634. bytes = hdrsize(hp);
  635. for (blksleft = BYTES2TBLKS(bytes);
  636. blksleft > 0 && getblkrd(ar, Justnxthdr) != nil;
  637. blksleft -= blksread) {
  638. blksread = gothowmany(blksleft);
  639. putreadblks(ar, blksread);
  640. }
  641. }
  642. /*
  643. * we have just read the end-of-archive Tblock.
  644. * now seek back over the (big) archive block containing it,
  645. * and back up curblk ptr over end-of-archive Tblock in memory.
  646. */
  647. if (seek(ar, blkoff, 0) < 0)
  648. sysfatal("can't seek back over end-of-archive: %r");
  649. curblk--;
  650. }
  651. for (i = 0; argv[i] != nil; i++) {
  652. addtoar(ar, argv[i], argv[i]);
  653. chdir(origdir); /* for correctness & profiling */
  654. }
  655. /* write end-of-archive marker */
  656. getblkz(ar);
  657. putblk(ar);
  658. getblkz(ar);
  659. putlastblk(ar);
  660. if (comp)
  661. return pushclose(&ps);
  662. if (ar > Stderr)
  663. close(ar);
  664. return nil;
  665. }
  666. /*
  667. * tar [xt]
  668. */
  669. /* is pfx a file-name prefix of name? */
  670. static int
  671. prefix(char *name, char *pfx)
  672. {
  673. int pfxlen = strlen(pfx);
  674. char clpfx[Maxname+1];
  675. if (pfxlen > Maxname)
  676. return 0;
  677. strcpy(clpfx, pfx);
  678. cleanname(clpfx);
  679. return strncmp(pfx, name, pfxlen) == 0 &&
  680. (name[pfxlen] == '\0' || name[pfxlen] == '/');
  681. }
  682. static int
  683. match(char *name, char **argv)
  684. {
  685. int i;
  686. char clname[Maxname+1];
  687. if (argv[0] == nil)
  688. return 1;
  689. strcpy(clname, name);
  690. cleanname(clname);
  691. for (i = 0; argv[i] != nil; i++)
  692. if (prefix(clname, argv[i]))
  693. return 1;
  694. return 0;
  695. }
  696. static void
  697. cantcreate(char *s, int mode)
  698. {
  699. int len;
  700. static char *last;
  701. /*
  702. * Always print about files. Only print about directories
  703. * we haven't printed about. (Assumes archive is ordered
  704. * nicely.)
  705. */
  706. if(mode&DMDIR){
  707. if(last){
  708. /* already printed this directory */
  709. if(strcmp(s, last) == 0)
  710. return;
  711. /* printed a higher directory, so printed this one */
  712. len = strlen(s);
  713. if(memcmp(s, last, len) == 0 && last[len] == '/')
  714. return;
  715. }
  716. /* save */
  717. free(last);
  718. last = strdup(s);
  719. }
  720. fprint(2, "%s: can't create %s: %r\n", argv0, s);
  721. }
  722. static int
  723. makedir(char *s)
  724. {
  725. int f;
  726. if (access(s, AEXIST) == 0)
  727. return -1;
  728. f = create(s, OREAD, DMDIR | 0777);
  729. if (f >= 0)
  730. close(f);
  731. else
  732. cantcreate(s, DMDIR);
  733. return f;
  734. }
  735. static int
  736. mkpdirs(char *s)
  737. {
  738. int err;
  739. char *p;
  740. p = s;
  741. err = 0;
  742. while (!err && (p = strchr(p+1, '/')) != nil) {
  743. *p = '\0';
  744. err = (access(s, AEXIST) < 0 && makedir(s) < 0);
  745. *p = '/';
  746. }
  747. return -err;
  748. }
  749. /* Call access but preserve the error string. */
  750. static int
  751. xaccess(char *name, int mode)
  752. {
  753. char err[ERRMAX];
  754. int rv;
  755. err[0] = 0;
  756. errstr(err, sizeof err);
  757. rv = access(name, mode);
  758. errstr(err, sizeof err);
  759. return rv;
  760. }
  761. /* copy a file from the archive into the filesystem */
  762. /* fname is result of name(), so has two extra bytes at beginning */
  763. static void
  764. extract1(int ar, Hdr *hp, char *fname)
  765. {
  766. int wrbytes, fd = -1, dir = 0;
  767. long mtime = strtol(hp->mtime, nil, 8);
  768. ulong mode = strtoul(hp->mode, nil, 8) & 0777;
  769. Off bytes = strtoll(hp->size, nil, 8); /* for printing */
  770. ulong blksread, blksleft = BYTES2TBLKS(hdrsize(hp));
  771. Hdr *hbp;
  772. if (isdir(hp)) {
  773. mode |= DMDIR|0700;
  774. dir = 1;
  775. }
  776. switch (hp->linkflag) {
  777. case LF_LINK:
  778. case LF_SYMLINK1:
  779. case LF_SYMLINK2:
  780. case LF_FIFO:
  781. blksleft = 0;
  782. break;
  783. }
  784. if (relative) {
  785. if(fname[0] == '/')
  786. *--fname = '.';
  787. else if(fname[0] == '#'){
  788. *--fname = '/';
  789. *--fname = '.';
  790. }
  791. }
  792. if (verb == Xtract) {
  793. cleanname(fname);
  794. switch (hp->linkflag) {
  795. case LF_LINK:
  796. case LF_SYMLINK1:
  797. case LF_SYMLINK2:
  798. fprint(2, "%s: can't make (sym)link %s\n",
  799. argv0, fname);
  800. break;
  801. case LF_FIFO:
  802. fprint(2, "%s: can't make fifo %s\n", argv0, fname);
  803. break;
  804. default:
  805. if (!keepexisting || access(fname, AEXIST) < 0) {
  806. int rw = (dir? OREAD: OWRITE);
  807. fd = create(fname, rw, mode);
  808. if (fd < 0) {
  809. mkpdirs(fname);
  810. fd = create(fname, rw, mode);
  811. }
  812. if (fd < 0 &&
  813. (!dir || xaccess(fname, AEXIST) < 0))
  814. cantcreate(fname, mode);
  815. }
  816. if (fd >= 0 && verbose)
  817. fprint(2, "%s\n", fname);
  818. break;
  819. }
  820. } else if (verbose) {
  821. char *cp = ctime(mtime);
  822. print("%M %8lld %-12.12s %-4.4s %s\n",
  823. mode, bytes, cp+4, cp+24, fname);
  824. } else
  825. print("%s\n", fname);
  826. for (; blksleft > 0; blksleft -= blksread) {
  827. hbp = getblkrd(ar, (fd >= 0? Alldata: Justnxthdr));
  828. if (hbp == nil)
  829. sysfatal("unexpected EOF on archive extracting %s",
  830. fname);
  831. blksread = gothowmany(blksleft);
  832. wrbytes = Tblock*blksread;
  833. if(wrbytes > bytes)
  834. wrbytes = bytes;
  835. if (fd >= 0 && write(fd, hbp->data, wrbytes) != wrbytes)
  836. sysfatal("write error on %s: %r", fname);
  837. putreadblks(ar, blksread);
  838. bytes -= wrbytes;
  839. }
  840. if (fd >= 0) {
  841. /*
  842. * directories should be wstated after we're done
  843. * creating files in them.
  844. */
  845. if (settime) {
  846. Dir nd;
  847. nulldir(&nd);
  848. nd.mtime = mtime;
  849. if (isustar(hp))
  850. nd.gid = hp->gname;
  851. dirfwstat(fd, &nd);
  852. }
  853. close(fd);
  854. }
  855. }
  856. static void
  857. skip(int ar, Hdr *hp, char *fname)
  858. {
  859. ulong blksleft, blksread;
  860. Hdr *hbp;
  861. for (blksleft = BYTES2TBLKS(hdrsize(hp)); blksleft > 0;
  862. blksleft -= blksread) {
  863. hbp = getblkrd(ar, Justnxthdr);
  864. if (hbp == nil)
  865. sysfatal("unexpected EOF on archive extracting %s",
  866. fname);
  867. blksread = gothowmany(blksleft);
  868. putreadblks(ar, blksread);
  869. }
  870. }
  871. static char *
  872. extract(char **argv)
  873. {
  874. int ar;
  875. char *longname;
  876. Hdr *hp;
  877. Compress *comp = nil;
  878. Pushstate ps;
  879. if (usefile) {
  880. ar = open(usefile, OREAD);
  881. comp = compmethod(usefile);
  882. } else
  883. ar = Stdin;
  884. if (comp)
  885. ar = push(ar, comp->decomp, Input, &ps);
  886. if (ar < 0)
  887. sysfatal("can't open archive %s: %r", usefile);
  888. while ((hp = readhdr(ar)) != nil) {
  889. longname = name(hp);
  890. if (match(longname, argv))
  891. extract1(ar, hp, longname);
  892. else
  893. skip(ar, hp, longname);
  894. }
  895. if (comp)
  896. return pushclose(&ps);
  897. if (ar > Stderr)
  898. close(ar);
  899. return nil;
  900. }
  901. void
  902. main(int argc, char *argv[])
  903. {
  904. int errflg = 0;
  905. char *ret = nil;
  906. quotefmtinstall();
  907. fmtinstall('M', dirmodefmt);
  908. TARGBEGIN {
  909. case 'c':
  910. docreate++;
  911. verb = Replace;
  912. break;
  913. case 'f':
  914. usefile = EARGF(usage());
  915. break;
  916. case 'g':
  917. argid = strtoul(EARGF(usage()), 0, 0);
  918. break;
  919. case 'k':
  920. keepexisting++;
  921. break;
  922. case 'm': /* compatibility */
  923. settime = 0;
  924. break;
  925. case 'p':
  926. posix++;
  927. break;
  928. case 'P':
  929. posix = 0;
  930. break;
  931. case 'r':
  932. verb = Replace;
  933. break;
  934. case 'R':
  935. relative = 0;
  936. break;
  937. case 't':
  938. verb = Toc;
  939. break;
  940. case 'T':
  941. settime++;
  942. break;
  943. case 'u':
  944. aruid = strtoul(EARGF(usage()), 0, 0);
  945. break;
  946. case 'v':
  947. verbose++;
  948. break;
  949. case 'x':
  950. verb = Xtract;
  951. break;
  952. case 'z':
  953. docompress++;
  954. break;
  955. case '-':
  956. break;
  957. default:
  958. fprint(2, "tar: unknown letter %C\n", TARGC());
  959. errflg++;
  960. break;
  961. } TARGEND
  962. if (argc < 0 || errflg)
  963. usage();
  964. initblks();
  965. switch (verb) {
  966. case Toc:
  967. case Xtract:
  968. ret = extract(argv);
  969. break;
  970. case Replace:
  971. if (getwd(origdir, sizeof origdir) == nil)
  972. strcpy(origdir, "/tmp");
  973. ret = replace(argv);
  974. break;
  975. default:
  976. usage();
  977. break;
  978. }
  979. exits(ret);
  980. }