You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
2.6 KiB

  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2014 Antonio SJ Musumeci <trapexit@spawn.link>
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. #include <sys/types.h>
  21. #include <sys/stat.h>
  22. #include <unistd.h>
  23. #include <pthread.h>
  24. namespace mergerfs
  25. {
  26. namespace ugid
  27. {
  28. extern uid_t currentuid;
  29. extern gid_t currentgid;
  30. extern pthread_rwlock_t rwlock;
  31. static
  32. void
  33. ugid_set(const uid_t newuid,
  34. const gid_t newgid)
  35. {
  36. pthread_rwlock_rdlock(&rwlock);
  37. if(newuid == currentuid && newgid == currentgid)
  38. return;
  39. pthread_rwlock_unlock(&rwlock);
  40. pthread_rwlock_wrlock(&rwlock);
  41. if(newuid == currentuid && newgid == currentgid)
  42. return;
  43. if(currentuid != 0)
  44. {
  45. ::seteuid(0);
  46. ::setegid(0);
  47. }
  48. if(newgid)
  49. {
  50. ::setegid(newgid);
  51. initgroups(newuid,newgid);
  52. }
  53. if(newuid)
  54. ::seteuid(newuid);
  55. currentuid = newuid;
  56. currentgid = newgid;
  57. }
  58. struct Set
  59. {
  60. Set(const uid_t newuid,
  61. const gid_t newgid)
  62. {
  63. ugid_set(newuid,newgid);
  64. }
  65. ~Set()
  66. {
  67. pthread_rwlock_unlock(&rwlock);
  68. }
  69. };
  70. struct SetRootGuard
  71. {
  72. SetRootGuard() :
  73. prevuid(currentuid),
  74. prevgid(currentgid)
  75. {
  76. pthread_rwlock_unlock(&rwlock);
  77. ugid_set(0,0);
  78. }
  79. ~SetRootGuard()
  80. {
  81. pthread_rwlock_unlock(&rwlock);
  82. ugid_set(prevuid,prevgid);
  83. }
  84. const uid_t prevuid;
  85. const gid_t prevgid;
  86. };
  87. }
  88. }