tar.c 22 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  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. quotefmtinstall();
  920. fmtinstall('M', dirmodefmt);
  921. TARGBEGIN {
  922. case 'c':
  923. docreate++;
  924. verb = Replace;
  925. break;
  926. case 'f':
  927. usefile = EARGF(usage());
  928. break;
  929. case 'g':
  930. argid = strtoul(EARGF(usage()), 0, 0);
  931. break;
  932. case 'k':
  933. keepexisting++;
  934. break;
  935. case 'm': /* compatibility */
  936. settime = 0;
  937. break;
  938. case 'p':
  939. posix++;
  940. break;
  941. case 'P':
  942. posix = 0;
  943. break;
  944. case 'r':
  945. verb = Replace;
  946. break;
  947. case 'R':
  948. relative = 0;
  949. break;
  950. case 't':
  951. verb = Toc;
  952. break;
  953. case 'T':
  954. settime++;
  955. break;
  956. case 'u':
  957. aruid = strtoul(EARGF(usage()), 0, 0);
  958. break;
  959. case 'v':
  960. verbose++;
  961. break;
  962. case 'x':
  963. verb = Xtract;
  964. break;
  965. case 'z':
  966. docompress++;
  967. break;
  968. case '-':
  969. break;
  970. default:
  971. fprint(2, "tar: unknown letter %C\n", TARGC());
  972. errflg++;
  973. break;
  974. } TARGEND
  975. if (argc < 0 || errflg)
  976. usage();
  977. initblks();
  978. switch (verb) {
  979. case Toc:
  980. case Xtract:
  981. ret = extract(argv);
  982. break;
  983. case Replace:
  984. if (getwd(origdir, sizeof origdir) == nil)
  985. strcpy(origdir, "/tmp");
  986. ret = replace(argv);
  987. break;
  988. default:
  989. usage();
  990. break;
  991. }
  992. exits(ret);
  993. }