lazysphere/src/commands/id.c
2023-05-04 16:10:37 -04:00

53 lines
1.1 KiB
C

#include "../command.h"
#include <grp.h>
#include <pwd.h>
COMMAND_EMPTY(user_id) {
uid_t uid;
gid_t gid, *groups;
int ngroups, i;
struct passwd* pw;
struct group* ugr;
uid = getuid();
gid = getgid();
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);
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: %s", strerror(errno));
}
printf("%d(%s)", gr->gr_gid, gr->gr_name);
if (i + 1 < ngroups) putchar(',');
}
printf("\b\n");
free(groups);
return EXIT_SUCCESS;
}