summaryrefslogtreecommitdiff
path: root/src/commands/groups.c
blob: bd2e5f9bb4803e8be0d12962b5173f893e966f19 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include "../command.h"

#include <grp.h>
#include <pwd.h>

COMMAND_EMPTY(groups) {

    uid_t uid;
    int ngroups, i;
    gid_t* groups;
    struct passwd* pw;

    uid = getuid();
    
    pw = getpwuid(uid);
    if(pw == NULL){
        error("failed to fetch groups: %s", strerror(errno));
    }
    
    ngroups = 0;
    getgrouplist(pw->pw_name, pw->pw_gid, NULL, &ngroups);
    
    groups = malloc(sizeof(gid_t) * ngroups);
    getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups);
   
    for (i = 0; i < ngroups; i++){
        struct group* gr = getgrgid(groups[i]);

        if(gr == NULL) {
            free(groups);
            error("failed to fetch groups: %s", strerror(errno));
        }

        printf("%s ",gr->gr_name);
    }

    printf("\n");

    free(groups);

    return EXIT_SUCCESS;
}