which.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Which implementation for busybox
  4. *
  5. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  6. *
  7. * Licensed under the GPL v2, see the file LICENSE in this tarball.
  8. *
  9. * Based on which from debianutils
  10. */
  11. #include <string.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <unistd.h>
  15. #include <sys/stat.h>
  16. #include "busybox.h"
  17. int which_main(int argc, char **argv)
  18. {
  19. int status = EXIT_SUCCESS;
  20. size_t i, count;
  21. char *path_list;
  22. if (argc <= 1 || **(argv + 1) == '-') {
  23. bb_show_usage();
  24. }
  25. argc--;
  26. path_list = getenv("PATH");
  27. if (path_list != NULL) {
  28. size_t path_len = bb_strlen(path_list);
  29. char *new_list = NULL;
  30. count = 1;
  31. for (i = 0; i <= path_len; i++) {
  32. char *this_i = &path_list[i];
  33. if (*this_i == ':') {
  34. /* ^::[^:] == \.: */
  35. if (!i && (*(this_i + 1) == ':')) {
  36. *this_i = '.';
  37. continue;
  38. }
  39. *this_i = 0;
  40. count++;
  41. /* ^:[^:] == \.0 and [^:]::[^:] == 0\.0 and [^:]:$ == 0\.0 */
  42. if (!i || (*(this_i + 1) == ':') || (i == path_len-1)) {
  43. new_list = xrealloc(new_list, path_len += 1);
  44. if (i) {
  45. memmove(&new_list[i+2], &path_list[i+1], path_len-i);
  46. new_list[i+1] = '.';
  47. memmove(new_list, path_list, i);
  48. } else {
  49. memmove(&new_list[i+1], &path_list[i], path_len-i);
  50. new_list[i] = '.';
  51. }
  52. path_list = new_list;
  53. }
  54. }
  55. }
  56. } else {
  57. path_list = "/bin\0/sbin\0/usr/bin\0/usr/sbin\0/usr/local/bin";
  58. count = 5;
  59. }
  60. while (argc-- > 0) {
  61. struct stat stat_b;
  62. char *buf;
  63. char *path_n;
  64. char found = 0;
  65. #define is_executable_file(a, b) (!access(a,X_OK) && !stat(a, &b) && \
  66. S_ISREG(b.st_mode))
  67. argv++;
  68. path_n = path_list;
  69. buf = *argv;
  70. /* if filename is either absolute or contains slashes,
  71. * stat it */
  72. if (strchr(buf, '/') != NULL && is_executable_file(buf, stat_b)) {
  73. found = 1;
  74. } else {
  75. /* Couldn't access file and file doesn't contain slashes */
  76. for (i = 0; i < count; i++) {
  77. buf = concat_path_file(path_n, *argv);
  78. if (is_executable_file(buf, stat_b)) {
  79. found = 1;
  80. break;
  81. }
  82. free(buf);
  83. path_n += (bb_strlen(path_n) + 1);
  84. }
  85. }
  86. if (found) {
  87. puts(buf);
  88. } else {
  89. status = EXIT_FAILURE;
  90. }
  91. }
  92. bb_fflush_stdout_and_exit(status);
  93. }
  94. /*
  95. Local Variables:
  96. c-file-style: "linux"
  97. c-basic-offset: 4
  98. tab-width: 4
  99. End:
  100. */