initgroups.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * initgroups.c - This file is part of the libc-8086/grp package for ELKS,
  4. * Copyright (C) 1995, 1996 Nat Friedman <ndf@linux.mit.edu>.
  5. * Copyright (C) 2001-2003 Erik Andersen <andersee@debian.org>
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Library General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Library General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Library General Public
  18. * License along with this library; if not, write to the Free
  19. * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  20. *
  21. */
  22. #include <unistd.h>
  23. #include <string.h>
  24. #include <fcntl.h>
  25. #include <paths.h>
  26. #include <stdlib.h>
  27. #include <errno.h>
  28. #include "config.h"
  29. #ifdef __UCLIBC_HAS_THREADS__
  30. #include <pthread.h>
  31. static pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
  32. # define LOCK pthread_mutex_lock(&mylock)
  33. # define UNLOCK pthread_mutex_unlock(&mylock);
  34. #else
  35. # define LOCK
  36. # define UNLOCK
  37. #endif
  38. int initgroups(__const char *user, gid_t gid)
  39. {
  40. gid_t *group_list = NULL;
  41. register char **tmp_mem;
  42. int num_groups;
  43. int grp_fd;
  44. static struct group group;
  45. static char line_buff[PWD_BUFFER_SIZE];
  46. if ((grp_fd = open(_PATH_GROUP, O_RDONLY)) < 0)
  47. return errno;
  48. num_groups = 0;
  49. group_list = (gid_t *) realloc(group_list, 1);
  50. group_list[num_groups] = gid;
  51. LOCK;
  52. while (__getgrent_r(&group, line_buff, sizeof(line_buff), grp_fd) == 0)
  53. {
  54. if (group.gr_gid != gid)
  55. {
  56. tmp_mem = group.gr_mem;
  57. while (*tmp_mem != NULL) {
  58. if (!strcmp(*tmp_mem, user)) {
  59. num_groups++;
  60. group_list = (gid_t *) realloc(group_list, num_groups * sizeof(gid_t *));
  61. group_list[num_groups-1] = group.gr_gid;
  62. }
  63. tmp_mem++;
  64. }
  65. }
  66. }
  67. close(grp_fd);
  68. UNLOCK;
  69. return setgroups(num_groups, group_list);
  70. }