lazysphere/src/commands/id.c

54 lines
1.1 KiB
C
Raw Normal View History

2023-04-27 23:41:32 +00:00
#include "../command.h"
#include <grp.h>
#include <pwd.h>
COMMAND_EMPTY(user_id) {
2023-05-04 20:10:37 +00:00
uid_t uid;
gid_t gid, *groups;
int ngroups, i;
struct passwd* pw;
struct group* ugr;
2023-04-27 23:41:32 +00:00
2023-05-04 20:10:37 +00:00
uid = getuid();
gid = getgid();
2023-04-27 23:41:32 +00:00
2023-05-04 20:10:37 +00:00
pw = getpwuid(uid);
2023-04-27 23:41:32 +00:00
if(pw == NULL){
2023-05-03 16:17:56 +00:00
error("failed to fetch groups: %s", strerror(errno));
2023-04-27 23:41:32 +00:00
}
2023-05-04 20:10:37 +00:00
ngroups = 0;
2023-04-27 23:41:32 +00:00
getgrouplist(pw->pw_name, pw->pw_gid, NULL, &ngroups);
2023-05-04 20:10:37 +00:00
groups = malloc(sizeof(gid_t) * ngroups);
2023-04-27 23:41:32 +00:00
getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups);
2023-05-04 20:10:37 +00:00
ugr = getgrgid(gid);
2023-04-27 23:41:32 +00:00
printf("uid=%d(%s) gid=%d(%s) ",
uid, ugr->gr_name, gid, ugr->gr_name);
if (ngroups > 0) {
printf("groups=");
}
2023-05-04 20:10:37 +00:00
for (i = 0; i < ngroups; i++){
2023-04-27 23:41:32 +00:00
struct group* gr = getgrgid(groups[i]);
2023-05-04 20:10:37 +00:00
if(gr == NULL) {
free(groups);
2023-05-03 16:17:56 +00:00
error("failed to fetch groups: %s", strerror(errno));
2023-04-27 23:41:32 +00:00
}
2023-05-04 20:10:37 +00:00
2023-04-27 23:41:32 +00:00
printf("%d(%s)", gr->gr_gid, gr->gr_name);
2023-05-04 20:10:37 +00:00
2023-04-27 23:41:32 +00:00
if (i + 1 < ngroups) putchar(',');
}
2023-05-04 20:10:37 +00:00
2023-04-27 23:41:32 +00:00
printf("\b\n");
2023-05-04 20:10:37 +00:00
free(groups);
2023-04-27 23:41:32 +00:00
return EXIT_SUCCESS;
}