xref: /qemu/os-posix.c (revision 2a96042a)
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 "sysemu/sysemu.h"
34 #include "net/slirp.h"
35 #include "qemu-options.h"
36 #include "qemu/error-report.h"
37 #include "qemu/log.h"
38 #include "qemu/cutils.h"
39 
40 #ifdef CONFIG_LINUX
41 #include <sys/prctl.h>
42 #endif
43 
44 /*
45  * Must set all three of these at once.
46  * Legal combinations are              unset   by name   by uid
47  */
48 static struct passwd *user_pwd;    /*   NULL   non-NULL   NULL   */
49 static uid_t user_uid = (uid_t)-1; /*   -1      -1        >=0    */
50 static gid_t user_gid = (gid_t)-1; /*   -1      -1        >=0    */
51 
52 static const char *chroot_dir;
53 static int daemonize;
54 static int daemon_pipe;
55 
56 void os_setup_early_signal_handling(void)
57 {
58     struct sigaction act;
59     sigfillset(&act.sa_mask);
60     act.sa_flags = 0;
61     act.sa_handler = SIG_IGN;
62     sigaction(SIGPIPE, &act, NULL);
63 }
64 
65 static void termsig_handler(int signal, siginfo_t *info, void *c)
66 {
67     qemu_system_killed(info->si_signo, info->si_pid);
68 }
69 
70 void os_setup_signal_handling(void)
71 {
72     struct sigaction act;
73 
74     memset(&act, 0, sizeof(act));
75     act.sa_sigaction = termsig_handler;
76     act.sa_flags = SA_SIGINFO;
77     sigaction(SIGINT,  &act, NULL);
78     sigaction(SIGHUP,  &act, NULL);
79     sigaction(SIGTERM, &act, NULL);
80 }
81 
82 /* Find a likely location for support files using the location of the binary.
83    For installed binaries this will be "$bindir/../share/qemu".  When
84    running from the build tree this will be "$bindir/../pc-bios".  */
85 #define SHARE_SUFFIX "/share/qemu"
86 #define BUILD_SUFFIX "/pc-bios"
87 char *os_find_datadir(void)
88 {
89     char *dir, *exec_dir;
90     char *res;
91     size_t max_len;
92 
93     exec_dir = qemu_get_exec_dir();
94     if (exec_dir == NULL) {
95         return NULL;
96     }
97     dir = g_path_get_dirname(exec_dir);
98 
99     max_len = strlen(dir) +
100         MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
101     res = g_malloc0(max_len);
102     snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
103     if (access(res, R_OK)) {
104         snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
105         if (access(res, R_OK)) {
106             g_free(res);
107             res = NULL;
108         }
109     }
110 
111     g_free(dir);
112     g_free(exec_dir);
113     return res;
114 }
115 #undef SHARE_SUFFIX
116 #undef BUILD_SUFFIX
117 
118 void os_set_proc_name(const char *s)
119 {
120 #if defined(PR_SET_NAME)
121     char name[16];
122     if (!s)
123         return;
124     pstrcpy(name, sizeof(name), s);
125     /* Could rewrite argv[0] too, but that's a bit more complicated.
126        This simple way is enough for `top'. */
127     if (prctl(PR_SET_NAME, name)) {
128         error_report("unable to change process name: %s", strerror(errno));
129         exit(1);
130     }
131 #else
132     error_report("Change of process name not supported by your OS");
133     exit(1);
134 #endif
135 }
136 
137 
138 static bool os_parse_runas_uid_gid(const char *optarg)
139 {
140     unsigned long lv;
141     const char *ep;
142     uid_t got_uid;
143     gid_t got_gid;
144     int rc;
145 
146     rc = qemu_strtoul(optarg, &ep, 0, &lv);
147     got_uid = lv; /* overflow here is ID in C99 */
148     if (rc || *ep != ':' || got_uid != lv || got_uid == (uid_t)-1) {
149         return false;
150     }
151 
152     rc = qemu_strtoul(ep + 1, 0, 0, &lv);
153     got_gid = lv; /* overflow here is ID in C99 */
154     if (rc || got_gid != lv || got_gid == (gid_t)-1) {
155         return false;
156     }
157 
158     user_pwd = NULL;
159     user_uid = got_uid;
160     user_gid = got_gid;
161     return true;
162 }
163 
164 /*
165  * Parse OS specific command line options.
166  * return 0 if option handled, -1 otherwise
167  */
168 int os_parse_cmd_args(int index, const char *optarg)
169 {
170     switch (index) {
171     case QEMU_OPTION_runas:
172         user_pwd = getpwnam(optarg);
173         if (user_pwd) {
174             user_uid = -1;
175             user_gid = -1;
176         } else if (!os_parse_runas_uid_gid(optarg)) {
177             error_report("User \"%s\" doesn't exist"
178                          " (and is not <uid>:<gid>)",
179                          optarg);
180             exit(1);
181         }
182         break;
183     case QEMU_OPTION_chroot:
184         chroot_dir = optarg;
185         break;
186     case QEMU_OPTION_daemonize:
187         daemonize = 1;
188         break;
189 #if defined(CONFIG_LINUX)
190     case QEMU_OPTION_enablefips:
191         fips_set_state(true);
192         break;
193 #endif
194     default:
195         return -1;
196     }
197 
198     return 0;
199 }
200 
201 static void change_process_uid(void)
202 {
203     assert((user_uid == (uid_t)-1) || user_pwd == NULL);
204     assert((user_uid == (uid_t)-1) ==
205            (user_gid == (gid_t)-1));
206 
207     if (user_pwd || user_uid != (uid_t)-1) {
208         gid_t intended_gid = user_pwd ? user_pwd->pw_gid : user_gid;
209         uid_t intended_uid = user_pwd ? user_pwd->pw_uid : user_uid;
210         if (setgid(intended_gid) < 0) {
211             error_report("Failed to setgid(%d)", intended_gid);
212             exit(1);
213         }
214         if (user_pwd) {
215             if (initgroups(user_pwd->pw_name, user_pwd->pw_gid) < 0) {
216                 error_report("Failed to initgroups(\"%s\", %d)",
217                         user_pwd->pw_name, user_pwd->pw_gid);
218                 exit(1);
219             }
220         } else {
221             if (setgroups(1, &user_gid) < 0) {
222                 error_report("Failed to setgroups(1, [%d])",
223                         user_gid);
224                 exit(1);
225             }
226         }
227         if (setuid(intended_uid) < 0) {
228             error_report("Failed to setuid(%d)", intended_uid);
229             exit(1);
230         }
231         if (setuid(0) != -1) {
232             error_report("Dropping privileges failed");
233             exit(1);
234         }
235     }
236 }
237 
238 static void change_root(void)
239 {
240     if (chroot_dir) {
241         if (chroot(chroot_dir) < 0) {
242             error_report("chroot failed");
243             exit(1);
244         }
245         if (chdir("/")) {
246             error_report("not able to chdir to /: %s", strerror(errno));
247             exit(1);
248         }
249     }
250 
251 }
252 
253 void os_daemonize(void)
254 {
255     if (daemonize) {
256         pid_t pid;
257         int fds[2];
258 
259         if (pipe(fds) == -1) {
260             exit(1);
261         }
262 
263         pid = fork();
264         if (pid > 0) {
265             uint8_t status;
266             ssize_t len;
267 
268             close(fds[1]);
269 
270             do {
271                 len = read(fds[0], &status, 1);
272             } while (len < 0 && errno == EINTR);
273 
274             /* only exit successfully if our child actually wrote
275              * a one-byte zero to our pipe, upon successful init */
276             exit(len == 1 && status == 0 ? 0 : 1);
277 
278         } else if (pid < 0) {
279             exit(1);
280         }
281 
282         close(fds[0]);
283         daemon_pipe = fds[1];
284         qemu_set_cloexec(daemon_pipe);
285 
286         setsid();
287 
288         pid = fork();
289         if (pid > 0) {
290             exit(0);
291         } else if (pid < 0) {
292             exit(1);
293         }
294         umask(027);
295 
296         signal(SIGTSTP, SIG_IGN);
297         signal(SIGTTOU, SIG_IGN);
298         signal(SIGTTIN, SIG_IGN);
299     }
300 }
301 
302 void os_setup_post(void)
303 {
304     int fd = 0;
305 
306     if (daemonize) {
307         if (chdir("/")) {
308             error_report("not able to chdir to /: %s", strerror(errno));
309             exit(1);
310         }
311         TFR(fd = qemu_open("/dev/null", O_RDWR));
312         if (fd == -1) {
313             exit(1);
314         }
315     }
316 
317     change_root();
318     change_process_uid();
319 
320     if (daemonize) {
321         uint8_t status = 0;
322         ssize_t len;
323 
324         dup2(fd, 0);
325         dup2(fd, 1);
326         /* In case -D is given do not redirect stderr to /dev/null */
327         if (!qemu_logfile) {
328             dup2(fd, 2);
329         }
330 
331         close(fd);
332 
333         do {
334             len = write(daemon_pipe, &status, 1);
335         } while (len < 0 && errno == EINTR);
336         if (len != 1) {
337             exit(1);
338         }
339     }
340 }
341 
342 void os_set_line_buffering(void)
343 {
344     setvbuf(stdout, NULL, _IOLBF, 0);
345 }
346 
347 int qemu_create_pidfile(const char *filename)
348 {
349     char buffer[128];
350     int len;
351     int fd;
352 
353     fd = qemu_open(filename, O_RDWR | O_CREAT, 0600);
354     if (fd == -1) {
355         return -1;
356     }
357     if (lockf(fd, F_TLOCK, 0) == -1) {
358         close(fd);
359         return -1;
360     }
361     len = snprintf(buffer, sizeof(buffer), FMT_pid "\n", getpid());
362     if (write(fd, buffer, len) != len) {
363         close(fd);
364         return -1;
365     }
366 
367     /* keep pidfile open & locked forever */
368     return 0;
369 }
370 
371 bool is_daemonized(void)
372 {
373     return daemonize;
374 }
375 
376 int os_mlock(void)
377 {
378     int ret = 0;
379 
380     ret = mlockall(MCL_CURRENT | MCL_FUTURE);
381     if (ret < 0) {
382         error_report("mlockall: %s", strerror(errno));
383     }
384 
385     return ret;
386 }
387