1 /* vi: set sw=4 ts=4: */
2 /*
3 * password utility routines.
4 *
5 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6 * Copyright (C) 2008 by Tito Ragusa <farmatito@tiscali.it>
7 *
8 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
9 */
10 #include "libbb.h"
11
12 /* TODO: maybe change API to return malloced data?
13 * This will allow to stop using libc functions returning
14 * pointers to static data (getpwuid)
15 */
16
xgetpwnam(const char * name)17 struct passwd* FAST_FUNC xgetpwnam(const char *name)
18 {
19 struct passwd *pw = getpwnam(name);
20 if (!pw)
21 bb_error_msg_and_die("unknown user %s", name);
22 return pw;
23 }
24
xgetgrnam(const char * name)25 struct group* FAST_FUNC xgetgrnam(const char *name)
26 {
27 struct group *gr = getgrnam(name);
28 if (!gr)
29 bb_error_msg_and_die("unknown group %s", name);
30 return gr;
31 }
32
xgetpwuid(uid_t uid)33 struct passwd* FAST_FUNC xgetpwuid(uid_t uid)
34 {
35 /* Note: used in nofork applets (whoami), be careful not to leak anything */
36 struct passwd *pw = getpwuid(uid);
37 if (!pw)
38 bb_error_msg_and_die("unknown uid %u", (unsigned)uid);
39 return pw;
40 }
41
xgetgrgid(gid_t gid)42 struct group* FAST_FUNC xgetgrgid(gid_t gid)
43 {
44 struct group *gr = getgrgid(gid);
45 if (!gr)
46 bb_error_msg_and_die("unknown gid %u", (unsigned)gid);
47 return gr;
48 }
49
xuid2uname(uid_t uid)50 char* FAST_FUNC xuid2uname(uid_t uid)
51 {
52 /* Note: used in nofork applets (whoami), be careful not to leak anything */
53 struct passwd *pw = xgetpwuid(uid);
54 return pw->pw_name;
55 }
56
xgid2group(gid_t gid)57 char* FAST_FUNC xgid2group(gid_t gid)
58 {
59 struct group *gr = xgetgrgid(gid);
60 return gr->gr_name;
61 }
62
uid2uname(uid_t uid)63 char* FAST_FUNC uid2uname(uid_t uid)
64 {
65 struct passwd *pw = getpwuid(uid);
66 return (pw) ? pw->pw_name : NULL;
67 }
68
gid2group(gid_t gid)69 char* FAST_FUNC gid2group(gid_t gid)
70 {
71 struct group *gr = getgrgid(gid);
72 return (gr) ? gr->gr_name : NULL;
73 }
74
uid2uname_utoa(uid_t uid)75 char* FAST_FUNC uid2uname_utoa(uid_t uid)
76 {
77 char *name = uid2uname(uid);
78 return (name) ? name : utoa(uid);
79 }
80
gid2group_utoa(gid_t gid)81 char* FAST_FUNC gid2group_utoa(gid_t gid)
82 {
83 char *name = gid2group(gid);
84 return (name) ? name : utoa(gid);
85 }
86
xuname2uid(const char * name)87 long FAST_FUNC xuname2uid(const char *name)
88 {
89 struct passwd *myuser;
90
91 myuser = xgetpwnam(name);
92 return myuser->pw_uid;
93 }
94
xgroup2gid(const char * name)95 long FAST_FUNC xgroup2gid(const char *name)
96 {
97 struct group *mygroup;
98
99 mygroup = xgetgrnam(name);
100 return mygroup->gr_gid;
101 }
102
get_ug_id(const char * s,long FAST_FUNC (* xname2id)(const char *))103 unsigned long FAST_FUNC get_ug_id(const char *s,
104 long FAST_FUNC (*xname2id)(const char *))
105 {
106 unsigned long r;
107
108 r = bb_strtoul(s, NULL, 10);
109 if (errno)
110 return xname2id(s);
111 return r;
112 }
113