setgroups.c (1080B)
1 /* ISC license. */ 2 3 #include <skalibs/sysdeps.h> 4 5 #ifdef SKALIBS_HASSETGROUPS 6 7 #include <skalibs/nonposix.h> 8 9 #include <string.h> 10 #include <unistd.h> 11 #include <grp.h> 12 13 #include <skalibs/setgroups.h> 14 #include <skalibs/posixishard.h> 15 16 int setgroups_and_gid (gid_t g, size_t n, gid_t const *tab) 17 { 18 size_t i = 1 ; 19 if (!n) return setgroups(1, &g) ; 20 if (tab[0] == g) return setgroups(n, tab) ; 21 for (; i < n ; i++) if (tab[i] == g) break ; 22 if (i < n) 23 { 24 gid_t newtab[n] ; 25 newtab[0] = g ; 26 memcpy(newtab + 1, tab, i * sizeof(gid_t)) ; 27 memcpy(newtab + i + 1, tab + i + 1, (n - i - 1) * sizeof(gid_t)) ; 28 return setgroups(n, newtab) ; 29 } 30 else 31 { 32 gid_t newtab[n+1] ; 33 newtab[0] = g ; 34 memcpy(newtab + 1, tab, n * sizeof(gid_t)) ; 35 return setgroups(n+1, newtab) ; 36 } 37 } 38 39 int setgroups_with_egid (size_t n, gid_t const *tab) 40 { 41 return setgroups_and_gid(getegid(), n, tab) ; 42 } 43 44 int skalibs_setgroups (size_t n, gid_t const *tab) 45 { 46 #ifdef SKALIBS_BSD_SUCKS 47 return setgroups_with_egid(n, tab) ; 48 #else 49 return setgroups(n, tab) ; 50 #endif 51 } 52 53 #endif