commit dac77d3089f3b5233ca6f0a4c10ebc860c54bf9a
parent 137ebef3aca354e79d259553c3a0756cda0af9cc
Author: sin <sin@2f30.org>
Date: Sun, 1 Dec 2013 10:40:14 +0000
Add support to display user and group info for any user
Currently we only handle login names - it should be trivial to
fix to allow for parsing UIDs as well.
Diffstat:
M | id.1 | | | 8 | ++++++-- |
M | id.c | | | 49 | +++++++++++++++++++++++++++++++++++++++++++++++-- |
2 files changed, 53 insertions(+), 4 deletions(-)
diff --git a/id.1 b/id.1
@@ -1,8 +1,12 @@
.TH ID 1 sbase\-VERSION
.SH NAME
id \- print real and effective user and group IDs
-.SH DESCRIPTION
+.SH SYNOPSIS
.B id
-Print user and group information for the current user.
+.RB [ user ]
+.SH DESCRIPTION
+Print user and group information of the calling process to standard output.
+If a login name is specified, the user and group information of that user
+is displayed.
.SH SEE ALSO
.IR who(1)
diff --git a/id.c b/id.c
@@ -1,5 +1,6 @@
/* See LICENSE file for copyright and license details. */
#include <sys/types.h>
+#include <errno.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
@@ -8,28 +9,72 @@
#include <limits.h>
#include "util.h"
+static void user(struct passwd *pw);
static void curproc(void);
static void
usage(void)
{
- eprintf("usage: %s\n", argv0);
+ eprintf("usage: %s [user]\n", argv0);
}
int
main(int argc, char *argv[])
{
+ struct passwd *pw;
+
ARGBEGIN {
default:
usage();
} ARGEND;
- curproc();
+ switch (argc) {
+ case 0:
+ curproc();
+ break;
+ case 1:
+ errno = 0;
+ pw = getpwnam(argv[0]);
+ if (errno != 0)
+ eprintf("getpwnam %s:", argv[0]);
+ else if (!pw)
+ eprintf("getpwnam %s: no such user\n", argv[0]);
+ user(pw);
+ break;
+ default:
+ usage();
+ }
return EXIT_SUCCESS;
}
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');
+}
+
+static void
curproc(void)
{
struct passwd *pw;