1 /* vi: set sw=4 ts=4: */
3 * Mini id implementation for busybox
5 * Copyright (C) 2000 by Randolph Chung <tausq@debian.org>
7 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
10 /* BB_AUDIT SUSv3 compliant. */
11 /* Hacked by Tito Ragusa (C) 2004 to handle usernames of whatever length and to
12 * be more similar to GNU id.
13 * -Z option support: by Yuichi Nakamura <ynakam@hitachisoft.jp>
14 * Added -G option Tito Ragusa (C) 2008 for SUSv3.
20 #define NAME_NOT_NUMBER 2
23 #define JUST_ALL_GROUPS 16
25 #define JUST_CONTEXT 32
28 static int printf_full(unsigned int id, const char *arg, const char *prefix)
30 const char *fmt = "%s%u";
31 int status = EXIT_FAILURE;
35 status = EXIT_SUCCESS;
37 printf(fmt, prefix, id, arg);
41 int id_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
42 int id_main(int argc UNUSED_PARAM, char **argv)
52 security_context_t scontext;
54 /* Don't allow -n -r -nr -ug -rug -nug -rnug */
55 /* Don't allow more than one username */
56 opt_complementary = "?1:u--g:g--u:G--u:u--G:g--G:G--g:r?ugG:n?ugG" USE_SELINUX(":u--Z:Z--u:g--Z:Z--g");
57 flags = getopt32(argv, "rnugG" USE_SELINUX("Z"));
59 /* This values could be overwritten later */
62 if (flags & PRINT_REAL) {
68 p = getpwnam(argv[optind]);
69 /* xuname2uid is needed because it exits on failure */
70 uid = xuname2uid(argv[optind]);
72 /* in this case PRINT_REAL is the same */
75 n = getgroups(0, NULL);
76 groups = xmalloc(sizeof(groups[0]) * n);
79 if (flags & JUST_ALL_GROUPS) {
81 if (flags & NAME_NOT_NUMBER)
82 printf("%s", bb_getgrgid(NULL, 0, *groups++));
84 printf("%d", (int) *groups++);
85 bb_putchar((n > 0) ? ' ' : '\n');
88 fflush_stdout_and_exit(EXIT_SUCCESS);
91 if (flags & (JUST_GROUP | JUST_USER USE_SELINUX(| JUST_CONTEXT))) {
92 /* JUST_GROUP and JUST_USER are mutually exclusive */
93 if (flags & NAME_NOT_NUMBER) {
94 /* bb_getXXXid(-1) exit on failure, puts cannot segfault */
95 puts((flags & JUST_USER) ? bb_getpwuid(NULL, -1, uid) : bb_getgrgid(NULL, -1, gid));
97 if (flags & JUST_USER) {
100 if (flags & JUST_GROUP) {
106 if (flags & JUST_CONTEXT) {
109 bb_error_msg_and_die("user name can't be passed with -Z");
112 if (getcon(&scontext)) {
113 bb_error_msg_and_die("can't get process context");
119 fflush_stdout_and_exit(EXIT_SUCCESS);
122 /* Print full info like GNU id */
123 /* bb_getpwuid(0) doesn't exit on failure (returns NULL) */
124 status = printf_full(uid, bb_getpwuid(NULL, 0, uid), "uid=");
125 status |= printf_full(gid, bb_getgrgid(NULL, 0, gid), " gid=");
127 const char *msg = " groups=";
129 status |= printf_full(*groups, bb_getgrgid(NULL, 0, *groups), msg);
134 /* we leak groups vector... */
137 if (is_selinux_enabled()) {
138 security_context_t mysid;
144 context = alloca(strlen(mysid) + 1);
145 strcpy((char*)context, mysid);
148 printf(" context=%s", context);
153 fflush_stdout_and_exit(status);