From d8f2c10b7108fff6b7e437291093a1cadc15ab9f Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Sat, 6 May 2023 00:39:44 -0400 Subject: refactor --- command/groups.c | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 command/groups.c (limited to 'command/groups.c') diff --git a/command/groups.c b/command/groups.c new file mode 100644 index 0000000..cb950be --- /dev/null +++ b/command/groups.c @@ -0,0 +1,63 @@ +#include "args.h" +#include "command.h" +#include "lslib.h" + +#include +#include +#include +#include +#include +#include + +static void help (void) { + printf("Usage: groups [USER]\n\n"); + printf("Print the groups USER is in\n"); +} + +COMMAND(groups) { + + uid_t uid; + int ngroups, i; + gid_t* groups; + struct passwd* pw; + + 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: %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); + + 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("%s ",gr->gr_name); + } + + printf("\n"); + + free(groups); + + return EXIT_SUCCESS; +} -- cgit v1.2.3-freya