3
0

remove_file.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini remove_file implementation for busybox
  4. *
  5. * Copyright (C) 2001 Matt Kraai <kraai@alumni.carnegiemellon.edu>
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  8. */
  9. #include "libbb.h"
  10. /* Used from NOFORK applets. Must not allocate anything */
  11. int remove_file(const char *path, int flags)
  12. {
  13. struct stat path_stat;
  14. if (lstat(path, &path_stat) < 0) {
  15. if (errno != ENOENT) {
  16. bb_perror_msg("cannot stat '%s'", path);
  17. return -1;
  18. }
  19. if (!(flags & FILEUTILS_FORCE)) {
  20. bb_perror_msg("cannot remove '%s'", path);
  21. return -1;
  22. }
  23. return 0;
  24. }
  25. if (S_ISDIR(path_stat.st_mode)) {
  26. DIR *dp;
  27. struct dirent *d;
  28. int status = 0;
  29. if (!(flags & FILEUTILS_RECUR)) {
  30. bb_error_msg("%s: is a directory", path);
  31. return -1;
  32. }
  33. if ((!(flags & FILEUTILS_FORCE) && access(path, W_OK) < 0 && isatty(0))
  34. || (flags & FILEUTILS_INTERACTIVE)
  35. ) {
  36. fprintf(stderr, "%s: descend into directory '%s'? ", applet_name,
  37. path);
  38. if (!bb_ask_confirmation())
  39. return 0;
  40. }
  41. dp = opendir(path);
  42. if (dp == NULL) {
  43. return -1;
  44. }
  45. while ((d = readdir(dp)) != NULL) {
  46. char *new_path;
  47. new_path = concat_subpath_file(path, d->d_name);
  48. if (new_path == NULL)
  49. continue;
  50. if (remove_file(new_path, flags) < 0)
  51. status = -1;
  52. free(new_path);
  53. }
  54. if (closedir(dp) < 0) {
  55. bb_perror_msg("cannot close '%s'", path);
  56. return -1;
  57. }
  58. if (flags & FILEUTILS_INTERACTIVE) {
  59. fprintf(stderr, "%s: remove directory '%s'? ", applet_name, path);
  60. if (!bb_ask_confirmation())
  61. return status;
  62. }
  63. if (rmdir(path) < 0) {
  64. bb_perror_msg("cannot remove '%s'", path);
  65. return -1;
  66. }
  67. return status;
  68. }
  69. /* !ISDIR */
  70. if ((!(flags & FILEUTILS_FORCE)
  71. && access(path, W_OK) < 0
  72. && !S_ISLNK(path_stat.st_mode)
  73. && isatty(0))
  74. || (flags & FILEUTILS_INTERACTIVE)
  75. ) {
  76. fprintf(stderr, "%s: remove '%s'? ", applet_name, path);
  77. if (!bb_ask_confirmation())
  78. return 0;
  79. }
  80. if (unlink(path) < 0) {
  81. bb_perror_msg("cannot remove '%s'", path);
  82. return -1;
  83. }
  84. return 0;
  85. }