summaryrefslogtreecommitdiff
path: root/command/id.c
blob: 3d3d19edbf369c2bd3308ca6dd2782302860cce4 (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include "command.h"
#include "lslib.h"

#include <grp.h>
#include <pwd.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

static void help (void) {
    printf("Usage: id [USER]\n\n");
    printf("Print information about the USER\n");
}

COMMAND(user_id) {
    
    uid_t uid;
    gid_t gid, *groups;
    int ngroups, i;
    struct passwd* pw;
    struct group* ugr;

    parse_help(argc, argv, help);
    
    if (argc < 1) {
        uid = getuid();
        pw = getpwuid(uid);
    } else {
        pw = getpwnam(argv[0]);
    }

    if(pw == NULL){
        if (errno == 0) {
            error("user not found");
        } else {
            error("failed to fetch groups");
        }
    }

    uid = pw->pw_uid;
    
    ngroups = 0;
    getgrouplist(pw->pw_name, pw->pw_gid, NULL, &ngroups);
    
    groups = xalloc(sizeof(gid_t) * ngroups);
    getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups);
   
    gid = pw->pw_gid;
    ugr = getgrgid(gid);
    printf("uid=%d(%s) gid=%d(%s) ",
           uid, ugr->gr_name, gid, ugr->gr_name);
    
    if (ngroups > 0) {
        printf("groups=");
    }

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

    printf("\b\n");

    free(groups);

    return EXIT_SUCCESS;
}