getgroups.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /* This test was ripped out of GNU 'id' from coreutils-5.0
  2. * by Erik Andersen.
  3. *
  4. *
  5. * id is Copyright (C) 1989-2003 Free Software Foundation, Inc.
  6. * and licensed under the GPL v2 or later, and was written by
  7. * Arnold Robbins, with a major rewrite by David MacKenzie,
  8. */
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <unistd.h>
  12. #include <sys/types.h>
  13. #include <pwd.h>
  14. #include <grp.h>
  15. #include <err.h>
  16. /* The number of errors encountered so far. */
  17. static int problems = 0;
  18. /* Print the name or value of group ID GID. */
  19. static void print_group(gid_t gid)
  20. {
  21. struct group *grp = NULL;
  22. grp = getgrgid(gid);
  23. if (grp == NULL) {
  24. warn("cannot find name for group ID %u", gid);
  25. problems++;
  26. }
  27. if (grp == NULL)
  28. printf("%u", (unsigned)gid);
  29. else
  30. printf("%s", grp->gr_name);
  31. }
  32. static int xgetgroups(gid_t gid, int *n_groups, gid_t ** groups)
  33. {
  34. int max_n_groups;
  35. int ng;
  36. gid_t *g;
  37. int fail = 0;
  38. max_n_groups = getgroups(0, NULL);
  39. /* Add 1 just in case max_n_groups is zero. */
  40. g = (gid_t *) malloc(max_n_groups * sizeof(gid_t) + 1);
  41. if (g == NULL)
  42. err(EXIT_FAILURE, "out of memory");
  43. ng = getgroups(max_n_groups, g);
  44. if (ng < 0) {
  45. warn("cannot get supplemental group list");
  46. ++fail;
  47. free(g);
  48. }
  49. if (!fail) {
  50. *n_groups = ng;
  51. *groups = g;
  52. }
  53. return fail;
  54. }
  55. /* Print all of the distinct groups the user is in. */
  56. int main(int argc, char *argv[])
  57. {
  58. struct passwd *pwd;
  59. pwd = getpwuid(getuid());
  60. if (pwd == NULL)
  61. problems++;
  62. print_group(getgid());
  63. if (getegid() != getgid()) {
  64. putchar(' ');
  65. print_group(getegid());
  66. }
  67. {
  68. int n_groups = 0;
  69. gid_t *groups;
  70. register int i;
  71. if (xgetgroups((pwd ? pwd->pw_gid : (gid_t) - 1),
  72. &n_groups, &groups)) {
  73. return ++problems;
  74. }
  75. for (i = 0; i < n_groups; i++)
  76. if (groups[i] != getgid() && groups[i] != getegid()) {
  77. putchar(' ');
  78. print_group(groups[i]);
  79. }
  80. free(groups);
  81. }
  82. putchar('\n');
  83. return (problems != 0);
  84. }