summaryrefslogtreecommitdiff
path: root/src/commands/id.c
blob: 4bd7bca71aa699137415a8186244cabf3535090b (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
#include "../command.h"

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

COMMAND_EMPTY(user_id) {

    uid_t uid = getuid();
    gid_t gid = getgid();
    
    struct passwd* pw = getpwuid(uid);
    if(pw == NULL){
        error("failed to fetch groups: %s", strerror(errno));
    }
    
    int ngroups = 0;
    getgrouplist(pw->pw_name, pw->pw_gid, NULL, &ngroups);
    
    gid_t groups[ngroups];
    getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups);
   
    struct group* ugr = getgrgid(gid);
    printf("uid=%d(%s) gid=%d(%s) ",
           uid, ugr->gr_name, gid, ugr->gr_name);
    
    if (ngroups > 0) {
        printf("groups=");
    }

    for (int i = 0; i < ngroups; i++){
        struct group* gr = getgrgid(groups[i]);
        if(gr == NULL){
            error("failed to fetch groups: %s", strerror(errno));
        }
        printf("%d(%s)", gr->gr_gid, gr->gr_name);
        if (i + 1 < ngroups) putchar(',');
    }
    printf("\b\n");

    return EXIT_SUCCESS;
}