misc.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  1. /* Miscellaneous functions, not really specific to GNU tar.
  2. Copyright 1988, 1992, 1994-1997, 1999-2001, 2003-2007, 2009-2010,
  3. 2012-2014 Free Software Foundation, Inc.
  4. This program is free software; you can redistribute it and/or modify it
  5. under the terms of the GNU General Public License as published by the
  6. Free Software Foundation; either version 3, or (at your option) any later
  7. version.
  8. This program is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
  11. Public License for more details.
  12. You should have received a copy of the GNU General Public License along
  13. with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #define COMMON_INLINE _GL_EXTERN_INLINE
  15. #include <system.h>
  16. #include <rmt.h>
  17. #include "common.h"
  18. #include <quotearg.h>
  19. #include <xgetcwd.h>
  20. #include <unlinkdir.h>
  21. #include <utimens.h>
  22. #ifndef DOUBLE_SLASH_IS_DISTINCT_ROOT
  23. # define DOUBLE_SLASH_IS_DISTINCT_ROOT 0
  24. #endif
  25. static const char *tar_getcdpath (int);
  26. /* Handling strings. */
  27. /* Assign STRING to a copy of VALUE if not zero, or to zero. If
  28. STRING was nonzero, it is freed first. */
  29. void
  30. assign_string (char **string, const char *value)
  31. {
  32. free (*string);
  33. *string = value ? xstrdup (value) : 0;
  34. }
  35. #if 0
  36. /* This function is currently unused; perhaps it should be removed? */
  37. /* Allocate a copy of the string quoted as in C, and returns that. If
  38. the string does not have to be quoted, it returns a null pointer.
  39. The allocated copy should normally be freed with free() after the
  40. caller is done with it.
  41. This is used in one context only: generating the directory file in
  42. incremental dumps. The quoted string is not intended for human
  43. consumption; it is intended only for unquote_string. The quoting
  44. is locale-independent, so that users needn't worry about locale
  45. when reading directory files. This means that we can't use
  46. quotearg, as quotearg is locale-dependent and is meant for human
  47. consumption. */
  48. static char *
  49. quote_copy_string (const char *string)
  50. {
  51. const char *source = string;
  52. char *destination = 0;
  53. char *buffer = 0;
  54. int copying = 0;
  55. while (*source)
  56. {
  57. int character = *source++;
  58. switch (character)
  59. {
  60. case '\n': case '\\':
  61. if (!copying)
  62. {
  63. size_t length = (source - string) - 1;
  64. copying = 1;
  65. buffer = xmalloc (length + 2 + 2 * strlen (source) + 1);
  66. memcpy (buffer, string, length);
  67. destination = buffer + length;
  68. }
  69. *destination++ = '\\';
  70. *destination++ = character == '\\' ? '\\' : 'n';
  71. break;
  72. default:
  73. if (copying)
  74. *destination++ = character;
  75. break;
  76. }
  77. }
  78. if (copying)
  79. {
  80. *destination = '\0';
  81. return buffer;
  82. }
  83. return 0;
  84. }
  85. #endif
  86. /* Takes a quoted C string (like those produced by quote_copy_string)
  87. and turns it back into the un-quoted original. This is done in
  88. place. Returns 0 only if the string was not properly quoted, but
  89. completes the unquoting anyway.
  90. This is used for reading the saved directory file in incremental
  91. dumps. It is used for decoding old 'N' records (demangling names).
  92. But also, it is used for decoding file arguments, would they come
  93. from the shell or a -T file, and for decoding the --exclude
  94. argument. */
  95. int
  96. unquote_string (char *string)
  97. {
  98. int result = 1;
  99. char *source = string;
  100. char *destination = string;
  101. /* Escape sequences other than \\ and \n are no longer generated by
  102. quote_copy_string, but accept them for backwards compatibility,
  103. and also because unquote_string is used for purposes other than
  104. parsing the output of quote_copy_string. */
  105. while (*source)
  106. if (*source == '\\')
  107. switch (*++source)
  108. {
  109. case '\\':
  110. *destination++ = '\\';
  111. source++;
  112. break;
  113. case 'a':
  114. *destination++ = '\a';
  115. source++;
  116. break;
  117. case 'b':
  118. *destination++ = '\b';
  119. source++;
  120. break;
  121. case 'f':
  122. *destination++ = '\f';
  123. source++;
  124. break;
  125. case 'n':
  126. *destination++ = '\n';
  127. source++;
  128. break;
  129. case 'r':
  130. *destination++ = '\r';
  131. source++;
  132. break;
  133. case 't':
  134. *destination++ = '\t';
  135. source++;
  136. break;
  137. case 'v':
  138. *destination++ = '\v';
  139. source++;
  140. break;
  141. case '?':
  142. *destination++ = 0177;
  143. source++;
  144. break;
  145. case '0':
  146. case '1':
  147. case '2':
  148. case '3':
  149. case '4':
  150. case '5':
  151. case '6':
  152. case '7':
  153. {
  154. int value = *source++ - '0';
  155. if (*source < '0' || *source > '7')
  156. {
  157. *destination++ = value;
  158. break;
  159. }
  160. value = value * 8 + *source++ - '0';
  161. if (*source < '0' || *source > '7')
  162. {
  163. *destination++ = value;
  164. break;
  165. }
  166. value = value * 8 + *source++ - '0';
  167. *destination++ = value;
  168. break;
  169. }
  170. default:
  171. result = 0;
  172. *destination++ = '\\';
  173. if (*source)
  174. *destination++ = *source++;
  175. break;
  176. }
  177. else if (source != destination)
  178. *destination++ = *source++;
  179. else
  180. source++, destination++;
  181. if (source != destination)
  182. *destination = '\0';
  183. return result;
  184. }
  185. /* Zap trailing slashes. */
  186. char *
  187. zap_slashes (char *name)
  188. {
  189. char *q;
  190. if (!name || *name == 0)
  191. return name;
  192. q = name + strlen (name) - 1;
  193. while (q > name && ISSLASH (*q))
  194. *q-- = '\0';
  195. return name;
  196. }
  197. /* Normalize FILE_NAME by removing redundant slashes and "."
  198. components, including redundant trailing slashes.
  199. Leave ".." alone, as it may be significant in the presence
  200. of symlinks and on platforms where "/.." != "/".
  201. Destructive version: modifies its argument. */
  202. void
  203. normalize_filename_x (char *file_name)
  204. {
  205. char *name = file_name + FILE_SYSTEM_PREFIX_LEN (file_name);
  206. char *p;
  207. char const *q;
  208. char c;
  209. /* Don't squeeze leading "//" to "/", on hosts where they're distinct. */
  210. name += (DOUBLE_SLASH_IS_DISTINCT_ROOT
  211. && ISSLASH (*name) && ISSLASH (name[1]) && ! ISSLASH (name[2]));
  212. /* Omit redundant leading "." components. */
  213. for (q = p = name; (*p = *q) == '.' && ISSLASH (q[1]); p += !*q)
  214. for (q += 2; ISSLASH (*q); q++)
  215. continue;
  216. /* Copy components from Q to P, omitting redundant slashes and
  217. internal "." components. */
  218. while ((*p++ = c = *q++) != '\0')
  219. if (ISSLASH (c))
  220. while (ISSLASH (q[*q == '.']))
  221. q += (*q == '.') + 1;
  222. /* Omit redundant trailing "." component and slash. */
  223. if (2 < p - name)
  224. {
  225. p -= p[-2] == '.' && ISSLASH (p[-3]);
  226. p -= 2 < p - name && ISSLASH (p[-2]);
  227. p[-1] = '\0';
  228. }
  229. }
  230. /* Normalize NAME by removing redundant slashes and "." components,
  231. including redundant trailing slashes.
  232. Return a normalized newly-allocated copy. */
  233. char *
  234. normalize_filename (int cdidx, const char *name)
  235. {
  236. char *copy = NULL;
  237. if (IS_RELATIVE_FILE_NAME (name))
  238. {
  239. /* Set COPY to the absolute path for this name.
  240. FIXME: There should be no need to get the absolute file name.
  241. tar_getcdpath does not return a true "canonical" path, so
  242. this following approach may lead to situations where the same
  243. file or directory is processed twice under different absolute
  244. paths without that duplication being detected. Perhaps we
  245. should use dev+ino pairs instead of names? (See listed03.at for
  246. a related test case.) */
  247. const char *cdpath = tar_getcdpath (cdidx);
  248. size_t copylen;
  249. bool need_separator;
  250. if (!cdpath)
  251. call_arg_fatal ("getcwd", ".");
  252. copylen = strlen (cdpath);
  253. need_separator = ! (DOUBLE_SLASH_IS_DISTINCT_ROOT
  254. && copylen == 2 && ISSLASH (cdpath[1]));
  255. copy = xmalloc (copylen + need_separator + strlen (name) + 1);
  256. strcpy (copy, cdpath);
  257. copy[copylen] = DIRECTORY_SEPARATOR;
  258. strcpy (copy + copylen + need_separator, name);
  259. }
  260. if (!copy)
  261. copy = xstrdup (name);
  262. normalize_filename_x (copy);
  263. return copy;
  264. }
  265. void
  266. replace_prefix (char **pname, const char *samp, size_t slen,
  267. const char *repl, size_t rlen)
  268. {
  269. char *name = *pname;
  270. size_t nlen = strlen (name);
  271. if (nlen > slen && memcmp (name, samp, slen) == 0 && ISSLASH (name[slen]))
  272. {
  273. if (rlen > slen)
  274. {
  275. name = xrealloc (name, nlen - slen + rlen + 1);
  276. *pname = name;
  277. }
  278. memmove (name + rlen, name + slen, nlen - slen + 1);
  279. memcpy (name, repl, rlen);
  280. }
  281. }
  282. /* Handling numbers. */
  283. /* Convert VALUE, which is converted from a system integer type whose
  284. minimum value is MINVAL and maximum MINVAL, to an decimal
  285. integer string. Use the storage in BUF and return a pointer to the
  286. converted string. If VALUE is converted from a negative integer in
  287. the range MINVAL .. -1, represent it with a string representation
  288. of the negative integer, using leading '-'. */
  289. #if ! (INTMAX_MAX <= UINTMAX_MAX / 2)
  290. # error "sysinttostr: uintmax_t cannot represent all intmax_t values"
  291. #endif
  292. char *
  293. sysinttostr (uintmax_t value, intmax_t minval, uintmax_t maxval,
  294. char buf[SYSINT_BUFSIZE])
  295. {
  296. if (value <= maxval)
  297. return umaxtostr (value, buf);
  298. else
  299. {
  300. intmax_t i = value - minval;
  301. return imaxtostr (i + minval, buf);
  302. }
  303. }
  304. /* Convert a prefix of the string ARG to a system integer type whose
  305. minimum value is MINVAL and maximum MAXVAL. If MINVAL is negative,
  306. negative integers MINVAL .. -1 are assumed to be represented using
  307. leading '-' in the usual way. If the represented value exceeds
  308. INTMAX_MAX, return a negative integer V such that (uintmax_t) V
  309. yields the represented value. If ARGLIM is nonnull, store into
  310. *ARGLIM a pointer to the first character after the prefix.
  311. This is the inverse of sysinttostr.
  312. On a normal return, set errno = 0.
  313. On conversion error, return 0 and set errno = EINVAL.
  314. On overflow, return an extreme value and set errno = ERANGE. */
  315. #if ! (INTMAX_MAX <= UINTMAX_MAX)
  316. # error "strtosysint: nonnegative intmax_t does not fit in uintmax_t"
  317. #endif
  318. intmax_t
  319. strtosysint (char const *arg, char **arglim, intmax_t minval, uintmax_t maxval)
  320. {
  321. errno = 0;
  322. if (maxval <= INTMAX_MAX)
  323. {
  324. if (ISDIGIT (arg[*arg == '-']))
  325. {
  326. intmax_t i = strtoimax (arg, arglim, 10);
  327. intmax_t imaxval = maxval;
  328. if (minval <= i && i <= imaxval)
  329. return i;
  330. errno = ERANGE;
  331. return i < minval ? minval : maxval;
  332. }
  333. }
  334. else
  335. {
  336. if (ISDIGIT (*arg))
  337. {
  338. uintmax_t i = strtoumax (arg, arglim, 10);
  339. if (i <= maxval)
  340. return represent_uintmax (i);
  341. errno = ERANGE;
  342. return maxval;
  343. }
  344. }
  345. errno = EINVAL;
  346. return 0;
  347. }
  348. /* Output fraction and trailing digits appropriate for a nanoseconds
  349. count equal to NS, but don't output unnecessary '.' or trailing
  350. zeros. */
  351. void
  352. code_ns_fraction (int ns, char *p)
  353. {
  354. if (ns == 0)
  355. *p = '\0';
  356. else
  357. {
  358. int i = 9;
  359. *p++ = '.';
  360. while (ns % 10 == 0)
  361. {
  362. ns /= 10;
  363. i--;
  364. }
  365. p[i] = '\0';
  366. for (;;)
  367. {
  368. p[--i] = '0' + ns % 10;
  369. if (i == 0)
  370. break;
  371. ns /= 10;
  372. }
  373. }
  374. }
  375. char const *
  376. code_timespec (struct timespec t, char sbuf[TIMESPEC_STRSIZE_BOUND])
  377. {
  378. time_t s = t.tv_sec;
  379. int ns = t.tv_nsec;
  380. char *np;
  381. bool negative = s < 0;
  382. /* ignore invalid values of ns */
  383. if (BILLION <= ns || ns < 0)
  384. ns = 0;
  385. if (negative && ns != 0)
  386. {
  387. s++;
  388. ns = BILLION - ns;
  389. }
  390. np = umaxtostr (negative ? - (uintmax_t) s : (uintmax_t) s, sbuf + 1);
  391. if (negative)
  392. *--np = '-';
  393. code_ns_fraction (ns, sbuf + UINTMAX_STRSIZE_BOUND);
  394. return np;
  395. }
  396. struct timespec
  397. decode_timespec (char const *arg, char **arg_lim, bool parse_fraction)
  398. {
  399. time_t s = TYPE_MINIMUM (time_t);
  400. int ns = -1;
  401. char const *p = arg;
  402. bool negative = *arg == '-';
  403. struct timespec r;
  404. if (! ISDIGIT (arg[negative]))
  405. errno = EINVAL;
  406. else
  407. {
  408. errno = 0;
  409. if (negative)
  410. {
  411. intmax_t i = strtoimax (arg, arg_lim, 10);
  412. if (TYPE_SIGNED (time_t) ? TYPE_MINIMUM (time_t) <= i : 0 <= i)
  413. s = i;
  414. else
  415. errno = ERANGE;
  416. }
  417. else
  418. {
  419. uintmax_t i = strtoumax (arg, arg_lim, 10);
  420. if (i <= TYPE_MAXIMUM (time_t))
  421. s = i;
  422. else
  423. errno = ERANGE;
  424. }
  425. p = *arg_lim;
  426. ns = 0;
  427. if (parse_fraction && *p == '.')
  428. {
  429. int digits = 0;
  430. bool trailing_nonzero = false;
  431. while (ISDIGIT (*++p))
  432. if (digits < LOG10_BILLION)
  433. digits++, ns = 10 * ns + (*p - '0');
  434. else
  435. trailing_nonzero |= *p != '0';
  436. while (digits < LOG10_BILLION)
  437. digits++, ns *= 10;
  438. if (negative)
  439. {
  440. /* Convert "-1.10000000000001" to s == -2, ns == 89999999.
  441. I.e., truncate time stamps towards minus infinity while
  442. converting them to internal form. */
  443. ns += trailing_nonzero;
  444. if (ns != 0)
  445. {
  446. if (s == TYPE_MINIMUM (time_t))
  447. ns = -1;
  448. else
  449. {
  450. s--;
  451. ns = BILLION - ns;
  452. }
  453. }
  454. }
  455. }
  456. if (errno == ERANGE)
  457. ns = -1;
  458. }
  459. *arg_lim = (char *) p;
  460. r.tv_sec = s;
  461. r.tv_nsec = ns;
  462. return r;
  463. }
  464. /* File handling. */
  465. /* Saved names in case backup needs to be undone. */
  466. static char *before_backup_name;
  467. static char *after_backup_name;
  468. /* Return 1 if FILE_NAME is obviously "." or "/". */
  469. bool
  470. must_be_dot_or_slash (char const *file_name)
  471. {
  472. file_name += FILE_SYSTEM_PREFIX_LEN (file_name);
  473. if (ISSLASH (file_name[0]))
  474. {
  475. for (;;)
  476. if (ISSLASH (file_name[1]))
  477. file_name++;
  478. else if (file_name[1] == '.'
  479. && ISSLASH (file_name[2 + (file_name[2] == '.')]))
  480. file_name += 2 + (file_name[2] == '.');
  481. else
  482. return ! file_name[1];
  483. }
  484. else
  485. {
  486. while (file_name[0] == '.' && ISSLASH (file_name[1]))
  487. {
  488. file_name += 2;
  489. while (ISSLASH (*file_name))
  490. file_name++;
  491. }
  492. return ! file_name[0] || (file_name[0] == '.' && ! file_name[1]);
  493. }
  494. }
  495. /* Some implementations of rmdir let you remove '.' or '/'.
  496. Report an error with errno set to zero for obvious cases of this;
  497. otherwise call rmdir. */
  498. static int
  499. safer_rmdir (const char *file_name)
  500. {
  501. if (must_be_dot_or_slash (file_name))
  502. {
  503. errno = 0;
  504. return -1;
  505. }
  506. if (unlinkat (chdir_fd, file_name, AT_REMOVEDIR) == 0)
  507. {
  508. remove_delayed_set_stat (file_name);
  509. return 0;
  510. }
  511. return -1;
  512. }
  513. /* Remove FILE_NAME, returning 1 on success. If FILE_NAME is a directory,
  514. then if OPTION is RECURSIVE_REMOVE_OPTION is set remove FILE_NAME
  515. recursively; otherwise, remove it only if it is empty. If FILE_NAME is
  516. a directory that cannot be removed (e.g., because it is nonempty)
  517. and if OPTION is WANT_DIRECTORY_REMOVE_OPTION, then return -1.
  518. Return 0 on error, with errno set; if FILE_NAME is obviously the working
  519. directory return zero with errno set to zero. */
  520. int
  521. remove_any_file (const char *file_name, enum remove_option option)
  522. {
  523. /* Try unlink first if we cannot unlink directories, as this saves
  524. us a system call in the common case where we're removing a
  525. non-directory. */
  526. bool try_unlink_first = cannot_unlink_dir ();
  527. if (try_unlink_first)
  528. {
  529. if (unlinkat (chdir_fd, file_name, 0) == 0)
  530. return 1;
  531. /* POSIX 1003.1-2001 requires EPERM when attempting to unlink a
  532. directory without appropriate privileges, but many Linux
  533. kernels return the more-sensible EISDIR. */
  534. if (errno != EPERM && errno != EISDIR)
  535. return 0;
  536. }
  537. if (safer_rmdir (file_name) == 0)
  538. return 1;
  539. switch (errno)
  540. {
  541. case ENOTDIR:
  542. return !try_unlink_first && unlinkat (chdir_fd, file_name, 0) == 0;
  543. case 0:
  544. case EEXIST:
  545. #if defined ENOTEMPTY && ENOTEMPTY != EEXIST
  546. case ENOTEMPTY:
  547. #endif
  548. switch (option)
  549. {
  550. case ORDINARY_REMOVE_OPTION:
  551. break;
  552. case WANT_DIRECTORY_REMOVE_OPTION:
  553. return -1;
  554. case RECURSIVE_REMOVE_OPTION:
  555. {
  556. char *directory = tar_savedir (file_name, 0);
  557. char const *entry;
  558. size_t entrylen;
  559. if (! directory)
  560. return 0;
  561. for (entry = directory;
  562. (entrylen = strlen (entry)) != 0;
  563. entry += entrylen + 1)
  564. {
  565. char *file_name_buffer = new_name (file_name, entry);
  566. int r = remove_any_file (file_name_buffer,
  567. RECURSIVE_REMOVE_OPTION);
  568. int e = errno;
  569. free (file_name_buffer);
  570. if (! r)
  571. {
  572. free (directory);
  573. errno = e;
  574. return 0;
  575. }
  576. }
  577. free (directory);
  578. return safer_rmdir (file_name) == 0;
  579. }
  580. }
  581. break;
  582. }
  583. return 0;
  584. }
  585. /* Check if FILE_NAME already exists and make a backup of it right now.
  586. Return success (nonzero) only if the backup is either unneeded, or
  587. successful. For now, directories are considered to never need
  588. backup. If THIS_IS_THE_ARCHIVE is nonzero, this is the archive and
  589. so, we do not have to backup block or character devices, nor remote
  590. entities. */
  591. bool
  592. maybe_backup_file (const char *file_name, bool this_is_the_archive)
  593. {
  594. struct stat file_stat;
  595. assign_string (&before_backup_name, file_name);
  596. /* A run situation may exist between Emacs or other GNU programs trying to
  597. make a backup for the same file simultaneously. If theoretically
  598. possible, real problems are unlikely. Doing any better would require a
  599. convention, GNU-wide, for all programs doing backups. */
  600. assign_string (&after_backup_name, 0);
  601. /* Check if we really need to backup the file. */
  602. if (this_is_the_archive && _remdev (file_name))
  603. return true;
  604. if (deref_stat (file_name, &file_stat) != 0)
  605. {
  606. if (errno == ENOENT)
  607. return true;
  608. stat_error (file_name);
  609. return false;
  610. }
  611. if (S_ISDIR (file_stat.st_mode))
  612. return true;
  613. if (this_is_the_archive
  614. && (S_ISBLK (file_stat.st_mode) || S_ISCHR (file_stat.st_mode)))
  615. return true;
  616. after_backup_name = find_backup_file_name (file_name, backup_type);
  617. if (! after_backup_name)
  618. xalloc_die ();
  619. if (renameat (chdir_fd, before_backup_name, chdir_fd, after_backup_name)
  620. == 0)
  621. {
  622. if (verbose_option)
  623. fprintf (stdlis, _("Renaming %s to %s\n"),
  624. quote_n (0, before_backup_name),
  625. quote_n (1, after_backup_name));
  626. return true;
  627. }
  628. else
  629. {
  630. /* The backup operation failed. */
  631. int e = errno;
  632. ERROR ((0, e, _("%s: Cannot rename to %s"),
  633. quotearg_colon (before_backup_name),
  634. quote_n (1, after_backup_name)));
  635. assign_string (&after_backup_name, 0);
  636. return false;
  637. }
  638. }
  639. /* Try to restore the recently backed up file to its original name.
  640. This is usually only needed after a failed extraction. */
  641. void
  642. undo_last_backup (void)
  643. {
  644. if (after_backup_name)
  645. {
  646. if (renameat (chdir_fd, after_backup_name, chdir_fd, before_backup_name)
  647. != 0)
  648. {
  649. int e = errno;
  650. ERROR ((0, e, _("%s: Cannot rename to %s"),
  651. quotearg_colon (after_backup_name),
  652. quote_n (1, before_backup_name)));
  653. }
  654. if (verbose_option)
  655. fprintf (stdlis, _("Renaming %s back to %s\n"),
  656. quote_n (0, after_backup_name),
  657. quote_n (1, before_backup_name));
  658. assign_string (&after_backup_name, 0);
  659. }
  660. }
  661. /* Apply either stat or lstat to (NAME, BUF), depending on the
  662. presence of the --dereference option. NAME is relative to the
  663. most-recent argument to chdir_do. */
  664. int
  665. deref_stat (char const *name, struct stat *buf)
  666. {
  667. return fstatat (chdir_fd, name, buf, fstatat_flags);
  668. }
  669. /* Read from FD into the buffer BUF with COUNT bytes. Attempt to fill
  670. BUF. Wait until input is available; this matters because files are
  671. opened O_NONBLOCK for security reasons, and on some file systems
  672. this can cause read to fail with errno == EAGAIN. Return the
  673. actual number of bytes read, zero for EOF, or
  674. SAFE_READ_ERROR upon error. */
  675. size_t
  676. blocking_read (int fd, void *buf, size_t count)
  677. {
  678. size_t bytes = safe_read (fd, buf, count);
  679. #if defined F_SETFL && O_NONBLOCK
  680. if (bytes == SAFE_READ_ERROR && errno == EAGAIN)
  681. {
  682. int flags = fcntl (fd, F_GETFL);
  683. if (0 <= flags && flags & O_NONBLOCK
  684. && fcntl (fd, F_SETFL, flags & ~O_NONBLOCK) != -1)
  685. bytes = safe_read (fd, buf, count);
  686. }
  687. #endif
  688. return bytes;
  689. }
  690. /* Write to FD from the buffer BUF with COUNT bytes. Do a full write.
  691. Wait until an output buffer is available; this matters because
  692. files are opened O_NONBLOCK for security reasons, and on some file
  693. systems this can cause write to fail with errno == EAGAIN. Return
  694. the actual number of bytes written, setting errno if that is less
  695. than COUNT. */
  696. size_t
  697. blocking_write (int fd, void const *buf, size_t count)
  698. {
  699. size_t bytes = full_write (fd, buf, count);
  700. #if defined F_SETFL && O_NONBLOCK
  701. if (bytes < count && errno == EAGAIN)
  702. {
  703. int flags = fcntl (fd, F_GETFL);
  704. if (0 <= flags && flags & O_NONBLOCK
  705. && fcntl (fd, F_SETFL, flags & ~O_NONBLOCK) != -1)
  706. {
  707. char const *buffer = buf;
  708. bytes += full_write (fd, buffer + bytes, count - bytes);
  709. }
  710. }
  711. #endif
  712. return bytes;
  713. }
  714. /* Set FD's (i.e., assuming the working directory is PARENTFD, FILE's)
  715. access time to ATIME. */
  716. int
  717. set_file_atime (int fd, int parentfd, char const *file, struct timespec atime)
  718. {
  719. struct timespec ts[2];
  720. ts[0] = atime;
  721. ts[1].tv_nsec = UTIME_OMIT;
  722. return fdutimensat (fd, parentfd, file, ts, fstatat_flags);
  723. }
  724. /* A description of a working directory. */
  725. struct wd
  726. {
  727. /* The directory's name. */
  728. char const *name;
  729. /* "Absolute" path representing this directory; in the contrast to
  730. the real absolute pathname, it can contain /../ components (see
  731. normalize_filename_x for the reason of it). It is NULL if the
  732. absolute path could not be determined. */
  733. char *abspath;
  734. /* If nonzero, the file descriptor of the directory, or AT_FDCWD if
  735. the working directory. If zero, the directory needs to be opened
  736. to be used. */
  737. int fd;
  738. };
  739. /* A vector of chdir targets. wd[0] is the initial working directory. */
  740. static struct wd *wd;
  741. /* The number of working directories in the vector. */
  742. static size_t wd_count;
  743. /* The allocated size of the vector. */
  744. static size_t wd_alloc;
  745. /* The maximum number of chdir targets with open directories.
  746. Don't make it too large, as many operating systems have a small
  747. limit on the number of open file descriptors. Also, the current
  748. implementation does not scale well. */
  749. enum { CHDIR_CACHE_SIZE = 16 };
  750. /* Indexes into WD of chdir targets with open file descriptors, sorted
  751. most-recently used first. Zero indexes are unused. */
  752. static int wdcache[CHDIR_CACHE_SIZE];
  753. /* Number of nonzero entries in WDCACHE. */
  754. static size_t wdcache_count;
  755. int
  756. chdir_count (void)
  757. {
  758. if (wd_count == 0)
  759. return wd_count;
  760. return wd_count - 1;
  761. }
  762. /* DIR is the operand of a -C option; add it to vector of chdir targets,
  763. and return the index of its location. */
  764. int
  765. chdir_arg (char const *dir)
  766. {
  767. char *absdir;
  768. if (wd_count == wd_alloc)
  769. {
  770. if (wd_alloc == 0)
  771. wd_alloc = 2;
  772. wd = x2nrealloc (wd, &wd_alloc, sizeof *wd);
  773. if (! wd_count)
  774. {
  775. wd[wd_count].name = ".";
  776. wd[wd_count].abspath = xgetcwd ();
  777. wd[wd_count].fd = AT_FDCWD;
  778. wd_count++;
  779. }
  780. }
  781. /* Optimize the common special case of the working directory,
  782. or the working directory as a prefix. */
  783. if (dir[0])
  784. {
  785. while (dir[0] == '.' && ISSLASH (dir[1]))
  786. for (dir += 2; ISSLASH (*dir); dir++)
  787. continue;
  788. if (! dir[dir[0] == '.'])
  789. return wd_count - 1;
  790. }
  791. /* If the given name is absolute, use it to represent this directory;
  792. otherwise, construct a name based on the previous -C option. */
  793. if (IS_ABSOLUTE_FILE_NAME (dir))
  794. absdir = xstrdup (dir);
  795. else if (wd[wd_count - 1].abspath)
  796. {
  797. namebuf_t nbuf = namebuf_create (wd[wd_count - 1].abspath);
  798. namebuf_add_dir (nbuf, dir);
  799. absdir = namebuf_finish (nbuf);
  800. }
  801. else
  802. absdir = 0;
  803. wd[wd_count].name = dir;
  804. wd[wd_count].abspath = absdir;
  805. wd[wd_count].fd = 0;
  806. return wd_count++;
  807. }
  808. /* Index of current directory. */
  809. int chdir_current;
  810. /* Value suitable for use as the first argument to openat, and in
  811. similar locations for fstatat, etc. This is an open file
  812. descriptor, or AT_FDCWD if the working directory is current. It is
  813. valid until the next invocation of chdir_do. */
  814. int chdir_fd = AT_FDCWD;
  815. /* Change to directory I, in a virtual way. This does not actually
  816. invoke chdir; it merely sets chdir_fd to an int suitable as the
  817. first argument for openat, etc. If I is 0, change to the initial
  818. working directory; otherwise, I must be a value returned by
  819. chdir_arg. */
  820. void
  821. chdir_do (int i)
  822. {
  823. if (chdir_current != i)
  824. {
  825. struct wd *curr = &wd[i];
  826. int fd = curr->fd;
  827. if (! fd)
  828. {
  829. if (! IS_ABSOLUTE_FILE_NAME (curr->name))
  830. chdir_do (i - 1);
  831. fd = openat (chdir_fd, curr->name,
  832. open_searchdir_flags & ~ O_NOFOLLOW);
  833. if (fd < 0)
  834. open_fatal (curr->name);
  835. curr->fd = fd;
  836. /* Add I to the cache, tossing out the lowest-ranking entry if the
  837. cache is full. */
  838. if (wdcache_count < CHDIR_CACHE_SIZE)
  839. wdcache[wdcache_count++] = i;
  840. else
  841. {
  842. struct wd *stale = &wd[wdcache[CHDIR_CACHE_SIZE - 1]];
  843. if (close (stale->fd) != 0)
  844. close_diag (stale->name);
  845. stale->fd = 0;
  846. wdcache[CHDIR_CACHE_SIZE - 1] = i;
  847. }
  848. }
  849. if (0 < fd)
  850. {
  851. /* Move the i value to the front of the cache. This is
  852. O(CHDIR_CACHE_SIZE), but the cache is small. */
  853. size_t ci;
  854. int prev = wdcache[0];
  855. for (ci = 1; prev != i; ci++)
  856. {
  857. int cur = wdcache[ci];
  858. wdcache[ci] = prev;
  859. if (cur == i)
  860. break;
  861. prev = cur;
  862. }
  863. wdcache[0] = i;
  864. }
  865. chdir_current = i;
  866. chdir_fd = fd;
  867. }
  868. }
  869. const char *
  870. tar_dirname (void)
  871. {
  872. return wd[chdir_current].name;
  873. }
  874. /* Return the absolute path that represents the working
  875. directory referenced by IDX.
  876. If wd is empty, then there were no -C options given, and
  877. chdir_args() has never been called, so we simply return the
  878. process's actual cwd. (Note that in this case IDX is ignored,
  879. since it should always be 0.) */
  880. static const char *
  881. tar_getcdpath (int idx)
  882. {
  883. if (!wd)
  884. {
  885. static char *cwd;
  886. if (!cwd)
  887. cwd = xgetcwd ();
  888. return cwd;
  889. }
  890. return wd[idx].abspath;
  891. }
  892. void
  893. close_diag (char const *name)
  894. {
  895. if (ignore_failed_read_option)
  896. close_warn (name);
  897. else
  898. close_error (name);
  899. }
  900. void
  901. open_diag (char const *name)
  902. {
  903. if (ignore_failed_read_option)
  904. open_warn (name);
  905. else
  906. open_error (name);
  907. }
  908. void
  909. read_diag_details (char const *name, off_t offset, size_t size)
  910. {
  911. if (ignore_failed_read_option)
  912. read_warn_details (name, offset, size);
  913. else
  914. read_error_details (name, offset, size);
  915. }
  916. void
  917. readlink_diag (char const *name)
  918. {
  919. if (ignore_failed_read_option)
  920. readlink_warn (name);
  921. else
  922. readlink_error (name);
  923. }
  924. void
  925. savedir_diag (char const *name)
  926. {
  927. if (ignore_failed_read_option)
  928. savedir_warn (name);
  929. else
  930. savedir_error (name);
  931. }
  932. void
  933. seek_diag_details (char const *name, off_t offset)
  934. {
  935. if (ignore_failed_read_option)
  936. seek_warn_details (name, offset);
  937. else
  938. seek_error_details (name, offset);
  939. }
  940. void
  941. stat_diag (char const *name)
  942. {
  943. if (ignore_failed_read_option)
  944. stat_warn (name);
  945. else
  946. stat_error (name);
  947. }
  948. void
  949. file_removed_diag (const char *name, bool top_level,
  950. void (*diagfn) (char const *name))
  951. {
  952. if (!top_level && errno == ENOENT)
  953. {
  954. WARNOPT (WARN_FILE_REMOVED,
  955. (0, 0, _("%s: File removed before we read it"),
  956. quotearg_colon (name)));
  957. set_exit_status (TAREXIT_DIFFERS);
  958. }
  959. else
  960. diagfn (name);
  961. }
  962. void
  963. write_fatal_details (char const *name, ssize_t status, size_t size)
  964. {
  965. write_error_details (name, status, size);
  966. fatal_exit ();
  967. }
  968. /* Fork, aborting if unsuccessful. */
  969. pid_t
  970. xfork (void)
  971. {
  972. pid_t p = fork ();
  973. if (p == (pid_t) -1)
  974. call_arg_fatal ("fork", _("child process"));
  975. return p;
  976. }
  977. /* Create a pipe, aborting if unsuccessful. */
  978. void
  979. xpipe (int fd[2])
  980. {
  981. if (pipe (fd) < 0)
  982. call_arg_fatal ("pipe", _("interprocess channel"));
  983. }
  984. /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
  985. ALIGNMENT must be nonzero. The caller must arrange for ((char *)
  986. PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
  987. locations. */
  988. static inline void *
  989. ptr_align (void *ptr, size_t alignment)
  990. {
  991. char *p0 = ptr;
  992. char *p1 = p0 + alignment - 1;
  993. return p1 - (size_t) p1 % alignment;
  994. }
  995. /* Return the address of a page-aligned buffer of at least SIZE bytes.
  996. The caller should free *PTR when done with the buffer. */
  997. void *
  998. page_aligned_alloc (void **ptr, size_t size)
  999. {
  1000. size_t alignment = getpagesize ();
  1001. size_t size1 = size + alignment;
  1002. if (size1 < size)
  1003. xalloc_die ();
  1004. *ptr = xmalloc (size1);
  1005. return ptr_align (*ptr, alignment);
  1006. }
  1007. struct namebuf
  1008. {
  1009. char *buffer; /* directory, '/', and directory member */
  1010. size_t buffer_size; /* allocated size of name_buffer */
  1011. size_t dir_length; /* length of directory part in buffer */
  1012. };
  1013. namebuf_t
  1014. namebuf_create (const char *dir)
  1015. {
  1016. namebuf_t buf = xmalloc (sizeof (*buf));
  1017. buf->buffer_size = strlen (dir) + 2;
  1018. buf->buffer = xmalloc (buf->buffer_size);
  1019. strcpy (buf->buffer, dir);
  1020. buf->dir_length = strlen (buf->buffer);
  1021. if (!ISSLASH (buf->buffer[buf->dir_length - 1]))
  1022. buf->buffer[buf->dir_length++] = DIRECTORY_SEPARATOR;
  1023. return buf;
  1024. }
  1025. void
  1026. namebuf_free (namebuf_t buf)
  1027. {
  1028. free (buf->buffer);
  1029. free (buf);
  1030. }
  1031. char *
  1032. namebuf_name (namebuf_t buf, const char *name)
  1033. {
  1034. size_t len = strlen (name);
  1035. while (buf->dir_length + len + 1 >= buf->buffer_size)
  1036. buf->buffer = x2realloc (buf->buffer, &buf->buffer_size);
  1037. strcpy (buf->buffer + buf->dir_length, name);
  1038. return buf->buffer;
  1039. }
  1040. void
  1041. namebuf_add_dir (namebuf_t buf, const char *name)
  1042. {
  1043. static char dirsep[] = { DIRECTORY_SEPARATOR, 0 };
  1044. if (!ISSLASH (buf->buffer[buf->dir_length - 1]))
  1045. {
  1046. namebuf_name (buf, dirsep);
  1047. buf->dir_length++;
  1048. }
  1049. namebuf_name (buf, name);
  1050. buf->dir_length += strlen (name);
  1051. }
  1052. char *
  1053. namebuf_finish (namebuf_t buf)
  1054. {
  1055. char *res = buf->buffer;
  1056. if (ISSLASH (buf->buffer[buf->dir_length - 1]))
  1057. buf->buffer[buf->dir_length] = 0;
  1058. free (buf);
  1059. return res;
  1060. }
  1061. /* Return the filenames in directory NAME, relative to the chdir_fd.
  1062. If the directory does not exist, report error if MUST_EXIST is
  1063. true.
  1064. Return NULL on errors.
  1065. */
  1066. char *
  1067. tar_savedir (const char *name, int must_exist)
  1068. {
  1069. char *ret = NULL;
  1070. DIR *dir = NULL;
  1071. int fd = openat (chdir_fd, name, open_read_flags | O_DIRECTORY);
  1072. if (fd < 0)
  1073. {
  1074. if (!must_exist && errno == ENOENT)
  1075. return NULL;
  1076. open_error (name);
  1077. }
  1078. else if (! ((dir = fdopendir (fd))
  1079. && (ret = streamsavedir (dir, savedir_sort_order))))
  1080. savedir_error (name);
  1081. if (dir ? closedir (dir) != 0 : 0 <= fd && close (fd) != 0)
  1082. savedir_error (name);
  1083. return ret;
  1084. }