find_mount_point.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. #include <mntent.h>
  11. /*
  12. * Given a block device, find the mount table entry if that block device
  13. * is mounted.
  14. *
  15. * Given any other file (or directory), find the mount table entry for its
  16. * filesystem.
  17. */
  18. struct mntent* FAST_FUNC find_mount_point(const char *name, int subdir_too)
  19. {
  20. struct stat s;
  21. FILE *mtab_fp;
  22. struct mntent *mountEntry;
  23. dev_t devno_of_name;
  24. bool block_dev;
  25. if (stat(name, &s) != 0)
  26. return NULL;
  27. devno_of_name = s.st_dev;
  28. block_dev = 0;
  29. /* Why S_ISCHR? - UBI volumes use char devices, not block */
  30. if (S_ISBLK(s.st_mode) || S_ISCHR(s.st_mode)) {
  31. devno_of_name = s.st_rdev;
  32. block_dev = 1;
  33. }
  34. mtab_fp = setmntent(bb_path_mtab_file, "r");
  35. if (!mtab_fp)
  36. return NULL;
  37. while ((mountEntry = getmntent(mtab_fp)) != NULL) {
  38. /* rootfs mount in Linux 2.6 exists always,
  39. * and it makes sense to always ignore it.
  40. * Otherwise people can't reference their "real" root! */
  41. if (ENABLE_FEATURE_SKIP_ROOTFS && strcmp(mountEntry->mnt_fsname, "rootfs") == 0)
  42. continue;
  43. if (strcmp(name, mountEntry->mnt_dir) == 0
  44. || strcmp(name, mountEntry->mnt_fsname) == 0
  45. ) { /* String match. */
  46. break;
  47. }
  48. if (!(subdir_too || block_dev))
  49. continue;
  50. /* Is device's dev_t == name's dev_t? */
  51. if (mountEntry->mnt_fsname[0] == '/'
  52. /* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  53. * avoid stat'ing "sysfs", "proc", "none" and such,
  54. * useless at best, can stat unrelated files at worst.
  55. */
  56. && stat(mountEntry->mnt_fsname, &s) == 0
  57. && s.st_rdev == devno_of_name
  58. ) {
  59. break;
  60. }
  61. /* Match the directory's mount point. */
  62. if (stat(mountEntry->mnt_dir, &s) == 0
  63. && s.st_dev == devno_of_name
  64. ) {
  65. break;
  66. }
  67. }
  68. endmntent(mtab_fp);
  69. return mountEntry;
  70. }