remove_file.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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 source tree.
  8. */
  9. #include "libbb.h"
  10. /* Used from NOFORK applets. Must not allocate anything */
  11. int FAST_FUNC 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("can't stat '%s'", path);
  17. return -1;
  18. }
  19. if (!(flags & FILEUTILS_FORCE)) {
  20. bb_perror_msg("can't 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("can't 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("can't remove '%s'", path);
  65. return -1;
  66. }
  67. if (flags & FILEUTILS_VERBOSE) {
  68. printf("removed directory: '%s'\n", path);
  69. }
  70. return status;
  71. }
  72. /* !ISDIR */
  73. if ((!(flags & FILEUTILS_FORCE)
  74. && access(path, W_OK) < 0
  75. && !S_ISLNK(path_stat.st_mode)
  76. && isatty(0))
  77. || (flags & FILEUTILS_INTERACTIVE)
  78. ) {
  79. fprintf(stderr, "%s: remove '%s'? ", applet_name, path);
  80. if (!bb_ask_confirmation())
  81. return 0;
  82. }
  83. if (unlink(path) < 0) {
  84. bb_perror_msg("can't remove '%s'", path);
  85. return -1;
  86. }
  87. if (flags & FILEUTILS_VERBOSE) {
  88. printf("removed '%s'\n", path);
  89. }
  90. return 0;
  91. }