tar.c 20 KB

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