lazysphere/command/groups.c

63 lines
1.2 KiB
C
Raw Permalink Normal View History

2023-05-06 04:39:44 +00:00
#include "command.h"
#include "lslib.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-05-15 01:43:02 +00:00
#include <errno.h>
2023-04-27 23:41:32 +00:00
2023-05-06 04:39:44 +00:00
static void help (void) {
printf("Usage: groups [USER]\n\n");
printf("Print the groups USER is in\n");
}
2023-05-15 14:57:33 +00:00
COMMAND(groups_main) {
2023-04-27 23:41:32 +00:00
2023-05-04 20:10:37 +00:00
uid_t uid;
int ngroups, i;
gid_t* groups;
struct passwd* pw;
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 {
2023-05-15 01:43:02 +00:00
error("failed to fetch groups");
2023-05-06 04:39:44 +00:00
}
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-15 01:43:02 +00:00
groups = xalloc(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
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-15 01:43:02 +00:00
error("failed to fetch groups");
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("%s ",gr->gr_name);
}
2023-05-04 20:10:37 +00:00
2023-04-27 23:41:32 +00:00
printf("\n");
2023-05-04 20:10:37 +00:00
free(groups);
2023-04-27 23:41:32 +00:00
return EXIT_SUCCESS;
}