added demo of signal/uid handling feature
[tridge/junkcode.git] / initgroups.c
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <stdlib.h>
4 #include <grp.h>
5 #include <pwd.h>
6 #include <sys/types.h>
7 #include <errno.h>
8
9 int listgroups(char *user)
10 {
11         struct passwd *pass;
12         struct group *grp;
13         int ngroups, i;
14         gid_t *grps;
15
16         pass = getpwnam(user);
17
18         if (!pass) {
19                 printf("Unknown user '%s'\n", user);
20                 exit(1);
21         }
22
23         if (initgroups(user, pass->pw_gid) != 0) {
24                 perror("initgroups");
25                 exit(1);
26         }
27
28         ngroups = getgroups(0, NULL);
29
30         if (ngroups == 0) {
31                 printf("Using is in no groups!\n");
32                 exit(1);
33         }
34
35         grps = (gid_t *)malloc(ngroups * sizeof(gid_t));
36         
37         if (getgroups(ngroups, grps) != ngroups) {
38                 printf("Failed to get group list!\n");
39                 exit(1);
40         }
41
42         grp = getgrgid(pass->pw_gid);
43
44         if (pass->pw_gid != grps[0]) {
45                 printf("%5d %s\n", pass->pw_gid, grp?grp->gr_name:"UNKNOWN");
46         }
47
48         for (i=0;i<ngroups;i++) {
49                 grp = getgrgid(grps[i]);
50                 printf("%5d %s\n", grps[i], grp?grp->gr_name:"UNKNOWN");
51         }
52         return ngroups;
53 }
54
55
56
57 int main(int argc, char *argv[])
58 {
59         if (argc < 2) {
60                 printf("Usage: initgroups USERNAME\n");
61                 exit(1);
62         }
63
64         if (geteuid() != 0) {
65                 printf("This program must be run as root\n");
66                 exit(1);
67         }
68
69
70         listgroups(argv[1]);
71         return 0;
72 }