4
0

misc.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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 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 2, 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 <sys/time.h>
  17. #include <sys/resource.h>
  18. #include <rmt.h>
  19. #include "common.h"
  20. #include <quotearg.h>
  21. #include <save-cwd.h>
  22. #include <xgetcwd.h>
  23. #include <unlinkdir.h>
  24. #include <utimens.h>
  25. #if HAVE_STROPTS_H
  26. # include <stropts.h>
  27. #endif
  28. #if HAVE_SYS_FILIO_H
  29. # include <sys/filio.h>
  30. #endif
  31. /* Handling strings. */
  32. /* Assign STRING to a copy of VALUE if not zero, or to zero. If
  33. STRING was nonzero, it is freed first. */
  34. void
  35. assign_string (char **string, const char *value)
  36. {
  37. if (*string)
  38. free (*string);
  39. *string = value ? xstrdup (value) : 0;
  40. }
  41. /* Allocate a copy of the string quoted as in C, and returns that. If
  42. the string does not have to be quoted, it returns a null pointer.
  43. The allocated copy should normally be freed with free() after the
  44. caller is done with it.
  45. This is used in one context only: generating the directory file in
  46. incremental dumps. The quoted string is not intended for human
  47. consumption; it is intended only for unquote_string. The quoting
  48. is locale-independent, so that users needn't worry about locale
  49. when reading directory files. This means that we can't use
  50. quotearg, as quotearg is locale-dependent and is meant for human
  51. consumption. */
  52. char *
  53. quote_copy_string (const char *string)
  54. {
  55. const char *source = string;
  56. char *destination = 0;
  57. char *buffer = 0;
  58. int copying = 0;
  59. while (*source)
  60. {
  61. int character = *source++;
  62. switch (character)
  63. {
  64. case '\n': case '\\':
  65. if (!copying)
  66. {
  67. size_t length = (source - string) - 1;
  68. copying = 1;
  69. buffer = xmalloc (length + 2 + 2 * strlen (source) + 1);
  70. memcpy (buffer, string, length);
  71. destination = buffer + length;
  72. }
  73. *destination++ = '\\';
  74. *destination++ = character == '\\' ? '\\' : 'n';
  75. break;
  76. default:
  77. if (copying)
  78. *destination++ = character;
  79. break;
  80. }
  81. }
  82. if (copying)
  83. {
  84. *destination = '\0';
  85. return buffer;
  86. }
  87. return 0;
  88. }
  89. /* Takes a quoted C string (like those produced by quote_copy_string)
  90. and turns it back into the un-quoted original. This is done in
  91. place. Returns 0 only if the string was not properly quoted, but
  92. completes the unquoting anyway.
  93. This is used for reading the saved directory file in incremental
  94. dumps. It is used for decoding old `N' records (demangling names).
  95. But also, it is used for decoding file arguments, would they come
  96. from the shell or a -T file, and for decoding the --exclude
  97. argument. */
  98. int
  99. unquote_string (char *string)
  100. {
  101. int result = 1;
  102. char *source = string;
  103. char *destination = string;
  104. /* Escape sequences other than \\ and \n are no longer generated by
  105. quote_copy_string, but accept them for backwards compatibility,
  106. and also because unquote_string is used for purposes other than
  107. parsing the output of quote_copy_string. */
  108. while (*source)
  109. if (*source == '\\')
  110. switch (*++source)
  111. {
  112. case '\\':
  113. *destination++ = '\\';
  114. source++;
  115. break;
  116. case 'a':
  117. *destination++ = '\a';
  118. source++;
  119. break;
  120. case 'b':
  121. *destination++ = '\b';
  122. source++;
  123. break;
  124. case 'f':
  125. *destination++ = '\f';
  126. source++;
  127. break;
  128. case 'n':
  129. *destination++ = '\n';
  130. source++;
  131. break;
  132. case 'r':
  133. *destination++ = '\r';
  134. source++;
  135. break;
  136. case 't':
  137. *destination++ = '\t';
  138. source++;
  139. break;
  140. case 'v':
  141. *destination++ = '\v';
  142. source++;
  143. break;
  144. case '?':
  145. *destination++ = 0177;
  146. source++;
  147. break;
  148. case '0':
  149. case '1':
  150. case '2':
  151. case '3':
  152. case '4':
  153. case '5':
  154. case '6':
  155. case '7':
  156. {
  157. int value = *source++ - '0';
  158. if (*source < '0' || *source > '7')
  159. {
  160. *destination++ = value;
  161. break;
  162. }
  163. value = value * 8 + *source++ - '0';
  164. if (*source < '0' || *source > '7')
  165. {
  166. *destination++ = value;
  167. break;
  168. }
  169. value = value * 8 + *source++ - '0';
  170. *destination++ = value;
  171. break;
  172. }
  173. default:
  174. result = 0;
  175. *destination++ = '\\';
  176. if (*source)
  177. *destination++ = *source++;
  178. break;
  179. }
  180. else if (source != destination)
  181. *destination++ = *source++;
  182. else
  183. source++, destination++;
  184. if (source != destination)
  185. *destination = '\0';
  186. return result;
  187. }
  188. /* Handling numbers. */
  189. /* Output fraction and trailing digits appropriate for a nanoseconds
  190. count equal to NS, but don't output unnecessary '.' or trailing
  191. zeros. */
  192. void
  193. code_ns_fraction (int ns, char *p)
  194. {
  195. if (ns == 0)
  196. *p = '\0';
  197. else
  198. {
  199. int i = 9;
  200. *p++ = '.';
  201. while (ns % 10 == 0)
  202. {
  203. ns /= 10;
  204. i--;
  205. }
  206. p[i] = '\0';
  207. for (;;)
  208. {
  209. p[--i] = '0' + ns % 10;
  210. if (i == 0)
  211. break;
  212. ns /= 10;
  213. }
  214. }
  215. }
  216. char const *
  217. code_timespec (struct timespec t, char sbuf[TIMESPEC_STRSIZE_BOUND])
  218. {
  219. time_t s = t.tv_sec;
  220. int ns = t.tv_nsec;
  221. char *np;
  222. bool negative = s < 0;
  223. if (negative && ns != 0)
  224. {
  225. s++;
  226. ns = BILLION - ns;
  227. }
  228. np = umaxtostr (negative ? - (uintmax_t) s : (uintmax_t) s, sbuf + 1);
  229. if (negative)
  230. *--np = '-';
  231. code_ns_fraction (ns, sbuf + UINTMAX_STRSIZE_BOUND);
  232. return np;
  233. }
  234. /* File handling. */
  235. /* Saved names in case backup needs to be undone. */
  236. static char *before_backup_name;
  237. static char *after_backup_name;
  238. /* Return 1 if FILE_NAME is obviously "." or "/". */
  239. static bool
  240. must_be_dot_or_slash (char const *file_name)
  241. {
  242. file_name += FILE_SYSTEM_PREFIX_LEN (file_name);
  243. if (ISSLASH (file_name[0]))
  244. {
  245. for (;;)
  246. if (ISSLASH (file_name[1]))
  247. file_name++;
  248. else if (file_name[1] == '.'
  249. && ISSLASH (file_name[2 + (file_name[2] == '.')]))
  250. file_name += 2 + (file_name[2] == '.');
  251. else
  252. return ! file_name[1];
  253. }
  254. else
  255. {
  256. while (file_name[0] == '.' && ISSLASH (file_name[1]))
  257. {
  258. file_name += 2;
  259. while (ISSLASH (*file_name))
  260. file_name++;
  261. }
  262. return ! file_name[0] || (file_name[0] == '.' && ! file_name[1]);
  263. }
  264. }
  265. /* Some implementations of rmdir let you remove '.' or '/'.
  266. Report an error with errno set to zero for obvious cases of this;
  267. otherwise call rmdir. */
  268. static int
  269. safer_rmdir (const char *file_name)
  270. {
  271. if (must_be_dot_or_slash (file_name))
  272. {
  273. errno = 0;
  274. return -1;
  275. }
  276. return rmdir (file_name);
  277. }
  278. /* Remove FILE_NAME, returning 1 on success. If FILE_NAME is a directory,
  279. then if OPTION is RECURSIVE_REMOVE_OPTION is set remove FILE_NAME
  280. recursively; otherwise, remove it only if it is empty. If FILE_NAME is
  281. a directory that cannot be removed (e.g., because it is nonempty)
  282. and if OPTION is WANT_DIRECTORY_REMOVE_OPTION, then return -1.
  283. Return 0 on error, with errno set; if FILE_NAME is obviously the working
  284. directory return zero with errno set to zero. */
  285. int
  286. remove_any_file (const char *file_name, enum remove_option option)
  287. {
  288. /* Try unlink first if we cannot unlink directories, as this saves
  289. us a system call in the common case where we're removing a
  290. non-directory. */
  291. bool try_unlink_first = cannot_unlink_dir ();
  292. if (try_unlink_first)
  293. {
  294. if (unlink (file_name) == 0)
  295. return 1;
  296. /* POSIX 1003.1-2001 requires EPERM when attempting to unlink a
  297. directory without appropriate privileges, but many Linux
  298. kernels return the more-sensible EISDIR. */
  299. if (errno != EPERM && errno != EISDIR)
  300. return 0;
  301. }
  302. if (safer_rmdir (file_name) == 0)
  303. return 1;
  304. switch (errno)
  305. {
  306. case ENOTDIR:
  307. return !try_unlink_first && unlink (file_name) == 0;
  308. case 0:
  309. case EEXIST:
  310. #if defined ENOTEMPTY && ENOTEMPTY != EEXIST
  311. case ENOTEMPTY:
  312. #endif
  313. switch (option)
  314. {
  315. case ORDINARY_REMOVE_OPTION:
  316. break;
  317. case WANT_DIRECTORY_REMOVE_OPTION:
  318. return -1;
  319. case RECURSIVE_REMOVE_OPTION:
  320. {
  321. char *directory = savedir (file_name);
  322. char const *entry;
  323. size_t entrylen;
  324. if (! directory)
  325. return 0;
  326. for (entry = directory;
  327. (entrylen = strlen (entry)) != 0;
  328. entry += entrylen + 1)
  329. {
  330. char *file_name_buffer = new_name (file_name, entry);
  331. int r = remove_any_file (file_name_buffer,
  332. RECURSIVE_REMOVE_OPTION);
  333. int e = errno;
  334. free (file_name_buffer);
  335. if (! r)
  336. {
  337. free (directory);
  338. errno = e;
  339. return 0;
  340. }
  341. }
  342. free (directory);
  343. return safer_rmdir (file_name) == 0;
  344. }
  345. }
  346. break;
  347. }
  348. return 0;
  349. }
  350. /* Check if FILE_NAME already exists and make a backup of it right now.
  351. Return success (nonzero) only if the backup is either unneeded, or
  352. successful. For now, directories are considered to never need
  353. backup. If THIS_IS_THE_ARCHIVE is nonzero, this is the archive and
  354. so, we do not have to backup block or character devices, nor remote
  355. entities. */
  356. bool
  357. maybe_backup_file (const char *file_name, bool this_is_the_archive)
  358. {
  359. struct stat file_stat;
  360. /* Check if we really need to backup the file. */
  361. if (this_is_the_archive && _remdev (file_name))
  362. return true;
  363. if (stat (file_name, &file_stat))
  364. {
  365. if (errno == ENOENT)
  366. return true;
  367. stat_error (file_name);
  368. return false;
  369. }
  370. if (S_ISDIR (file_stat.st_mode))
  371. return true;
  372. if (this_is_the_archive
  373. && (S_ISBLK (file_stat.st_mode) || S_ISCHR (file_stat.st_mode)))
  374. return true;
  375. assign_string (&before_backup_name, file_name);
  376. /* A run situation may exist between Emacs or other GNU programs trying to
  377. make a backup for the same file simultaneously. If theoretically
  378. possible, real problems are unlikely. Doing any better would require a
  379. convention, GNU-wide, for all programs doing backups. */
  380. assign_string (&after_backup_name, 0);
  381. after_backup_name = find_backup_file_name (file_name, backup_type);
  382. if (! after_backup_name)
  383. xalloc_die ();
  384. if (rename (before_backup_name, after_backup_name) == 0)
  385. {
  386. if (verbose_option)
  387. fprintf (stdlis, _("Renaming %s to %s\n"),
  388. quote_n (0, before_backup_name),
  389. quote_n (1, after_backup_name));
  390. return true;
  391. }
  392. else
  393. {
  394. /* The backup operation failed. */
  395. int e = errno;
  396. ERROR ((0, e, _("%s: Cannot rename to %s"),
  397. quotearg_colon (before_backup_name),
  398. quote_n (1, after_backup_name)));
  399. assign_string (&after_backup_name, 0);
  400. return false;
  401. }
  402. }
  403. /* Try to restore the recently backed up file to its original name.
  404. This is usually only needed after a failed extraction. */
  405. void
  406. undo_last_backup (void)
  407. {
  408. if (after_backup_name)
  409. {
  410. if (rename (after_backup_name, before_backup_name) != 0)
  411. {
  412. int e = errno;
  413. ERROR ((0, e, _("%s: Cannot rename to %s"),
  414. quotearg_colon (after_backup_name),
  415. quote_n (1, before_backup_name)));
  416. }
  417. if (verbose_option)
  418. fprintf (stdlis, _("Renaming %s back to %s\n"),
  419. quote_n (0, after_backup_name),
  420. quote_n (1, before_backup_name));
  421. assign_string (&after_backup_name, 0);
  422. }
  423. }
  424. /* Depending on DEREF, apply either stat or lstat to (NAME, BUF). */
  425. int
  426. deref_stat (bool deref, char const *name, struct stat *buf)
  427. {
  428. return deref ? stat (name, buf) : lstat (name, buf);
  429. }
  430. /* Set FD's (i.e., FILE's) access time to TIMESPEC[0]. If that's not
  431. possible to do by itself, set its access and data modification
  432. times to TIMESPEC[0] and TIMESPEC[1], respectively. */
  433. int
  434. set_file_atime (int fd, char const *file, struct timespec const timespec[2])
  435. {
  436. #ifdef _FIOSATIME
  437. if (0 <= fd)
  438. {
  439. struct timeval timeval;
  440. timeval.tv_sec = timespec[0].tv_sec;
  441. timeval.tv_usec = timespec[0].tv_nsec / 1000;
  442. if (ioctl (fd, _FIOSATIME, &timeval) == 0)
  443. return 0;
  444. }
  445. #endif
  446. return futimens (fd, file, timespec);
  447. }
  448. /* A description of a working directory. */
  449. struct wd
  450. {
  451. char const *name;
  452. int saved;
  453. struct saved_cwd saved_cwd;
  454. };
  455. /* A vector of chdir targets. wd[0] is the initial working directory. */
  456. static struct wd *wd;
  457. /* The number of working directories in the vector. */
  458. static size_t wds;
  459. /* The allocated size of the vector. */
  460. static size_t wd_alloc;
  461. /* DIR is the operand of a -C option; add it to vector of chdir targets,
  462. and return the index of its location. */
  463. int
  464. chdir_arg (char const *dir)
  465. {
  466. if (wds == wd_alloc)
  467. {
  468. if (wd_alloc == 0)
  469. {
  470. wd_alloc = 2;
  471. wd = xmalloc (sizeof *wd * wd_alloc);
  472. }
  473. else
  474. wd = x2nrealloc (wd, &wd_alloc, sizeof *wd);
  475. if (! wds)
  476. {
  477. wd[wds].name = ".";
  478. wd[wds].saved = 0;
  479. wds++;
  480. }
  481. }
  482. /* Optimize the common special case of the working directory,
  483. or the working directory as a prefix. */
  484. if (dir[0])
  485. {
  486. while (dir[0] == '.' && ISSLASH (dir[1]))
  487. for (dir += 2; ISSLASH (*dir); dir++)
  488. continue;
  489. if (! dir[dir[0] == '.'])
  490. return wds - 1;
  491. }
  492. wd[wds].name = dir;
  493. wd[wds].saved = 0;
  494. return wds++;
  495. }
  496. /* Return maximum number of open files */
  497. int
  498. get_max_open_files ()
  499. {
  500. #if defined _SC_OPEN_MAX
  501. return sysconf (_SC_OPEN_MAX);
  502. #elif defined RLIMIT_NOFILE
  503. struct rlimit rlim;
  504. if (getrlimit(RLIMIT_NOFILE, &rlim) == 0)
  505. return rlim.rlim_max;
  506. #elif defined HAVE_GETDTABLESIZE
  507. return getdtablesize ();
  508. #endif
  509. return -1;
  510. }
  511. /* Close all descriptors, except the first three */
  512. void
  513. closeopen ()
  514. {
  515. int i;
  516. for (i = get_max_open_files () - 1; i > 2; i--)
  517. close (i);
  518. }
  519. /* Change to directory I. If I is 0, change to the initial working
  520. directory; otherwise, I must be a value returned by chdir_arg. */
  521. void
  522. chdir_do (int i)
  523. {
  524. static int previous;
  525. static int saved_count;
  526. if (previous != i)
  527. {
  528. struct wd *prev = &wd[previous];
  529. struct wd *curr = &wd[i];
  530. if (! prev->saved)
  531. {
  532. prev->saved = 1;
  533. saved_count++;
  534. /* Make sure we still have at least one descriptor available */
  535. if (saved_count >= get_max_open_files () - 4)
  536. {
  537. /* Force restore_cwd to use chdir_long */
  538. prev->saved_cwd.desc = -1;
  539. prev->saved_cwd.name = xgetcwd ();
  540. }
  541. else if (save_cwd (&prev->saved_cwd) != 0)
  542. FATAL_ERROR ((0, 0, _("Cannot save working directory")));
  543. }
  544. if (curr->saved)
  545. {
  546. if (restore_cwd (&curr->saved_cwd))
  547. FATAL_ERROR ((0, 0, _("Cannot change working directory")));
  548. }
  549. else
  550. {
  551. if (i && ! ISSLASH (curr->name[0]))
  552. chdir_do (i - 1);
  553. if (chdir (curr->name) != 0)
  554. chdir_fatal (curr->name);
  555. }
  556. previous = i;
  557. }
  558. }
  559. void
  560. close_diag (char const *name)
  561. {
  562. if (ignore_failed_read_option)
  563. close_warn (name);
  564. else
  565. close_error (name);
  566. }
  567. void
  568. open_diag (char const *name)
  569. {
  570. if (ignore_failed_read_option)
  571. open_warn (name);
  572. else
  573. open_error (name);
  574. }
  575. void
  576. read_diag_details (char const *name, off_t offset, size_t size)
  577. {
  578. if (ignore_failed_read_option)
  579. read_warn_details (name, offset, size);
  580. else
  581. read_error_details (name, offset, size);
  582. }
  583. void
  584. readlink_diag (char const *name)
  585. {
  586. if (ignore_failed_read_option)
  587. readlink_warn (name);
  588. else
  589. readlink_error (name);
  590. }
  591. void
  592. savedir_diag (char const *name)
  593. {
  594. if (ignore_failed_read_option)
  595. savedir_warn (name);
  596. else
  597. savedir_error (name);
  598. }
  599. void
  600. seek_diag_details (char const *name, off_t offset)
  601. {
  602. if (ignore_failed_read_option)
  603. seek_warn_details (name, offset);
  604. else
  605. seek_error_details (name, offset);
  606. }
  607. void
  608. stat_diag (char const *name)
  609. {
  610. if (ignore_failed_read_option)
  611. stat_warn (name);
  612. else
  613. stat_error (name);
  614. }
  615. void
  616. write_fatal_details (char const *name, ssize_t status, size_t size)
  617. {
  618. write_error_details (name, status, size);
  619. fatal_exit ();
  620. }
  621. /* Fork, aborting if unsuccessful. */
  622. pid_t
  623. xfork (void)
  624. {
  625. pid_t p = fork ();
  626. if (p == (pid_t) -1)
  627. call_arg_fatal ("fork", _("child process"));
  628. return p;
  629. }
  630. /* Create a pipe, aborting if unsuccessful. */
  631. void
  632. xpipe (int fd[2])
  633. {
  634. if (pipe (fd) < 0)
  635. call_arg_fatal ("pipe", _("interprocess channel"));
  636. }
  637. /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
  638. ALIGNMENT must be nonzero. The caller must arrange for ((char *)
  639. PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
  640. locations. */
  641. static inline void *
  642. ptr_align (void *ptr, size_t alignment)
  643. {
  644. char *p0 = ptr;
  645. char *p1 = p0 + alignment - 1;
  646. return p1 - (size_t) p1 % alignment;
  647. }
  648. /* Return the address of a page-aligned buffer of at least SIZE bytes.
  649. The caller should free *PTR when done with the buffer. */
  650. void *
  651. page_aligned_alloc (void **ptr, size_t size)
  652. {
  653. size_t alignment = getpagesize ();
  654. size_t size1 = size + alignment;
  655. if (size1 < size)
  656. xalloc_die ();
  657. *ptr = xmalloc (size1);
  658. return ptr_align (*ptr, alignment);
  659. }