getgroups.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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
  20. print_group (gid_t gid)
  21. {
  22. struct group *grp = NULL;
  23. grp = getgrgid (gid);
  24. if (grp == NULL)
  25. {
  26. warn("cannot find name for group ID %u", gid);
  27. problems++;
  28. }
  29. if (grp == NULL)
  30. printf ("%u", (unsigned) gid);
  31. else
  32. printf ("%s", grp->gr_name);
  33. }
  34. static int
  35. xgetgroups (gid_t gid, int *n_groups, gid_t **groups)
  36. {
  37. int max_n_groups;
  38. int ng;
  39. gid_t *g;
  40. int fail = 0;
  41. max_n_groups = getgroups (0, NULL);
  42. /* Add 1 just in case max_n_groups is zero. */
  43. g = (gid_t *) malloc (max_n_groups * sizeof (gid_t) + 1);
  44. if (g==NULL)
  45. err(EXIT_FAILURE, "out of memory");
  46. ng = getgroups (max_n_groups, g);
  47. if (ng < 0)
  48. {
  49. warn("cannot get supplemental group list");
  50. ++fail;
  51. free (groups);
  52. }
  53. if (!fail)
  54. {
  55. *n_groups = ng;
  56. *groups = g;
  57. }
  58. return fail;
  59. }
  60. /* Print all of the distinct groups the user is in. */
  61. int main (int argc, char **argv)
  62. {
  63. struct passwd *pwd;
  64. pwd = getpwuid (getuid());
  65. if (pwd == NULL)
  66. problems++;
  67. print_group (getgid());
  68. if (getegid() != getgid())
  69. {
  70. putchar (' ');
  71. print_group (getegid());
  72. }
  73. {
  74. int n_groups;
  75. gid_t *groups;
  76. register int i;
  77. if (xgetgroups ((pwd ? pwd->pw_gid : (gid_t) -1),
  78. &n_groups, &groups))
  79. {
  80. return ++problems;
  81. }
  82. for (i = 0; i < n_groups; i++)
  83. if (groups[i] != getgid() && groups[i] != getegid())
  84. {
  85. putchar (' ');
  86. print_group (groups[i]);
  87. }
  88. free (groups);
  89. }
  90. putchar('\n');
  91. return (problems != 0);
  92. }