sbase/id.c

101 lines
1.7 KiB
C
Raw Normal View History

2013-08-07 08:40:21 -04:00
/* See LICENSE file for copyright and license details. */
#include <sys/types.h>
#include <errno.h>
2013-08-07 08:40:21 -04:00
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <stdio.h>
#include <stdlib.h>
2013-08-07 08:40:21 -04:00
#include <limits.h>
2013-12-01 06:40:49 -05:00
#include <ctype.h>
2013-08-07 08:40:21 -04:00
#include "util.h"
static void user(struct passwd *pw);
2013-12-01 06:40:49 -05:00
static void userid(uid_t id);
static void usernam(const char *nam);
2013-08-07 08:40:21 -04:00
static void
usage(void)
{
2013-12-01 06:40:49 -05:00
eprintf("usage: %s [user | uid]\n", argv0);
2013-08-07 08:40:21 -04:00
}
int
main(int argc, char *argv[])
{
ARGBEGIN {
default:
usage();
} ARGEND;
2013-12-01 06:31:36 -05:00
errno = 0;
switch (argc) {
case 0:
2013-12-01 06:40:49 -05:00
userid(getuid());
break;
case 1:
2013-12-01 06:40:49 -05:00
/* user names can't begin [0-9] */
if (isdigit(argv[0][0]))
userid(estrtol(argv[0], 0));
else
usernam(argv[0]);
break;
default:
usage();
}
return EXIT_SUCCESS;
}
2013-12-01 06:40:49 -05:00
static void usernam(const char *nam)
{
struct passwd *pw;
errno = 0;
pw = getpwnam(nam);
if (errno != 0)
eprintf("getpwnam %s:", nam);
else if (!pw)
eprintf("getpwnam %s: no such user\n", nam);
user(pw);
}
static void userid(uid_t id)
{
struct passwd *pw;
errno = 0;
pw = getpwuid(id);
if (errno != 0)
eprintf("getpwuid %d:", id);
else if (!pw)
eprintf("getpwuid %d: no such user\n", id);
user(pw);
}
static void
user(struct passwd *pw)
{
struct group *gr;
gid_t gid, groups[NGROUPS_MAX];
int ngroups;
int i;
printf("uid=%u(%s)", pw->pw_uid, pw->pw_name);
printf(" gid=%u", pw->pw_gid);
if (!(gr = getgrgid(pw->pw_gid)))
eprintf("getgrgid:");
printf("(%s)", gr->gr_name);
ngroups = NGROUPS_MAX;
getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups);
for (i = 0; i < ngroups; i++) {
gid = groups[i];
printf("%s%u", !i ? " groups=" : ",", gid);
if (!(gr = getgrgid(gid)))
eprintf("getgrgid:");
printf("(%s)", gr->gr_name);
}
putchar('\n');
}