]> code.delx.au - pulseaudio/blob - polyp/caps.c
* add first part of zeroconf publisher
[pulseaudio] / polyp / caps.c
1 /* $Id$ */
2
3 /***
4 This file is part of polypaudio.
5
6 polypaudio is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published
8 by the Free Software Foundation; either version 2 of the License,
9 or (at your option) any later version.
10
11 polypaudio is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with polypaudio; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19 USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 /* setresuid() is only available on GNU */
27 #define _GNU_SOURCE
28
29 #include <assert.h>
30 #include <unistd.h>
31 #include <errno.h>
32 #include <string.h>
33
34 #ifdef HAVE_SYS_CAPABILITY_H
35 #include <sys/capability.h>
36 #endif
37
38 #include "log.h"
39 #include "caps.h"
40
41 /* Drop root rights when called SUID root */
42 void pa_drop_root(void) {
43 uid_t uid = getuid();
44
45 if (uid == 0 || geteuid() != 0)
46 return;
47
48 pa_log_info(__FILE__": dropping root rights.\n");
49
50 #if defined(HAVE_SETRESUID)
51 setresuid(uid, uid, uid);
52 #elif defined(HAVE_SETREUID)
53 setreuid(uid, uid);
54 #else
55 setuid(uid);
56 seteuid(uid);
57 #endif
58 }
59
60 #ifdef HAVE_SYS_CAPABILITY_H
61
62 /* Limit capabilities set to CAPSYS_NICE */
63 int pa_limit_caps(void) {
64 int r = -1;
65 cap_t caps;
66 cap_value_t nice_cap = CAP_SYS_NICE;
67
68 caps = cap_init();
69 assert(caps);
70
71 cap_clear(caps);
72
73 cap_set_flag(caps, CAP_EFFECTIVE, 1, &nice_cap, CAP_SET);
74 cap_set_flag(caps, CAP_PERMITTED, 1, &nice_cap, CAP_SET);
75
76 if (cap_set_proc(caps) < 0)
77 goto fail;
78
79 pa_log_info(__FILE__": dropped capabilities successfully.\n");
80
81 r = 0;
82
83 fail:
84 cap_free (caps);
85
86 return r;
87 }
88
89 /* Drop all capabilities, effectively becoming a normal user */
90 int pa_drop_caps(void) {
91 cap_t caps;
92 int r = -1;
93
94 caps = cap_init();
95 assert(caps);
96
97 cap_clear(caps);
98
99 if (cap_set_proc(caps) < 0) {
100 pa_log(__FILE__": failed to drop capabilities: %s\n", strerror(errno));
101 goto fail;
102 }
103
104 r = 0;
105
106 fail:
107 cap_free (caps);
108
109 return r;
110 }
111
112 #else
113
114 /* NOOPs in case capabilities are not available. */
115 int pa_limit_caps(void) {
116 return 0;
117 }
118
119 int pa_drop_caps(void) {
120 pa_drop_root();
121 return 0;
122 }
123
124 #endif
125