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'? ",
  37. applet_name, path);
  38. if (!bb_ask_y_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'? ",
  60. applet_name, path);
  61. if (!bb_ask_y_confirmation())
  62. return status;
  63. }
  64. if (status == 0 && rmdir(path) < 0) {
  65. bb_perror_msg("can't remove '%s'", path);
  66. return -1;
  67. }
  68. if (flags & FILEUTILS_VERBOSE) {
  69. printf("removed directory: '%s'\n", path);
  70. }
  71. return status;
  72. }
  73. /* !ISDIR */
  74. if ((!(flags & FILEUTILS_FORCE)
  75. && access(path, W_OK) < 0
  76. && !S_ISLNK(path_stat.st_mode)
  77. && isatty(0))
  78. || (flags & FILEUTILS_INTERACTIVE)
  79. ) {
  80. fprintf(stderr, "%s: remove '%s'? ", applet_name, path);
  81. if (!bb_ask_y_confirmation())
  82. return 0;
  83. }
  84. if (unlink(path) < 0) {
  85. bb_perror_msg("can't remove '%s'", path);
  86. return -1;
  87. }
  88. if (flags & FILEUTILS_VERBOSE) {
  89. printf("removed '%s'\n", path);
  90. }
  91. return 0;
  92. }