lazysphere/command/id.c

77 lines
1.5 KiB
C
Raw Normal View History

2023-05-06 04:39:44 +00:00
#include "args.h"
#include "command.h"
#include "lslib.h"
2023-04-27 23:41:32 +00:00
2023-05-06 04:39:44 +00:00
#include <errno.h>
2023-04-27 23:41:32 +00:00
#include <grp.h>
#include <pwd.h>
2023-05-06 04:39:44 +00:00
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
2023-04-27 23:41:32 +00:00
2023-05-06 04:39:44 +00:00
static void help (void) {
printf("Usage: id [USER]\n\n");
printf("Print information about the USER\n");
}
COMMAND(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-06 04:39:44 +00:00
parse_help(argc, argv, help);
2023-04-27 23:41:32 +00:00
2023-05-06 04:39:44 +00:00
if (argc < 1) {
uid = getuid();
pw = getpwuid(uid);
} else {
pw = getpwnam(argv[0]);
}
2023-04-27 23:41:32 +00:00
if(pw == NULL){
2023-05-06 04:39:44 +00:00
if (errno == 0) {
error("user not found");
} else {
error("failed to fetch groups: %s", strerror(errno));
}
2023-04-27 23:41:32 +00:00
}
2023-05-06 04:39:44 +00:00
uid = pw->pw_uid;
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-06 04:39:44 +00:00
gid = pw->pw_gid;
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;
}