62 lines
1.2 KiB
C
62 lines
1.2 KiB
C
#include "command.h"
|
|
#include "lslib.h"
|
|
|
|
#include <grp.h>
|
|
#include <pwd.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
#include <errno.h>
|
|
|
|
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");
|
|
}
|
|
}
|
|
|
|
ngroups = 0;
|
|
getgrouplist(pw->pw_name, pw->pw_gid, NULL, &ngroups);
|
|
|
|
groups = xalloc(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");
|
|
}
|
|
|
|
printf("%s ",gr->gr_name);
|
|
}
|
|
|
|
printf("\n");
|
|
|
|
free(groups);
|
|
|
|
return EXIT_SUCCESS;
|
|
}
|