xref: /qemu/os-posix.c (revision 433aed5f)
1 /*
2  * os-posix.c
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  * Copyright (c) 2010 Red Hat, Inc.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25 
26 #include "qemu/osdep.h"
27 #include <sys/wait.h>
28 #include <pwd.h>
29 #include <grp.h>
30 #include <libgen.h>
31 
32 /* Needed early for CONFIG_BSD etc. */
33 #include "net/slirp.h"
34 #include "qemu/error-report.h"
35 #include "qemu/log.h"
36 #include "sysemu/runstate.h"
37 #include "qemu/cutils.h"
38 
39 #ifdef CONFIG_LINUX
40 #include <sys/prctl.h>
41 #endif
42 
43 
44 void os_setup_early_signal_handling(void)
45 {
46     struct sigaction act;
47     sigfillset(&act.sa_mask);
48     act.sa_flags = 0;
49     act.sa_handler = SIG_IGN;
50     sigaction(SIGPIPE, &act, NULL);
51 }
52 
53 static void termsig_handler(int signal, siginfo_t *info, void *c)
54 {
55     qemu_system_killed(info->si_signo, info->si_pid);
56 }
57 
58 void os_setup_signal_handling(void)
59 {
60     struct sigaction act;
61 
62     memset(&act, 0, sizeof(act));
63     act.sa_sigaction = termsig_handler;
64     act.sa_flags = SA_SIGINFO;
65     sigaction(SIGINT,  &act, NULL);
66     sigaction(SIGHUP,  &act, NULL);
67     sigaction(SIGTERM, &act, NULL);
68 }
69 
70 void os_set_proc_name(const char *s)
71 {
72 #if defined(PR_SET_NAME)
73     char name[16];
74     if (!s)
75         return;
76     pstrcpy(name, sizeof(name), s);
77     /* Could rewrite argv[0] too, but that's a bit more complicated.
78        This simple way is enough for `top'. */
79     if (prctl(PR_SET_NAME, name)) {
80         error_report("unable to change process name: %s", strerror(errno));
81         exit(1);
82     }
83 #else
84     error_report("Change of process name not supported by your OS");
85     exit(1);
86 #endif
87 }
88 
89 
90 /*
91  * Must set all three of these at once.
92  * Legal combinations are              unset   by name   by uid
93  */
94 static struct passwd *user_pwd;    /*   NULL   non-NULL   NULL   */
95 static uid_t user_uid = (uid_t)-1; /*   -1      -1        >=0    */
96 static gid_t user_gid = (gid_t)-1; /*   -1      -1        >=0    */
97 
98 /*
99  * Prepare to change user ID. optarg can be one of 3 forms:
100  *   - a username, in which case user ID will be changed to its uid,
101  *     with primary and supplementary groups set up too;
102  *   - a numeric uid, in which case only the uid will be set;
103  *   - a pair of numeric uid:gid.
104  */
105 bool os_set_runas(const char *optarg)
106 {
107     unsigned long lv;
108     const char *ep;
109     uid_t got_uid;
110     gid_t got_gid;
111     int rc;
112 
113     user_pwd = getpwnam(optarg);
114     if (user_pwd) {
115         user_uid = -1;
116         user_gid = -1;
117         return true;
118     }
119 
120     rc = qemu_strtoul(optarg, &ep, 0, &lv);
121     got_uid = lv; /* overflow here is ID in C99 */
122     if (rc || *ep != ':' || got_uid != lv || got_uid == (uid_t)-1) {
123         return false;
124     }
125 
126     rc = qemu_strtoul(ep + 1, 0, 0, &lv);
127     got_gid = lv; /* overflow here is ID in C99 */
128     if (rc || got_gid != lv || got_gid == (gid_t)-1) {
129         return false;
130     }
131 
132     user_pwd = NULL;
133     user_uid = got_uid;
134     user_gid = got_gid;
135     return true;
136 }
137 
138 static void change_process_uid(void)
139 {
140     assert((user_uid == (uid_t)-1) || user_pwd == NULL);
141     assert((user_uid == (uid_t)-1) ==
142            (user_gid == (gid_t)-1));
143 
144     if (user_pwd || user_uid != (uid_t)-1) {
145         gid_t intended_gid = user_pwd ? user_pwd->pw_gid : user_gid;
146         uid_t intended_uid = user_pwd ? user_pwd->pw_uid : user_uid;
147         if (setgid(intended_gid) < 0) {
148             error_report("Failed to setgid(%d)", intended_gid);
149             exit(1);
150         }
151         if (user_pwd) {
152             if (initgroups(user_pwd->pw_name, user_pwd->pw_gid) < 0) {
153                 error_report("Failed to initgroups(\"%s\", %d)",
154                         user_pwd->pw_name, user_pwd->pw_gid);
155                 exit(1);
156             }
157         } else {
158             if (setgroups(1, &user_gid) < 0) {
159                 error_report("Failed to setgroups(1, [%d])",
160                         user_gid);
161                 exit(1);
162             }
163         }
164         if (setuid(intended_uid) < 0) {
165             error_report("Failed to setuid(%d)", intended_uid);
166             exit(1);
167         }
168         if (setuid(0) != -1) {
169             error_report("Dropping privileges failed");
170             exit(1);
171         }
172     }
173 }
174 
175 
176 static const char *chroot_dir;
177 
178 void os_set_chroot(const char *optarg)
179 {
180     chroot_dir = optarg;
181 }
182 
183 static void change_root(void)
184 {
185     if (chroot_dir) {
186         if (chroot(chroot_dir) < 0) {
187             error_report("chroot failed");
188             exit(1);
189         }
190         if (chdir("/")) {
191             error_report("not able to chdir to /: %s", strerror(errno));
192             exit(1);
193         }
194     }
195 
196 }
197 
198 
199 static int daemonize;
200 static int daemon_pipe;
201 
202 bool is_daemonized(void)
203 {
204     return daemonize;
205 }
206 
207 int os_set_daemonize(bool d)
208 {
209     daemonize = d;
210     return 0;
211 }
212 
213 void os_daemonize(void)
214 {
215     if (daemonize) {
216         pid_t pid;
217         int fds[2];
218 
219         if (!g_unix_open_pipe(fds, FD_CLOEXEC, NULL)) {
220             exit(1);
221         }
222 
223         pid = fork();
224         if (pid > 0) {
225             uint8_t status;
226             ssize_t len;
227 
228             close(fds[1]);
229 
230             do {
231                 len = read(fds[0], &status, 1);
232             } while (len < 0 && errno == EINTR);
233 
234             /* only exit successfully if our child actually wrote
235              * a one-byte zero to our pipe, upon successful init */
236             exit(len == 1 && status == 0 ? 0 : 1);
237 
238         } else if (pid < 0) {
239             exit(1);
240         }
241 
242         close(fds[0]);
243         daemon_pipe = fds[1];
244 
245         setsid();
246 
247         pid = fork();
248         if (pid > 0) {
249             exit(0);
250         } else if (pid < 0) {
251             exit(1);
252         }
253         umask(027);
254 
255         signal(SIGTSTP, SIG_IGN);
256         signal(SIGTTOU, SIG_IGN);
257         signal(SIGTTIN, SIG_IGN);
258     }
259 }
260 
261 void os_setup_post(void)
262 {
263     int fd = 0;
264 
265     if (daemonize) {
266         if (chdir("/")) {
267             error_report("not able to chdir to /: %s", strerror(errno));
268             exit(1);
269         }
270         fd = RETRY_ON_EINTR(qemu_open_old("/dev/null", O_RDWR));
271         if (fd == -1) {
272             exit(1);
273         }
274     }
275 
276     change_root();
277     change_process_uid();
278 
279     if (daemonize) {
280         uint8_t status = 0;
281         ssize_t len;
282 
283         dup2(fd, 0);
284         dup2(fd, 1);
285         /* In case -D is given do not redirect stderr to /dev/null */
286         if (!qemu_log_enabled()) {
287             dup2(fd, 2);
288         }
289 
290         close(fd);
291 
292         do {
293             len = write(daemon_pipe, &status, 1);
294         } while (len < 0 && errno == EINTR);
295         if (len != 1) {
296             exit(1);
297         }
298     }
299 }
300 
301 void os_set_line_buffering(void)
302 {
303     setvbuf(stdout, NULL, _IOLBF, 0);
304 }
305 
306 int os_mlock(void)
307 {
308 #ifdef HAVE_MLOCKALL
309     int ret = 0;
310 
311     ret = mlockall(MCL_CURRENT | MCL_FUTURE);
312     if (ret < 0) {
313         error_report("mlockall: %s", strerror(errno));
314     }
315 
316     return ret;
317 #else
318     return -ENOSYS;
319 #endif
320 }
321