find_root_device.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  8. */
  9. #include "libbb.h"
  10. /* Find block device /dev/XXX which contains specified file
  11. * We handle /dev/dir/dir/dir too, at a cost of ~80 more bytes code */
  12. /* Do not reallocate all this stuff on each recursion */
  13. enum { DEVNAME_MAX = 256 };
  14. struct arena {
  15. struct stat st;
  16. dev_t dev;
  17. /* Was PATH_MAX, but we recurse _/dev_. We can assume
  18. * people are not crazy enough to have mega-deep tree there */
  19. char devpath[DEVNAME_MAX];
  20. };
  21. static char *find_block_device_in_dir(struct arena *ap)
  22. {
  23. DIR *dir;
  24. struct dirent *entry;
  25. char *retpath = NULL;
  26. int len, rem;
  27. len = strlen(ap->devpath);
  28. rem = DEVNAME_MAX-2 - len;
  29. if (rem <= 0)
  30. return NULL;
  31. dir = opendir(ap->devpath);
  32. if (!dir)
  33. return NULL;
  34. ap->devpath[len++] = '/';
  35. while ((entry = readdir(dir)) != NULL) {
  36. safe_strncpy(ap->devpath + len, entry->d_name, rem);
  37. /* lstat: do not follow links */
  38. if (lstat(ap->devpath, &ap->st) != 0)
  39. continue;
  40. if (S_ISBLK(ap->st.st_mode) && ap->st.st_rdev == ap->dev) {
  41. retpath = xstrdup(ap->devpath);
  42. break;
  43. }
  44. if (S_ISDIR(ap->st.st_mode)) {
  45. /* Do not recurse for '.' and '..' */
  46. if (DOT_OR_DOTDOT(entry->d_name))
  47. continue;
  48. retpath = find_block_device_in_dir(ap);
  49. if (retpath)
  50. break;
  51. }
  52. }
  53. closedir(dir);
  54. return retpath;
  55. }
  56. char* FAST_FUNC find_block_device(const char *path)
  57. {
  58. struct arena a;
  59. if (stat(path, &a.st) != 0)
  60. return NULL;
  61. a.dev = S_ISBLK(a.st.st_mode) ? a.st.st_rdev : a.st.st_dev;
  62. strcpy(a.devpath, "/dev");
  63. return find_block_device_in_dir(&a);
  64. }