LIRC libraries LinuxInfraredRemoteControl

- Main Page
- Related Pages
- Modules
- Data Structures
- Files
- Examples

- File List
- Globals

util.c
Go to the documentation of this file.
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 "util.h"
25
26
27 const char* drop_sudo_root(int (*set_some_uid)(uid_t))
28 {
29 struct passwd* pw;
30 char* user;
31 gid_t groups[32];
32 int group_cnt = sizeof(groups)/sizeof(gid_t);
33 char groupnames[256] = {0};
34 char buff[12];
35 int r;
36 int i;
37
38 if (getuid() != 0)
39 return "";
40 user = getenv("SUDO_USER");
41 if (user == NULL)
42 return "root";
43 pw = getpwnam(user);
44 if (pw == NULL) {
45 logperror(LIRC_ERROR, "Can't run getpwnam() for %s", user);
46 return "";
47 }
48 r = getgrouplist(user, pw->pw_gid, groups, &group_cnt);
49 if (r == -1) {
50 logperror(LIRC_WARNING, "Cannot get supplementary groups");
51 return "";
52 }
53 r = setgroups(group_cnt, groups);
54 if (r == -1) {
55 logperror(LIRC_WARNING, "Cannot set supplementary groups");
56 return "";
57 }
58 r = setgid(pw->pw_gid);
59 if (r == -1) {
60 logperror(LIRC_WARNING, "Cannot set GID");
61 return "";
62 }
63 r = set_some_uid(pw->pw_uid);
64 if (r == -1) {
65 logperror(LOG_WARNING, "Cannot change UID to %d", pw->pw_uid);
66 return "";
67 }
68 setenv("HOME", pw->pw_dir, 1);
69 logprintf(LIRC_NOTICE, "Running as user %s", user);
70 for (i = 0; i < group_cnt; i += 1) {
71 snprintf(buff, 5, " %d", groups[i]);
72 strcat(groupnames, buff);
73 }
74 logprintf(LIRC_DEBUG, "Groups: [%d]:%s", pw->pw_gid, groupnames);
75
76 return pw->pw_name;
77 }
78
79
80 void drop_root_cli(int (*set_some_uid)(uid_t))
81 {
82 const char* new_user;
83
84 new_user = drop_sudo_root(set_some_uid);
85 if (strcmp("root", new_user) == 0)
86 puts("Warning: Running as root.");
87 else if (strlen(new_user) == 0)
88 puts("Warning: Cannot change uid.");
89 else
90 printf("Running as regular user %s\n", new_user);
91 }
util.h
Utilities.
drop_root_cli
void drop_root_cli(int(*set_some_uid)(uid_t))
Definition: util.c:80
drop_sudo_root
const char * drop_sudo_root(int(*set_some_uid)(uid_t))
Definition: util.c:27
logperror
void logperror(loglevel_t prio, const char *fmt,...)
Definition: lirc_log.c:289