3
0

remove_file.c 2.2 KB

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