getgroups.c 1.9 KB

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