misc.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. /* Miscellaneous functions, not really specific to GNU tar.
  2. Copyright (C) 1988, 1992, 1994, 1995, 1996, 1997, 1999, 2000, 2001,
  3. 2003, 2004, 2005, 2006, 2007, 2009, 2010 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, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  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. /* Handling strings. */
  26. /* Assign STRING to a copy of VALUE if not zero, or to zero. If
  27. STRING was nonzero, it is freed first. */
  28. void
  29. assign_string (char **string, const char *value)
  30. {
  31. free (*string);
  32. *string = value ? xstrdup (value) : 0;
  33. }
  34. #if 0
  35. /* This function is currently unused; perhaps it should be removed? */
  36. /* Allocate a copy of the string quoted as in C, and returns that. If
  37. the string does not have to be quoted, it returns a null pointer.
  38. The allocated copy should normally be freed with free() after the
  39. caller is done with it.
  40. This is used in one context only: generating the directory file in
  41. incremental dumps. The quoted string is not intended for human
  42. consumption; it is intended only for unquote_string. The quoting
  43. is locale-independent, so that users needn't worry about locale
  44. when reading directory files. This means that we can't use
  45. quotearg, as quotearg is locale-dependent and is meant for human
  46. consumption. */
  47. static char *
  48. quote_copy_string (const char *string)
  49. {
  50. const char *source = string;
  51. char *destination = 0;
  52. char *buffer = 0;
  53. int copying = 0;
  54. while (*source)
  55. {
  56. int character = *source++;
  57. switch (character)
  58. {
  59. case '\n': case '\\':
  60. if (!copying)
  61. {
  62. size_t length = (source - string) - 1;
  63. copying = 1;
  64. buffer = xmalloc (length + 2 + 2 * strlen (source) + 1);
  65. memcpy (buffer, string, length);
  66. destination = buffer + length;
  67. }
  68. *destination++ = '\\';
  69. *destination++ = character == '\\' ? '\\' : 'n';
  70. break;
  71. default:
  72. if (copying)
  73. *destination++ = character;
  74. break;
  75. }
  76. }
  77. if (copying)
  78. {
  79. *destination = '\0';
  80. return buffer;
  81. }
  82. return 0;
  83. }
  84. #endif
  85. /* Takes a quoted C string (like those produced by quote_copy_string)
  86. and turns it back into the un-quoted original. This is done in
  87. place. Returns 0 only if the string was not properly quoted, but
  88. completes the unquoting anyway.
  89. This is used for reading the saved directory file in incremental
  90. dumps. It is used for decoding old 'N' records (demangling names).
  91. But also, it is used for decoding file arguments, would they come
  92. from the shell or a -T file, and for decoding the --exclude
  93. argument. */
  94. int
  95. unquote_string (char *string)
  96. {
  97. int result = 1;
  98. char *source = string;
  99. char *destination = string;
  100. /* Escape sequences other than \\ and \n are no longer generated by
  101. quote_copy_string, but accept them for backwards compatibility,
  102. and also because unquote_string is used for purposes other than
  103. parsing the output of quote_copy_string. */
  104. while (*source)
  105. if (*source == '\\')
  106. switch (*++source)
  107. {
  108. case '\\':
  109. *destination++ = '\\';
  110. source++;
  111. break;
  112. case 'a':
  113. *destination++ = '\a';
  114. source++;
  115. break;
  116. case 'b':
  117. *destination++ = '\b';
  118. source++;
  119. break;
  120. case 'f':
  121. *destination++ = '\f';
  122. source++;
  123. break;
  124. case 'n':
  125. *destination++ = '\n';
  126. source++;
  127. break;
  128. case 'r':
  129. *destination++ = '\r';
  130. source++;
  131. break;
  132. case 't':
  133. *destination++ = '\t';
  134. source++;
  135. break;
  136. case 'v':
  137. *destination++ = '\v';
  138. source++;
  139. break;
  140. case '?':
  141. *destination++ = 0177;
  142. source++;
  143. break;
  144. case '0':
  145. case '1':
  146. case '2':
  147. case '3':
  148. case '4':
  149. case '5':
  150. case '6':
  151. case '7':
  152. {
  153. int value = *source++ - '0';
  154. if (*source < '0' || *source > '7')
  155. {
  156. *destination++ = value;
  157. break;
  158. }
  159. value = value * 8 + *source++ - '0';
  160. if (*source < '0' || *source > '7')
  161. {
  162. *destination++ = value;
  163. break;
  164. }
  165. value = value * 8 + *source++ - '0';
  166. *destination++ = value;
  167. break;
  168. }
  169. default:
  170. result = 0;
  171. *destination++ = '\\';
  172. if (*source)
  173. *destination++ = *source++;
  174. break;
  175. }
  176. else if (source != destination)
  177. *destination++ = *source++;
  178. else
  179. source++, destination++;
  180. if (source != destination)
  181. *destination = '\0';
  182. return result;
  183. }
  184. /* Zap trailing slashes. */
  185. char *
  186. zap_slashes (char *name)
  187. {
  188. char *q;
  189. if (!name || *name == 0)
  190. return name;
  191. q = name + strlen (name) - 1;
  192. while (q > name && ISSLASH (*q))
  193. *q-- = '\0';
  194. return name;
  195. }
  196. /* Normalize FILE_NAME by removing redundant slashes and "."
  197. components, including redundant trailing slashes. Leave ".."
  198. alone, as it may be significant in the presence of symlinks and on
  199. platforms where "/.." != "/". Destructive version: modifies its
  200. argument. */
  201. static void
  202. normalize_filename_x (char *file_name)
  203. {
  204. char *name = file_name + FILE_SYSTEM_PREFIX_LEN (file_name);
  205. char *p;
  206. char const *q;
  207. char c;
  208. /* Don't squeeze leading "//" to "/", on hosts where they're distinct. */
  209. name += (DOUBLE_SLASH_IS_DISTINCT_ROOT
  210. && ISSLASH (*name) && ISSLASH (name[1]) && ! ISSLASH (name[2]));
  211. /* Omit redundant leading "." components. */
  212. for (q = p = name; (*p = *q) == '.' && ISSLASH (q[1]); p += !*q)
  213. for (q += 2; ISSLASH (*q); q++)
  214. continue;
  215. /* Copy components from Q to P, omitting redundant slashes and
  216. internal "." components. */
  217. while ((*p++ = c = *q++) != '\0')
  218. if (ISSLASH (c))
  219. while (ISSLASH (q[*q == '.']))
  220. q += (*q == '.') + 1;
  221. /* Omit redundant trailing "." component and slash. */
  222. if (2 < p - name)
  223. {
  224. p -= p[-2] == '.' && ISSLASH (p[-3]);
  225. p -= 2 < p - name && ISSLASH (p[-2]);
  226. p[-1] = '\0';
  227. }
  228. }
  229. /* Normalize NAME by removing redundant slashes and "." components,
  230. including redundant trailing slashes. Return a normalized
  231. newly-allocated copy. */
  232. char *
  233. normalize_filename (const char *name)
  234. {
  235. char *copy = NULL;
  236. if (IS_RELATIVE_FILE_NAME (name))
  237. {
  238. /* Set COPY to the absolute file name if possible.
  239. FIXME: There should be no need to get the absolute file name.
  240. getcwd is slow, it might fail, and it does not necessarily
  241. return a canonical name even when it succeeds. Perhaps we
  242. can use dev+ino pairs instead of names? */
  243. copy = xgetcwd ();
  244. if (copy)
  245. {
  246. size_t copylen = strlen (copy);
  247. bool need_separator = ! (DOUBLE_SLASH_IS_DISTINCT_ROOT
  248. && copylen == 2 && ISSLASH (copy[1]));
  249. copy = xrealloc (copy, copylen + need_separator + strlen (name) + 1);
  250. copy[copylen] = DIRECTORY_SEPARATOR;
  251. strcpy (copy + copylen + need_separator, name);
  252. }
  253. else
  254. WARN ((0, errno, _("Cannot get working directory")));
  255. }
  256. if (! copy)
  257. copy = xstrdup (name);
  258. normalize_filename_x (copy);
  259. return copy;
  260. }
  261. void
  262. replace_prefix (char **pname, const char *samp, size_t slen,
  263. const char *repl, size_t rlen)
  264. {
  265. char *name = *pname;
  266. size_t nlen = strlen (name);
  267. if (nlen > slen && memcmp (name, samp, slen) == 0 && ISSLASH (name[slen]))
  268. {
  269. if (rlen > slen)
  270. {
  271. name = xrealloc (name, nlen - slen + rlen + 1);
  272. *pname = name;
  273. }
  274. memmove (name + rlen, name + slen, nlen - slen + 1);
  275. memcpy (name, repl, rlen);
  276. }
  277. }
  278. /* Handling numbers. */
  279. /* Output fraction and trailing digits appropriate for a nanoseconds
  280. count equal to NS, but don't output unnecessary '.' or trailing
  281. zeros. */
  282. void
  283. code_ns_fraction (int ns, char *p)
  284. {
  285. if (ns == 0)
  286. *p = '\0';
  287. else
  288. {
  289. int i = 9;
  290. *p++ = '.';
  291. while (ns % 10 == 0)
  292. {
  293. ns /= 10;
  294. i--;
  295. }
  296. p[i] = '\0';
  297. for (;;)
  298. {
  299. p[--i] = '0' + ns % 10;
  300. if (i == 0)
  301. break;
  302. ns /= 10;
  303. }
  304. }
  305. }
  306. char const *
  307. code_timespec (struct timespec t, char sbuf[TIMESPEC_STRSIZE_BOUND])
  308. {
  309. time_t s = t.tv_sec;
  310. int ns = t.tv_nsec;
  311. char *np;
  312. bool negative = s < 0;
  313. /* ignore invalid values of ns */
  314. if (BILLION <= ns || ns < 0)
  315. ns = 0;
  316. if (negative && ns != 0)
  317. {
  318. s++;
  319. ns = BILLION - ns;
  320. }
  321. np = umaxtostr (negative ? - (uintmax_t) s : (uintmax_t) s, sbuf + 1);
  322. if (negative)
  323. *--np = '-';
  324. code_ns_fraction (ns, sbuf + UINTMAX_STRSIZE_BOUND);
  325. return np;
  326. }
  327. /* File handling. */
  328. /* Saved names in case backup needs to be undone. */
  329. static char *before_backup_name;
  330. static char *after_backup_name;
  331. /* Return 1 if FILE_NAME is obviously "." or "/". */
  332. bool
  333. must_be_dot_or_slash (char const *file_name)
  334. {
  335. file_name += FILE_SYSTEM_PREFIX_LEN (file_name);
  336. if (ISSLASH (file_name[0]))
  337. {
  338. for (;;)
  339. if (ISSLASH (file_name[1]))
  340. file_name++;
  341. else if (file_name[1] == '.'
  342. && ISSLASH (file_name[2 + (file_name[2] == '.')]))
  343. file_name += 2 + (file_name[2] == '.');
  344. else
  345. return ! file_name[1];
  346. }
  347. else
  348. {
  349. while (file_name[0] == '.' && ISSLASH (file_name[1]))
  350. {
  351. file_name += 2;
  352. while (ISSLASH (*file_name))
  353. file_name++;
  354. }
  355. return ! file_name[0] || (file_name[0] == '.' && ! file_name[1]);
  356. }
  357. }
  358. /* Some implementations of rmdir let you remove '.' or '/'.
  359. Report an error with errno set to zero for obvious cases of this;
  360. otherwise call rmdir. */
  361. static int
  362. safer_rmdir (const char *file_name)
  363. {
  364. if (must_be_dot_or_slash (file_name))
  365. {
  366. errno = 0;
  367. return -1;
  368. }
  369. return unlinkat (chdir_fd, file_name, AT_REMOVEDIR);
  370. }
  371. /* Remove FILE_NAME, returning 1 on success. If FILE_NAME is a directory,
  372. then if OPTION is RECURSIVE_REMOVE_OPTION is set remove FILE_NAME
  373. recursively; otherwise, remove it only if it is empty. If FILE_NAME is
  374. a directory that cannot be removed (e.g., because it is nonempty)
  375. and if OPTION is WANT_DIRECTORY_REMOVE_OPTION, then return -1.
  376. Return 0 on error, with errno set; if FILE_NAME is obviously the working
  377. directory return zero with errno set to zero. */
  378. int
  379. remove_any_file (const char *file_name, enum remove_option option)
  380. {
  381. /* Try unlink first if we cannot unlink directories, as this saves
  382. us a system call in the common case where we're removing a
  383. non-directory. */
  384. bool try_unlink_first = cannot_unlink_dir ();
  385. if (try_unlink_first)
  386. {
  387. if (unlinkat (chdir_fd, file_name, 0) == 0)
  388. return 1;
  389. /* POSIX 1003.1-2001 requires EPERM when attempting to unlink a
  390. directory without appropriate privileges, but many Linux
  391. kernels return the more-sensible EISDIR. */
  392. if (errno != EPERM && errno != EISDIR)
  393. return 0;
  394. }
  395. if (safer_rmdir (file_name) == 0)
  396. return 1;
  397. switch (errno)
  398. {
  399. case ENOTDIR:
  400. return !try_unlink_first && unlinkat (chdir_fd, file_name, 0) == 0;
  401. case 0:
  402. case EEXIST:
  403. #if defined ENOTEMPTY && ENOTEMPTY != EEXIST
  404. case ENOTEMPTY:
  405. #endif
  406. switch (option)
  407. {
  408. case ORDINARY_REMOVE_OPTION:
  409. break;
  410. case WANT_DIRECTORY_REMOVE_OPTION:
  411. return -1;
  412. case RECURSIVE_REMOVE_OPTION:
  413. {
  414. char *directory = savedir (file_name);
  415. char const *entry;
  416. size_t entrylen;
  417. if (! directory)
  418. return 0;
  419. for (entry = directory;
  420. (entrylen = strlen (entry)) != 0;
  421. entry += entrylen + 1)
  422. {
  423. char *file_name_buffer = new_name (file_name, entry);
  424. int r = remove_any_file (file_name_buffer,
  425. RECURSIVE_REMOVE_OPTION);
  426. int e = errno;
  427. free (file_name_buffer);
  428. if (! r)
  429. {
  430. free (directory);
  431. errno = e;
  432. return 0;
  433. }
  434. }
  435. free (directory);
  436. return safer_rmdir (file_name) == 0;
  437. }
  438. }
  439. break;
  440. }
  441. return 0;
  442. }
  443. /* Check if FILE_NAME already exists and make a backup of it right now.
  444. Return success (nonzero) only if the backup is either unneeded, or
  445. successful. For now, directories are considered to never need
  446. backup. If THIS_IS_THE_ARCHIVE is nonzero, this is the archive and
  447. so, we do not have to backup block or character devices, nor remote
  448. entities. */
  449. bool
  450. maybe_backup_file (const char *file_name, bool this_is_the_archive)
  451. {
  452. struct stat file_stat;
  453. assign_string (&before_backup_name, file_name);
  454. /* A run situation may exist between Emacs or other GNU programs trying to
  455. make a backup for the same file simultaneously. If theoretically
  456. possible, real problems are unlikely. Doing any better would require a
  457. convention, GNU-wide, for all programs doing backups. */
  458. assign_string (&after_backup_name, 0);
  459. /* Check if we really need to backup the file. */
  460. if (this_is_the_archive && _remdev (file_name))
  461. return true;
  462. if (deref_stat (file_name, &file_stat) != 0)
  463. {
  464. if (errno == ENOENT)
  465. return true;
  466. stat_error (file_name);
  467. return false;
  468. }
  469. if (S_ISDIR (file_stat.st_mode))
  470. return true;
  471. if (this_is_the_archive
  472. && (S_ISBLK (file_stat.st_mode) || S_ISCHR (file_stat.st_mode)))
  473. return true;
  474. after_backup_name = find_backup_file_name (file_name, backup_type);
  475. if (! after_backup_name)
  476. xalloc_die ();
  477. if (renameat (chdir_fd, before_backup_name, chdir_fd, after_backup_name)
  478. == 0)
  479. {
  480. if (verbose_option)
  481. fprintf (stdlis, _("Renaming %s to %s\n"),
  482. quote_n (0, before_backup_name),
  483. quote_n (1, after_backup_name));
  484. return true;
  485. }
  486. else
  487. {
  488. /* The backup operation failed. */
  489. int e = errno;
  490. ERROR ((0, e, _("%s: Cannot rename to %s"),
  491. quotearg_colon (before_backup_name),
  492. quote_n (1, after_backup_name)));
  493. assign_string (&after_backup_name, 0);
  494. return false;
  495. }
  496. }
  497. /* Try to restore the recently backed up file to its original name.
  498. This is usually only needed after a failed extraction. */
  499. void
  500. undo_last_backup (void)
  501. {
  502. if (after_backup_name)
  503. {
  504. if (renameat (chdir_fd, after_backup_name, chdir_fd, before_backup_name)
  505. != 0)
  506. {
  507. int e = errno;
  508. ERROR ((0, e, _("%s: Cannot rename to %s"),
  509. quotearg_colon (after_backup_name),
  510. quote_n (1, before_backup_name)));
  511. }
  512. if (verbose_option)
  513. fprintf (stdlis, _("Renaming %s back to %s\n"),
  514. quote_n (0, after_backup_name),
  515. quote_n (1, before_backup_name));
  516. assign_string (&after_backup_name, 0);
  517. }
  518. }
  519. /* Apply either stat or lstat to (NAME, BUF), depending on the
  520. presence of the --dereference option. NAME is relative to the
  521. most-recent argument to chdir_do. */
  522. int
  523. deref_stat (char const *name, struct stat *buf)
  524. {
  525. return fstatat (chdir_fd, name, buf, fstatat_flags);
  526. }
  527. /* Read from FD into the buffer BUF with COUNT bytes. Attempt to fill
  528. BUF. Wait until input is available; this matters because files are
  529. opened O_NONBLOCK for security reasons, and on some file systems
  530. this can cause read to fail with errno == EAGAIN. Return the
  531. actual number of bytes read, zero for EOF, or
  532. SAFE_READ_ERROR upon error. */
  533. size_t
  534. blocking_read (int fd, void *buf, size_t count)
  535. {
  536. size_t bytes = safe_read (fd, buf, count);
  537. #if defined F_SETFL && O_NONBLOCK
  538. if (bytes == SAFE_READ_ERROR && errno == EAGAIN)
  539. {
  540. int flags = fcntl (fd, F_GETFL);
  541. if (0 <= flags && flags & O_NONBLOCK
  542. && fcntl (fd, F_SETFL, flags & ~O_NONBLOCK) != -1)
  543. bytes = safe_read (fd, buf, count);
  544. }
  545. #endif
  546. return bytes;
  547. }
  548. /* Write to FD from the buffer BUF with COUNT bytes. Do a full write.
  549. Wait until an output buffer is available; this matters because
  550. files are opened O_NONBLOCK for security reasons, and on some file
  551. systems this can cause write to fail with errno == EAGAIN. Return
  552. the actual number of bytes written, setting errno if that is less
  553. than COUNT. */
  554. size_t
  555. blocking_write (int fd, void const *buf, size_t count)
  556. {
  557. size_t bytes = full_write (fd, buf, count);
  558. #if defined F_SETFL && O_NONBLOCK
  559. if (bytes < count && errno == EAGAIN)
  560. {
  561. int flags = fcntl (fd, F_GETFL);
  562. if (0 <= flags && flags & O_NONBLOCK
  563. && fcntl (fd, F_SETFL, flags & ~O_NONBLOCK) != -1)
  564. {
  565. char const *buffer = buf;
  566. bytes += full_write (fd, buffer + bytes, count - bytes);
  567. }
  568. }
  569. #endif
  570. return bytes;
  571. }
  572. /* Set FD's (i.e., assuming the working directory is PARENTFD, FILE's)
  573. access time to ATIME. */
  574. int
  575. set_file_atime (int fd, int parentfd, char const *file, struct timespec atime)
  576. {
  577. struct timespec ts[2];
  578. ts[0] = atime;
  579. ts[1].tv_nsec = UTIME_OMIT;
  580. return fdutimensat (fd, parentfd, file, ts, fstatat_flags);
  581. }
  582. /* A description of a working directory. */
  583. struct wd
  584. {
  585. /* The directory's name. */
  586. char const *name;
  587. /* If nonzero, the file descriptor of the directory, or AT_FDCWD if
  588. the working directory. If zero, the directory needs to be opened
  589. to be used. */
  590. int fd;
  591. };
  592. /* A vector of chdir targets. wd[0] is the initial working directory. */
  593. static struct wd *wd;
  594. /* The number of working directories in the vector. */
  595. static size_t wd_count;
  596. /* The allocated size of the vector. */
  597. static size_t wd_alloc;
  598. /* The maximum number of chdir targets with open directories.
  599. Don't make it too large, as many operating systems have a small
  600. limit on the number of open file descriptors. Also, the current
  601. implementation does not scale well. */
  602. enum { CHDIR_CACHE_SIZE = 16 };
  603. /* Indexes into WD of chdir targets with open file descriptors, sorted
  604. most-recently used first. Zero indexes are unused. */
  605. static int wdcache[CHDIR_CACHE_SIZE];
  606. /* Number of nonzero entries in WDCACHE. */
  607. static size_t wdcache_count;
  608. int
  609. chdir_count (void)
  610. {
  611. if (wd_count == 0)
  612. return wd_count;
  613. return wd_count - 1;
  614. }
  615. /* DIR is the operand of a -C option; add it to vector of chdir targets,
  616. and return the index of its location. */
  617. int
  618. chdir_arg (char const *dir)
  619. {
  620. if (wd_count == wd_alloc)
  621. {
  622. if (wd_alloc == 0)
  623. {
  624. wd_alloc = 2;
  625. wd = xmalloc (sizeof *wd * wd_alloc);
  626. }
  627. else
  628. wd = x2nrealloc (wd, &wd_alloc, sizeof *wd);
  629. if (! wd_count)
  630. {
  631. wd[wd_count].name = ".";
  632. wd[wd_count].fd = AT_FDCWD;
  633. wd_count++;
  634. }
  635. }
  636. /* Optimize the common special case of the working directory,
  637. or the working directory as a prefix. */
  638. if (dir[0])
  639. {
  640. while (dir[0] == '.' && ISSLASH (dir[1]))
  641. for (dir += 2; ISSLASH (*dir); dir++)
  642. continue;
  643. if (! dir[dir[0] == '.'])
  644. return wd_count - 1;
  645. }
  646. wd[wd_count].name = dir;
  647. wd[wd_count].fd = 0;
  648. return wd_count++;
  649. }
  650. /* Index of current directory. */
  651. int chdir_current;
  652. /* Value suitable for use as the first argument to openat, and in
  653. similar locations for fstatat, etc. This is an open file
  654. descriptor, or AT_FDCWD if the working directory is current. It is
  655. valid until the next invocation of chdir_do. */
  656. int chdir_fd = AT_FDCWD;
  657. /* Change to directory I, in a virtual way. This does not actually
  658. invoke chdir; it merely sets chdir_fd to an int suitable as the
  659. first argument for openat, etc. If I is 0, change to the initial
  660. working directory; otherwise, I must be a value returned by
  661. chdir_arg. */
  662. void
  663. chdir_do (int i)
  664. {
  665. if (chdir_current != i)
  666. {
  667. struct wd *curr = &wd[i];
  668. int fd = curr->fd;
  669. if (! fd)
  670. {
  671. if (! IS_ABSOLUTE_FILE_NAME (curr->name))
  672. chdir_do (i - 1);
  673. fd = openat (chdir_fd, curr->name,
  674. open_searchdir_flags & ~ O_NOFOLLOW);
  675. if (fd < 0)
  676. open_fatal (curr->name);
  677. curr->fd = fd;
  678. /* Add I to the cache, tossing out the lowest-ranking entry if the
  679. cache is full. */
  680. if (wdcache_count < CHDIR_CACHE_SIZE)
  681. wdcache[wdcache_count++] = i;
  682. else
  683. {
  684. struct wd *stale = &wd[wdcache[CHDIR_CACHE_SIZE - 1]];
  685. if (close (stale->fd) != 0)
  686. close_diag (stale->name);
  687. stale->fd = 0;
  688. wdcache[CHDIR_CACHE_SIZE - 1] = i;
  689. }
  690. }
  691. if (0 < fd)
  692. {
  693. /* Move the i value to the front of the cache. This is
  694. O(CHDIR_CACHE_SIZE), but the cache is small. */
  695. size_t ci;
  696. int prev = wdcache[0];
  697. for (ci = 1; prev != i; ci++)
  698. {
  699. int cur = wdcache[ci];
  700. wdcache[ci] = prev;
  701. if (cur == i)
  702. break;
  703. prev = cur;
  704. }
  705. wdcache[0] = i;
  706. }
  707. chdir_current = i;
  708. chdir_fd = fd;
  709. }
  710. }
  711. void
  712. close_diag (char const *name)
  713. {
  714. if (ignore_failed_read_option)
  715. close_warn (name);
  716. else
  717. close_error (name);
  718. }
  719. void
  720. open_diag (char const *name)
  721. {
  722. if (ignore_failed_read_option)
  723. open_warn (name);
  724. else
  725. open_error (name);
  726. }
  727. void
  728. read_diag_details (char const *name, off_t offset, size_t size)
  729. {
  730. if (ignore_failed_read_option)
  731. read_warn_details (name, offset, size);
  732. else
  733. read_error_details (name, offset, size);
  734. }
  735. void
  736. readlink_diag (char const *name)
  737. {
  738. if (ignore_failed_read_option)
  739. readlink_warn (name);
  740. else
  741. readlink_error (name);
  742. }
  743. void
  744. savedir_diag (char const *name)
  745. {
  746. if (ignore_failed_read_option)
  747. savedir_warn (name);
  748. else
  749. savedir_error (name);
  750. }
  751. void
  752. seek_diag_details (char const *name, off_t offset)
  753. {
  754. if (ignore_failed_read_option)
  755. seek_warn_details (name, offset);
  756. else
  757. seek_error_details (name, offset);
  758. }
  759. void
  760. stat_diag (char const *name)
  761. {
  762. if (ignore_failed_read_option)
  763. stat_warn (name);
  764. else
  765. stat_error (name);
  766. }
  767. void
  768. file_removed_diag (const char *name, bool top_level,
  769. void (*diagfn) (char const *name))
  770. {
  771. if (!top_level && errno == ENOENT)
  772. {
  773. WARNOPT (WARN_FILE_REMOVED,
  774. (0, 0, _("%s: File removed before we read it"),
  775. quotearg_colon (name)));
  776. set_exit_status (TAREXIT_DIFFERS);
  777. }
  778. else
  779. diagfn (name);
  780. }
  781. void
  782. write_fatal_details (char const *name, ssize_t status, size_t size)
  783. {
  784. write_error_details (name, status, size);
  785. fatal_exit ();
  786. }
  787. /* Fork, aborting if unsuccessful. */
  788. pid_t
  789. xfork (void)
  790. {
  791. pid_t p = fork ();
  792. if (p == (pid_t) -1)
  793. call_arg_fatal ("fork", _("child process"));
  794. return p;
  795. }
  796. /* Create a pipe, aborting if unsuccessful. */
  797. void
  798. xpipe (int fd[2])
  799. {
  800. if (pipe (fd) < 0)
  801. call_arg_fatal ("pipe", _("interprocess channel"));
  802. }
  803. /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
  804. ALIGNMENT must be nonzero. The caller must arrange for ((char *)
  805. PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
  806. locations. */
  807. static inline void *
  808. ptr_align (void *ptr, size_t alignment)
  809. {
  810. char *p0 = ptr;
  811. char *p1 = p0 + alignment - 1;
  812. return p1 - (size_t) p1 % alignment;
  813. }
  814. /* Return the address of a page-aligned buffer of at least SIZE bytes.
  815. The caller should free *PTR when done with the buffer. */
  816. void *
  817. page_aligned_alloc (void **ptr, size_t size)
  818. {
  819. size_t alignment = getpagesize ();
  820. size_t size1 = size + alignment;
  821. if (size1 < size)
  822. xalloc_die ();
  823. *ptr = xmalloc (size1);
  824. return ptr_align (*ptr, alignment);
  825. }
  826. struct namebuf
  827. {
  828. char *buffer; /* directory, '/', and directory member */
  829. size_t buffer_size; /* allocated size of name_buffer */
  830. size_t dir_length; /* length of directory part in buffer */
  831. };
  832. namebuf_t
  833. namebuf_create (const char *dir)
  834. {
  835. namebuf_t buf = xmalloc (sizeof (*buf));
  836. buf->buffer_size = strlen (dir) + 2;
  837. buf->buffer = xmalloc (buf->buffer_size);
  838. strcpy (buf->buffer, dir);
  839. buf->dir_length = strlen (buf->buffer);
  840. if (!ISSLASH (buf->buffer[buf->dir_length - 1]))
  841. buf->buffer[buf->dir_length++] = DIRECTORY_SEPARATOR;
  842. return buf;
  843. }
  844. void
  845. namebuf_free (namebuf_t buf)
  846. {
  847. free (buf->buffer);
  848. free (buf);
  849. }
  850. char *
  851. namebuf_name (namebuf_t buf, const char *name)
  852. {
  853. size_t len = strlen (name);
  854. while (buf->dir_length + len + 1 >= buf->buffer_size)
  855. buf->buffer = x2realloc (buf->buffer, &buf->buffer_size);
  856. strcpy (buf->buffer + buf->dir_length, name);
  857. return buf->buffer;
  858. }