id: support multiple specified users
[coreutils.git] / src / id.c
blob2f89736b13c8a69de2eb9be12aee9ca1c82dfa46
1 /* id -- print real and effective UIDs and GIDs
2 Copyright (C) 1989-2018 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* Written by Arnold Robbins.
18 Major rewrite by David MacKenzie, djm@gnu.ai.mit.edu. */
20 #include <config.h>
21 #include <stdio.h>
22 #include <sys/types.h>
23 #include <pwd.h>
24 #include <grp.h>
25 #include <getopt.h>
26 #include <selinux/selinux.h>
28 #include "system.h"
29 #include "die.h"
30 #include "error.h"
31 #include "mgetgroups.h"
32 #include "quote.h"
33 #include "group-list.h"
34 #include "smack.h"
35 #include "userspec.h"
37 /* The official name of this program (e.g., no 'g' prefix). */
38 #define PROGRAM_NAME "id"
40 #define AUTHORS \
41 proper_name ("Arnold Robbins"), \
42 proper_name ("David MacKenzie")
44 /* If nonzero, output only the SELinux context. */
45 static bool just_context = 0;
46 /* If true, delimit entries with NUL characters, not whitespace */
47 static bool opt_zero = false;
48 /* If true, output the list of all group IDs. -G */
49 static bool just_group_list = false;
50 /* If true, output only the group ID(s). -g */
51 static bool just_group = false;
52 /* If true, output real UID/GID instead of default effective UID/GID. -r */
53 static bool use_real = false;
54 /* If true, output only the user ID(s). -u */
55 static bool just_user = false;
56 /* True unless errors have been encountered. */
57 static bool ok = true;
58 /* If true, we are using multiple users. Terminate -G with double NUL. */
59 static bool multiple_users = false;
60 /* If true, output user/group name instead of ID number. -n */
61 static bool use_name = false;
63 /* The real and effective IDs of the user to print. */
64 static uid_t ruid, euid;
65 static gid_t rgid, egid;
67 /* The SELinux context. Start with a known invalid value so print_full_info
68 knows when 'context' has not been set to a meaningful value. */
69 static char *context = NULL;
71 static void print_user (uid_t uid);
72 static void print_full_info (const char *username);
73 static void print_stuff (const char *pw_name);
75 static struct option const longopts[] =
77 {"context", no_argument, NULL, 'Z'},
78 {"group", no_argument, NULL, 'g'},
79 {"groups", no_argument, NULL, 'G'},
80 {"name", no_argument, NULL, 'n'},
81 {"real", no_argument, NULL, 'r'},
82 {"user", no_argument, NULL, 'u'},
83 {"zero", no_argument, NULL, 'z'},
84 {GETOPT_HELP_OPTION_DECL},
85 {GETOPT_VERSION_OPTION_DECL},
86 {NULL, 0, NULL, 0}
89 void
90 usage (int status)
92 if (status != EXIT_SUCCESS)
93 emit_try_help ();
94 else
96 printf (_("Usage: %s [OPTION]... [USER]...\n"), program_name);
97 fputs (_("\
98 Print user and group information for each specified USER,\n\
99 or (when USER omitted) for the current user.\n\
100 \n"),
101 stdout);
102 fputs (_("\
103 -a ignore, for compatibility with other versions\n\
104 -Z, --context print only the security context of the process\n\
105 -g, --group print only the effective group ID\n\
106 -G, --groups print all group IDs\n\
107 -n, --name print a name instead of a number, for -ugG\n\
108 -r, --real print the real ID instead of the effective ID, with -ugG\n\
109 -u, --user print only the effective user ID\n\
110 -z, --zero delimit entries with NUL characters, not whitespace;\n\
111 not permitted in default format\n\
112 "), stdout);
113 fputs (HELP_OPTION_DESCRIPTION, stdout);
114 fputs (VERSION_OPTION_DESCRIPTION, stdout);
115 fputs (_("\
117 Without any OPTION, print some useful set of identified information.\n\
118 "), stdout);
119 emit_ancillary_info (PROGRAM_NAME);
121 exit (status);
125 main (int argc, char **argv)
127 int optc;
128 int selinux_enabled = (is_selinux_enabled () > 0);
129 bool smack_enabled = is_smack_enabled ();
130 char *pw_name = NULL;
132 initialize_main (&argc, &argv);
133 set_program_name (argv[0]);
134 setlocale (LC_ALL, "");
135 bindtextdomain (PACKAGE, LOCALEDIR);
136 textdomain (PACKAGE);
138 atexit (close_stdout);
140 while ((optc = getopt_long (argc, argv, "agnruzGZ", longopts, NULL)) != -1)
142 switch (optc)
144 case 'a':
145 /* Ignore -a, for compatibility with SVR4. */
146 break;
148 case 'Z':
149 /* politely decline if we're not on a SELinux/SMACK-enabled kernel. */
150 #ifdef HAVE_SMACK
151 if (!selinux_enabled && !smack_enabled)
152 die (EXIT_FAILURE, 0,
153 _("--context (-Z) works only on "
154 "an SELinux/SMACK-enabled kernel"));
155 #else
156 if (!selinux_enabled)
157 die (EXIT_FAILURE, 0,
158 _("--context (-Z) works only on an SELinux-enabled kernel"));
159 #endif
160 just_context = true;
161 break;
163 case 'g':
164 just_group = true;
165 break;
166 case 'n':
167 use_name = true;
168 break;
169 case 'r':
170 use_real = true;
171 break;
172 case 'u':
173 just_user = true;
174 break;
175 case 'z':
176 opt_zero = true;
177 break;
178 case 'G':
179 just_group_list = true;
180 break;
181 case_GETOPT_HELP_CHAR;
182 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
183 default:
184 usage (EXIT_FAILURE);
188 size_t n_ids = argc - optind;
190 if (n_ids && just_context)
191 die (EXIT_FAILURE, 0,
192 _("cannot print security context when user specified"));
194 if (just_user + just_group + just_group_list + just_context > 1)
195 die (EXIT_FAILURE, 0, _("cannot print \"only\" of more than one choice"));
197 bool default_format = ! (just_user
198 || just_group
199 || just_group_list
200 || just_context);
202 if (default_format && (use_real || use_name))
203 die (EXIT_FAILURE, 0,
204 _("cannot print only names or real IDs in default format"));
206 if (default_format && opt_zero)
207 die (EXIT_FAILURE, 0,
208 _("option --zero not permitted in default format"));
210 /* If we are on a SELinux/SMACK-enabled kernel, no user is specified, and
211 either --context is specified or none of (-u,-g,-G) is specified,
212 and we're not in POSIXLY_CORRECT mode, get our context. Otherwise,
213 leave the context variable alone - it has been initialized to an
214 invalid value that will be not displayed in print_full_info(). */
215 if (n_ids == 0
216 && (just_context
217 || (default_format && ! getenv ("POSIXLY_CORRECT"))))
219 /* Report failure only if --context (-Z) was explicitly requested. */
220 if ((selinux_enabled && getcon (&context) && just_context)
221 || (smack_enabled
222 && smack_new_label_from_self (&context) < 0
223 && just_context))
224 die (EXIT_FAILURE, 0, _("can't get process context"));
227 if (n_ids >= 1)
229 multiple_users = n_ids > 1 ? true : false;
230 /* Changing the value of n_ids to the last index in the array where we
231 have the last possible user id. This helps us because we don't have
232 to declare a different variable to keep a track of where the
233 last username lies in argv[]. */
234 n_ids += optind;
235 /* For each username/userid to get its pw_name field */
236 for (; optind < n_ids; optind++)
238 struct passwd *pwd = NULL;
239 const char *spec = argv[optind];
240 /* Disallow an empty spec here as parse_user_spec() doesn't
241 give an error for that as it seems it's a valid way to
242 specify a noop or "reset special bits" depending on the system. */
243 if (*spec)
245 if (parse_user_spec (spec, &euid, NULL, NULL, NULL) == NULL)
247 /* parse_user_spec will only extract a numeric spec,
248 so we lookup that here to verify and also retrieve
249 the PW_NAME used subsequently in group lookup. */
250 pwd = getpwuid (euid);
253 if (pwd == NULL)
255 error (0, errno, _("%s: no such user"), quote (argv[optind]));
256 ok &= false;
257 continue;
259 pw_name = xstrdup (pwd->pw_name);
260 ruid = euid = pwd->pw_uid;
261 rgid = egid = pwd->pw_gid;
262 print_stuff (pw_name);
263 free (pw_name);
266 else
268 /* POSIX says identification functions (getuid, getgid, and
269 others) cannot fail, but they can fail under GNU/Hurd and a
270 few other systems. Test for failure by checking errno. */
271 uid_t NO_UID = -1;
272 gid_t NO_GID = -1;
274 if (just_user ? !use_real
275 : !just_group && !just_group_list && !just_context)
277 errno = 0;
278 euid = geteuid ();
279 if (euid == NO_UID && errno)
280 die (EXIT_FAILURE, errno, _("cannot get effective UID"));
283 if (just_user ? use_real
284 : !just_group && (just_group_list || !just_context))
286 errno = 0;
287 ruid = getuid ();
288 if (ruid == NO_UID && errno)
289 die (EXIT_FAILURE, errno, _("cannot get real UID"));
292 if (!just_user && (just_group || just_group_list || !just_context))
294 errno = 0;
295 egid = getegid ();
296 if (egid == NO_GID && errno)
297 die (EXIT_FAILURE, errno, _("cannot get effective GID"));
299 errno = 0;
300 rgid = getgid ();
301 if (rgid == NO_GID && errno)
302 die (EXIT_FAILURE, errno, _("cannot get real GID"));
304 print_stuff (pw_name);
307 return ok ? EXIT_SUCCESS : EXIT_FAILURE;
310 /* Convert a gid_t to string. Do not use this function directly.
311 Instead, use it via the gidtostr macro.
312 Beware that it returns a pointer to static storage. */
313 static char *
314 gidtostr_ptr (gid_t const *gid)
316 static char buf[INT_BUFSIZE_BOUND (uintmax_t)];
317 return umaxtostr (*gid, buf);
319 #define gidtostr(g) gidtostr_ptr (&(g))
321 /* Convert a uid_t to string. Do not use this function directly.
322 Instead, use it via the uidtostr macro.
323 Beware that it returns a pointer to static storage. */
324 static char *
325 uidtostr_ptr (uid_t const *uid)
327 static char buf[INT_BUFSIZE_BOUND (uintmax_t)];
328 return umaxtostr (*uid, buf);
330 #define uidtostr(u) uidtostr_ptr (&(u))
332 /* Print the name or value of user ID UID. */
334 static void
335 print_user (uid_t uid)
337 struct passwd *pwd = NULL;
339 if (use_name)
341 pwd = getpwuid (uid);
342 if (pwd == NULL)
344 error (0, 0, _("cannot find name for user ID %s"),
345 uidtostr (uid));
346 ok &= false;
350 char *s = pwd ? pwd->pw_name : uidtostr (uid);
351 fputs (s, stdout);
354 /* Print all of the info about the user's user and group IDs. */
356 static void
357 print_full_info (const char *username)
359 struct passwd *pwd;
360 struct group *grp;
362 printf (_("uid=%s"), uidtostr (ruid));
363 pwd = getpwuid (ruid);
364 if (pwd)
365 printf ("(%s)", pwd->pw_name);
367 printf (_(" gid=%s"), gidtostr (rgid));
368 grp = getgrgid (rgid);
369 if (grp)
370 printf ("(%s)", grp->gr_name);
372 if (euid != ruid)
374 printf (_(" euid=%s"), uidtostr (euid));
375 pwd = getpwuid (euid);
376 if (pwd)
377 printf ("(%s)", pwd->pw_name);
380 if (egid != rgid)
382 printf (_(" egid=%s"), gidtostr (egid));
383 grp = getgrgid (egid);
384 if (grp)
385 printf ("(%s)", grp->gr_name);
389 gid_t *groups;
391 gid_t primary_group;
392 if (username)
393 primary_group = pwd ? pwd->pw_gid : -1;
394 else
395 primary_group = egid;
397 int n_groups = xgetgroups (username, primary_group, &groups);
398 if (n_groups < 0)
400 if (username)
401 error (0, errno, _("failed to get groups for user %s"),
402 quote (username));
403 else
404 error (0, errno, _("failed to get groups for the current process"));
405 ok &= false;
406 return;
409 if (n_groups > 0)
410 fputs (_(" groups="), stdout);
411 for (int i = 0; i < n_groups; i++)
413 if (i > 0)
414 putchar (',');
415 fputs (gidtostr (groups[i]), stdout);
416 grp = getgrgid (groups[i]);
417 if (grp)
418 printf ("(%s)", grp->gr_name);
420 free (groups);
423 /* POSIX mandates the precise output format, and that it not include
424 any context=... part, so skip that if POSIXLY_CORRECT is set. */
425 if (context)
426 printf (_(" context=%s"), context);
429 /* Print information about the user based on the arguments passed. */
431 static void
432 print_stuff (const char *pw_name)
434 if (just_user)
435 print_user (use_real ? ruid : euid);
437 /* print_group and print_group_lists functions return true on successful
438 execution but false if something goes wrong. We then AND this value with
439 the current value of 'ok' because we want to know if one of the previous
440 users faced a problem in these functions. This value of 'ok' is later used
441 to understand what status program should exit with. */
442 else if (just_group)
443 ok &= print_group (use_real ? rgid : egid, use_name);
444 else if (just_group_list)
445 ok &= print_group_list (pw_name, ruid, rgid, egid,
446 use_name, opt_zero ? '\0' : ' ');
447 else if (just_context)
448 fputs (context, stdout);
449 else
450 print_full_info (pw_name);
452 /* When printing records for more than 1 user, at the end of groups
453 of each user terminate the record with two consequent NUL characters
454 to make parsing and distinguishing between two records possible. */
455 if (opt_zero && just_group_list && multiple_users)
457 putchar ('\0');
458 putchar ('\0');
460 else
462 putchar (opt_zero ? '\0' : '\n');