"Fossies" - the Fresh Open Source Software Archive 
Member "bonnie++-1.04/bon_suid.cpp" (3 Jul 2009, 1576 Bytes) of package /linux/privat/bonnie++_1.04.tgz:
As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style:
standard) with prefixed line numbers and
code folding option.
Alternatively you can here
view or
download the uninterpreted source code file.
For more information about "bon_suid.cpp" see the
Fossies "Dox" file reference documentation and the latest
Fossies "Diffs" side-by-side code changes report:
1.03e_vs_1.04.
1 #include <pwd.h>
2 #include <grp.h>
3 #include <unistd.h>
4 #include <stdio.h>
5 #include "bonnie.h"
6
7 int bon_setugid(CPCCHAR userName, CPCCHAR groupName, bool quiet)
8 {
9 int id = 0;
10 uid_t userId = 0;
11 gid_t groupId = 0;
12 bool setGroup = false;
13 struct passwd *pw;
14 struct group *gr;
15 if(userName)
16 {
17 if(sscanf(userName, "%d", &id) == 1)
18 {
19 userId = uid_t(id);
20 pw = getpwuid(userId);
21 if(pw)
22 {
23 groupId = pw->pw_gid;
24 setGroup = true;
25 }
26 else
27 {
28 gr = getgrnam("nogroup");
29 if(gr)
30 {
31 groupId = gr->gr_gid;
32 setGroup = true;
33 }
34 }
35 }
36 else
37 {
38 pw = getpwnam(userName);
39 if(!pw)
40 {
41 fprintf(stderr, "Can't find user %s\n", userName);
42 return 1;
43 }
44 userId = pw->pw_uid;
45 groupId = pw->pw_gid;
46 setGroup = true;
47 }
48 }
49 if(groupName)
50 {
51 if(sscanf(groupName, "%d", &id) == 1)
52 {
53 groupId = gid_t(id);
54 setGroup = true;
55 }
56 else
57 {
58 gr = getgrnam(groupName);
59 if(!gr)
60 {
61 fprintf(stderr, "Can't find group %s\n", groupName);
62 return 1;
63 }
64 groupId = gr->gr_gid;
65 setGroup = true;
66 }
67 }
68 if(setGroup)
69 {
70 if(setgid(groupId))
71 {
72 fprintf(stderr, "Can't set gid to %d.\n", int(groupId));
73 return 1;
74 }
75 }
76 if(setuid(userId))
77 {
78 fprintf(stderr, "Can't set uid to %d.\n", int(userId));
79 return 1;
80 }
81 if(!quiet)
82 fprintf(stderr, "Using uid:%d, gid:%d.\n", int(getuid()), int(getgid()));
83 return 0;
84 }