| LIRC libraries LinuxInfraredRemoteControl

lirc-utils.c
1 /****************************************************************************
2 * util.c ***************************************************************
3 ****************************************************************************
4 */
5
12 #include <grp.h>
13 #include <pwd.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <sys/types.h>
17 #include <unistd.h>
18
19 #ifdef HAVE_CONFIG_H
20 # include <config.h>
21 #endif
22
23 #include "lirc/lirc_log.h"
24 #include "lirc-utils.h"
25
26 static const logchannel_t logchannel = LOG_LIB;
27
28 #ifdef HAVE_INT_GETGROUPLIST_GROUPS
29 #define lirc_gid int
30 #else
31 #define lirc_gid gid_t
32 #endif
33
34
35 const char* drop_sudo_root(int (*set_some_uid)(uid_t))
36 {
37 struct passwd* pw;
38 char* user;
39 lirc_gid groups[32];
40 int group_cnt = sizeof(groups)/sizeof(gid_t);
41 char groupnames[256] = {0};
42 char buff[12];
43 int r;
44 int i;
45
46 if (getuid() != 0)
47 return "";
48 user = getenv("SUDO_USER");
49 if (user == NULL)
50 return "root";
51 pw = getpwnam(user);
52 if (pw == NULL) {
53 log_perror_err("Can't run getpwnam() for %s", user);
54 return "";
55 }
56 r = getgrouplist(user, pw->pw_gid, groups, &group_cnt);
57 if (r == -1) {
58 log_perror_warn("Cannot get supplementary groups");
59 return "";
60 }
61 r = setgroups(group_cnt, groups);
62 if (r == -1) {
63 log_perror_warn("Cannot set supplementary groups");
64 return "";
65 }
66 r = setgid(pw->pw_gid);
67 if (r == -1) {
68 log_perror_warn("Cannot set GID");
69 return "";
70 }
71 r = set_some_uid(pw->pw_uid);
72 if (r == -1) {
73 log_perror_warn("Cannot change UID to %d", pw->pw_uid);
74 return "";
75 }
76 setenv("HOME", pw->pw_dir, 1);
77 log_notice("Running as user %s", user);
78 for (i = 0; i < group_cnt; i += 1) {
79 snprintf(buff, 5, " %d", groups[i]);
80 strcat(groupnames, buff);
81 }
82 log_debug("Groups: [%d]:%s", pw->pw_gid, groupnames);
83
84 return pw->pw_name;
85 }
86
87
88 void drop_root_cli(int (*set_some_uid)(uid_t))
89 {
90 const char* new_user;
91
92 new_user = drop_sudo_root(set_some_uid);
93 if (strcmp("root", new_user) == 0)
94 puts("Warning: Running as root.");
95 else if (strlen(new_user) == 0)
96 puts("Warning: Cannot change uid.");
97 else
98 printf("Running as regular user %s\n", new_user);
99 }
log_debug
#define log_debug(fmt,...)
Definition: lirc_log.h:124
logchannel_t
logchannel_t
Definition: lirc_log.h:53
log_perror_err
#define log_perror_err(fmt,...)
Definition: lirc_log.h:89
lirc-utils.h
Utilities.
drop_root_cli
void drop_root_cli(int(*set_some_uid)(uid_t))
Definition: lirc-utils.c:88
drop_sudo_root
const char * drop_sudo_root(int(*set_some_uid)(uid_t))
Definition: lirc-utils.c:35
log_perror_warn
#define log_perror_warn(fmt,...)
Definition: lirc_log.h:94
log_notice
#define log_notice(fmt,...)
Definition: lirc_log.h:119