9b2d60dc742df0f387b293c6297042dc4da1baef
[oweals/busybox.git] / coreutils / id.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini id implementation for busybox
4  *
5  * Copyright (C) 2000 by Randolph Chung <tausq@debian.org>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  *
21  */
22
23 /* BB_AUDIT SUSv3 _NOT_ compliant -- option -G is not currently supported. */
24
25 #include "busybox.h"
26 #include <stdio.h>
27 #include <unistd.h>
28 #include <getopt.h>
29 #include <string.h>
30 #include <sys/types.h>
31
32 #define NO_GROUP          1
33 #define NO_USER           2
34 #define PRINT_REAL        4
35 #define NAME_NOT_NUMBER   8
36
37 extern int id_main(int argc, char **argv)
38 {
39         char user[9], group[9];
40         long pwnam, grnam;
41         int uid, gid;
42         int flags;
43         
44         flags = bb_getopt_ulflags(argc, argv, "ugrn");
45
46         if (((flags & (NO_USER | NO_GROUP)) == (NO_USER | NO_GROUP))
47                 || (argc > optind + 1)
48         ) {
49                 bb_show_usage();
50         }
51
52         if (argv[optind] == NULL) {
53                 if (flags & PRINT_REAL) {
54                         uid = getuid();
55                         gid = getgid();
56                 } else {
57                         uid = geteuid();
58                         gid = getegid();
59                 }
60                 my_getpwuid(user, uid);
61         } else {
62                 safe_strncpy(user, argv[optind], sizeof(user));
63             gid = my_getpwnamegid(user);
64         }
65         my_getgrgid(group, gid);
66
67         pwnam=my_getpwnam(user);
68         grnam=my_getgrnam(group);
69
70         if (flags & (NO_GROUP | NO_USER)) {
71                 char *s = group;
72                 if (flags & NO_GROUP) {
73                         s = user;
74                         grnam = pwnam;
75                 }
76                 if (flags & NAME_NOT_NUMBER) {
77                         puts(s);
78                 } else {
79                         printf("%ld\n", grnam);
80                 }
81         } else {
82                 printf("uid=%ld(%s) gid=%ld(%s)\n", pwnam, user, grnam, group);
83         }
84
85         bb_fflush_stdout_and_exit(0);
86 }