misc.c 31 KB

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