]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/virt.c
resolve: use CMP() in dns_resource_record_compare_func
[thirdparty/systemd.git] / src / basic / virt.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #if defined(__i386__) || defined(__x86_64__)
4 #include <cpuid.h>
5 #endif
6 #include <errno.h>
7 #include <stdint.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <unistd.h>
11
12 #include "alloc-util.h"
13 #include "dirent-util.h"
14 #include "env-util.h"
15 #include "fd-util.h"
16 #include "fileio.h"
17 #include "macro.h"
18 #include "process-util.h"
19 #include "stat-util.h"
20 #include "string-table.h"
21 #include "string-util.h"
22 #include "virt.h"
23
24 static int detect_vm_cpuid(void) {
25
26 /* CPUID is an x86 specific interface. */
27 #if defined(__i386__) || defined(__x86_64__)
28
29 static const struct {
30 const char *cpuid;
31 int id;
32 } cpuid_vendor_table[] = {
33 { "XenVMMXenVMM", VIRTUALIZATION_XEN },
34 { "KVMKVMKVM", VIRTUALIZATION_KVM },
35 { "TCGTCGTCGTCG", VIRTUALIZATION_QEMU },
36 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
37 { "VMwareVMware", VIRTUALIZATION_VMWARE },
38 /* https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/reference/tlfs */
39 { "Microsoft Hv", VIRTUALIZATION_MICROSOFT },
40 /* https://wiki.freebsd.org/bhyve */
41 { "bhyve bhyve ", VIRTUALIZATION_BHYVE },
42 { "QNXQVMBSQG", VIRTUALIZATION_QNX },
43 };
44
45 uint32_t eax, ebx, ecx, edx;
46 bool hypervisor;
47
48 /* http://lwn.net/Articles/301888/ */
49
50 /* First detect whether there is a hypervisor */
51 if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) == 0)
52 return VIRTUALIZATION_NONE;
53
54 hypervisor = ecx & 0x80000000U;
55
56 if (hypervisor) {
57 union {
58 uint32_t sig32[3];
59 char text[13];
60 } sig = {};
61 unsigned j;
62
63 /* There is a hypervisor, see what it is */
64 __cpuid(0x40000000U, eax, ebx, ecx, edx);
65
66 sig.sig32[0] = ebx;
67 sig.sig32[1] = ecx;
68 sig.sig32[2] = edx;
69
70 log_debug("Virtualization found, CPUID=%s", sig.text);
71
72 for (j = 0; j < ELEMENTSOF(cpuid_vendor_table); j ++)
73 if (streq(sig.text, cpuid_vendor_table[j].cpuid))
74 return cpuid_vendor_table[j].id;
75
76 return VIRTUALIZATION_VM_OTHER;
77 }
78 #endif
79 log_debug("No virtualization found in CPUID");
80
81 return VIRTUALIZATION_NONE;
82 }
83
84 static int detect_vm_device_tree(void) {
85 #if defined(__arm__) || defined(__aarch64__) || defined(__powerpc__) || defined(__powerpc64__)
86 _cleanup_free_ char *hvtype = NULL;
87 int r;
88
89 r = read_one_line_file("/proc/device-tree/hypervisor/compatible", &hvtype);
90 if (r == -ENOENT) {
91 _cleanup_closedir_ DIR *dir = NULL;
92 struct dirent *dent;
93
94 dir = opendir("/proc/device-tree");
95 if (!dir) {
96 if (errno == ENOENT) {
97 log_debug_errno(errno, "/proc/device-tree: %m");
98 return VIRTUALIZATION_NONE;
99 }
100 return -errno;
101 }
102
103 FOREACH_DIRENT(dent, dir, return -errno)
104 if (strstr(dent->d_name, "fw-cfg")) {
105 log_debug("Virtualization QEMU: \"fw-cfg\" present in /proc/device-tree/%s", dent->d_name);
106 return VIRTUALIZATION_QEMU;
107 }
108
109 log_debug("No virtualization found in /proc/device-tree/*");
110 return VIRTUALIZATION_NONE;
111 } else if (r < 0)
112 return r;
113
114 log_debug("Virtualization %s found in /proc/device-tree/hypervisor/compatible", hvtype);
115 if (streq(hvtype, "linux,kvm"))
116 return VIRTUALIZATION_KVM;
117 else if (strstr(hvtype, "xen"))
118 return VIRTUALIZATION_XEN;
119 else
120 return VIRTUALIZATION_VM_OTHER;
121 #else
122 log_debug("This platform does not support /proc/device-tree");
123 return VIRTUALIZATION_NONE;
124 #endif
125 }
126
127 static int detect_vm_dmi(void) {
128 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
129
130 static const char *const dmi_vendors[] = {
131 "/sys/class/dmi/id/product_name", /* Test this before sys_vendor to detect KVM over QEMU */
132 "/sys/class/dmi/id/sys_vendor",
133 "/sys/class/dmi/id/board_vendor",
134 "/sys/class/dmi/id/bios_vendor"
135 };
136
137 static const struct {
138 const char *vendor;
139 int id;
140 } dmi_vendor_table[] = {
141 { "KVM", VIRTUALIZATION_KVM },
142 { "QEMU", VIRTUALIZATION_QEMU },
143 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
144 { "VMware", VIRTUALIZATION_VMWARE },
145 { "VMW", VIRTUALIZATION_VMWARE },
146 { "innotek GmbH", VIRTUALIZATION_ORACLE },
147 { "Xen", VIRTUALIZATION_XEN },
148 { "Bochs", VIRTUALIZATION_BOCHS },
149 { "Parallels", VIRTUALIZATION_PARALLELS },
150 /* https://wiki.freebsd.org/bhyve */
151 { "BHYVE", VIRTUALIZATION_BHYVE },
152 };
153 unsigned i;
154 int r;
155
156 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
157 _cleanup_free_ char *s = NULL;
158 unsigned j;
159
160 r = read_one_line_file(dmi_vendors[i], &s);
161 if (r < 0) {
162 if (r == -ENOENT)
163 continue;
164
165 return r;
166 }
167
168 for (j = 0; j < ELEMENTSOF(dmi_vendor_table); j++)
169 if (startswith(s, dmi_vendor_table[j].vendor)) {
170 log_debug("Virtualization %s found in DMI (%s)", s, dmi_vendors[i]);
171 return dmi_vendor_table[j].id;
172 }
173 }
174 #endif
175
176 log_debug("No virtualization found in DMI");
177
178 return VIRTUALIZATION_NONE;
179 }
180
181 static int detect_vm_xen(void) {
182
183 /* Check for Dom0 will be executed later in detect_vm_xen_dom0
184 The presence of /proc/xen indicates some form of a Xen domain */
185 if (access("/proc/xen", F_OK) < 0) {
186 log_debug("Virtualization XEN not found, /proc/xen does not exist");
187 return VIRTUALIZATION_NONE;
188 }
189
190 log_debug("Virtualization XEN found (/proc/xen exists)");
191 return VIRTUALIZATION_XEN;
192 }
193
194 #define XENFEAT_dom0 11 /* xen/include/public/features.h */
195 #define PATH_FEATURES "/sys/hypervisor/properties/features"
196 /* Returns -errno, or 0 for domU, or 1 for dom0 */
197 static int detect_vm_xen_dom0(void) {
198 _cleanup_free_ char *domcap = NULL;
199 char *cap, *i;
200 int r;
201
202 r = read_one_line_file(PATH_FEATURES, &domcap);
203 if (r < 0 && r != -ENOENT)
204 return r;
205 if (r == 0) {
206 unsigned long features;
207
208 /* Here, we need to use sscanf() instead of safe_atoul()
209 * as the string lacks the leading "0x". */
210 r = sscanf(domcap, "%lx", &features);
211 if (r == 1) {
212 r = !!(features & (1U << XENFEAT_dom0));
213 log_debug("Virtualization XEN, found %s with value %08lx, "
214 "XENFEAT_dom0 (indicating the 'hardware domain') is%s set.",
215 PATH_FEATURES, features, r ? "" : " not");
216 return r;
217 }
218 log_debug("Virtualization XEN, found %s, unhandled content '%s'",
219 PATH_FEATURES, domcap);
220 }
221
222 r = read_one_line_file("/proc/xen/capabilities", &domcap);
223 if (r == -ENOENT) {
224 log_debug("Virtualization XEN because /proc/xen/capabilities does not exist");
225 return 0;
226 }
227 if (r < 0)
228 return r;
229
230 i = domcap;
231 while ((cap = strsep(&i, ",")))
232 if (streq(cap, "control_d"))
233 break;
234 if (!cap) {
235 log_debug("Virtualization XEN DomU found (/proc/xen/capabilites)");
236 return 0;
237 }
238
239 log_debug("Virtualization XEN Dom0 ignored (/proc/xen/capabilities)");
240 return 1;
241 }
242
243 static int detect_vm_hypervisor(void) {
244 _cleanup_free_ char *hvtype = NULL;
245 int r;
246
247 r = read_one_line_file("/sys/hypervisor/type", &hvtype);
248 if (r == -ENOENT)
249 return VIRTUALIZATION_NONE;
250 if (r < 0)
251 return r;
252
253 log_debug("Virtualization %s found in /sys/hypervisor/type", hvtype);
254
255 if (streq(hvtype, "xen"))
256 return VIRTUALIZATION_XEN;
257 else
258 return VIRTUALIZATION_VM_OTHER;
259 }
260
261 static int detect_vm_uml(void) {
262 _cleanup_free_ char *cpuinfo_contents = NULL;
263 int r;
264
265 /* Detect User-Mode Linux by reading /proc/cpuinfo */
266 r = read_full_file("/proc/cpuinfo", &cpuinfo_contents, NULL);
267 if (r == -ENOENT) {
268 log_debug("/proc/cpuinfo not found, assuming no UML virtualization.");
269 return VIRTUALIZATION_NONE;
270 }
271 if (r < 0)
272 return r;
273
274 if (strstr(cpuinfo_contents, "\nvendor_id\t: User Mode Linux\n")) {
275 log_debug("UML virtualization found in /proc/cpuinfo");
276 return VIRTUALIZATION_UML;
277 }
278
279 log_debug("UML virtualization not found in /proc/cpuinfo.");
280 return VIRTUALIZATION_NONE;
281 }
282
283 static int detect_vm_zvm(void) {
284
285 #if defined(__s390__)
286 _cleanup_free_ char *t = NULL;
287 int r;
288
289 r = get_proc_field("/proc/sysinfo", "VM00 Control Program", WHITESPACE, &t);
290 if (r == -ENOENT)
291 return VIRTUALIZATION_NONE;
292 if (r < 0)
293 return r;
294
295 log_debug("Virtualization %s found in /proc/sysinfo", t);
296 if (streq(t, "z/VM"))
297 return VIRTUALIZATION_ZVM;
298 else
299 return VIRTUALIZATION_KVM;
300 #else
301 log_debug("This platform does not support /proc/sysinfo");
302 return VIRTUALIZATION_NONE;
303 #endif
304 }
305
306 /* Returns a short identifier for the various VM implementations */
307 int detect_vm(void) {
308 static thread_local int cached_found = _VIRTUALIZATION_INVALID;
309 bool other = false;
310 int r, dmi;
311
312 if (cached_found >= 0)
313 return cached_found;
314
315 /* We have to use the correct order here:
316 *
317 * → First, try to detect Oracle Virtualbox, even if it uses KVM, as well as Xen even if it cloaks as Microsoft
318 * Hyper-V.
319 *
320 * → Second, try to detect from CPUID, this will report KVM for whatever software is used even if info in DMI is
321 * overwritten.
322 *
323 * → Third, try to detect from DMI. */
324
325 dmi = detect_vm_dmi();
326 if (IN_SET(dmi, VIRTUALIZATION_ORACLE, VIRTUALIZATION_XEN)) {
327 r = dmi;
328 goto finish;
329 }
330
331 r = detect_vm_cpuid();
332 if (r < 0)
333 return r;
334 if (r == VIRTUALIZATION_VM_OTHER)
335 other = true;
336 else if (r != VIRTUALIZATION_NONE)
337 goto finish;
338
339 /* Now, let's get back to DMI */
340 if (dmi < 0)
341 return dmi;
342 if (dmi == VIRTUALIZATION_VM_OTHER)
343 other = true;
344 else if (dmi != VIRTUALIZATION_NONE) {
345 r = dmi;
346 goto finish;
347 }
348
349 /* x86 xen will most likely be detected by cpuid. If not (most likely
350 * because we're not an x86 guest), then we should try the /proc/xen
351 * directory next. If that's not found, then we check for the high-level
352 * hypervisor sysfs file.
353 */
354
355 r = detect_vm_xen();
356 if (r < 0)
357 return r;
358 if (r == VIRTUALIZATION_VM_OTHER)
359 other = true;
360 else if (r != VIRTUALIZATION_NONE)
361 goto finish;
362
363 r = detect_vm_hypervisor();
364 if (r < 0)
365 return r;
366 if (r == VIRTUALIZATION_VM_OTHER)
367 other = true;
368 else if (r != VIRTUALIZATION_NONE)
369 goto finish;
370
371 r = detect_vm_device_tree();
372 if (r < 0)
373 return r;
374 if (r == VIRTUALIZATION_VM_OTHER)
375 other = true;
376 else if (r != VIRTUALIZATION_NONE)
377 goto finish;
378
379 r = detect_vm_uml();
380 if (r < 0)
381 return r;
382 if (r == VIRTUALIZATION_VM_OTHER)
383 other = true;
384 else if (r != VIRTUALIZATION_NONE)
385 goto finish;
386
387 r = detect_vm_zvm();
388 if (r < 0)
389 return r;
390
391 finish:
392 /* x86 xen Dom0 is detected as XEN in hypervisor and maybe others.
393 * In order to detect the Dom0 as not virtualization we need to
394 * double-check it */
395 if (r == VIRTUALIZATION_XEN) {
396 int dom0;
397
398 dom0 = detect_vm_xen_dom0();
399 if (dom0 < 0)
400 return dom0;
401 if (dom0 > 0)
402 r = VIRTUALIZATION_NONE;
403 } else if (r == VIRTUALIZATION_NONE && other)
404 r = VIRTUALIZATION_VM_OTHER;
405
406 cached_found = r;
407 log_debug("Found VM virtualization %s", virtualization_to_string(r));
408 return r;
409 }
410
411 int detect_container(void) {
412
413 static const struct {
414 const char *value;
415 int id;
416 } value_table[] = {
417 { "lxc", VIRTUALIZATION_LXC },
418 { "lxc-libvirt", VIRTUALIZATION_LXC_LIBVIRT },
419 { "systemd-nspawn", VIRTUALIZATION_SYSTEMD_NSPAWN },
420 { "docker", VIRTUALIZATION_DOCKER },
421 { "rkt", VIRTUALIZATION_RKT },
422 };
423
424 static thread_local int cached_found = _VIRTUALIZATION_INVALID;
425 _cleanup_free_ char *m = NULL;
426 const char *e = NULL;
427 unsigned j;
428 int r;
429
430 if (cached_found >= 0)
431 return cached_found;
432
433 /* /proc/vz exists in container and outside of the container, /proc/bc only outside of the container. */
434 if (access("/proc/vz", F_OK) >= 0 &&
435 access("/proc/bc", F_OK) < 0) {
436 r = VIRTUALIZATION_OPENVZ;
437 goto finish;
438 }
439
440 if (getpid_cached() == 1) {
441 /* If we are PID 1 we can just check our own environment variable, and that's authoritative. */
442
443 e = getenv("container");
444 if (isempty(e)) {
445 r = VIRTUALIZATION_NONE;
446 goto finish;
447 }
448
449 goto translate_name;
450 }
451
452 /* Otherwise, PID 1 might have dropped this information into a file in /run. This is better than accessing
453 * /proc/1/environ, since we don't need CAP_SYS_PTRACE for that. */
454 r = read_one_line_file("/run/systemd/container", &m);
455 if (r >= 0) {
456 e = m;
457 goto translate_name;
458 }
459 if (r != -ENOENT)
460 return log_debug_errno(r, "Failed to read /run/systemd/container: %m");
461
462 /* Fallback for cases where PID 1 was not systemd (for example, cases where init=/bin/sh is used. */
463 r = getenv_for_pid(1, "container", &m);
464 if (r > 0) {
465 e = m;
466 goto translate_name;
467 }
468 if (r < 0) /* This only works if we have CAP_SYS_PTRACE, hence let's better ignore failures here */
469 log_debug_errno(r, "Failed to read $container of PID 1, ignoring: %m");
470
471 /* Interestingly /proc/1/sched actually shows the host's PID for what we see as PID 1. Hence, if the PID shown
472 * there is not 1, we know we are in a PID namespace. and hence a container. */
473 r = read_one_line_file("/proc/1/sched", &m);
474 if (r >= 0) {
475 const char *t;
476
477 t = strrchr(m, '(');
478 if (!t)
479 return -EIO;
480
481 if (!startswith(t, "(1,")) {
482 r = VIRTUALIZATION_CONTAINER_OTHER;
483 goto finish;
484 }
485 } else if (r != -ENOENT)
486 return r;
487
488 /* If that didn't work, give up, assume no container manager. */
489 r = VIRTUALIZATION_NONE;
490 goto finish;
491
492 translate_name:
493 for (j = 0; j < ELEMENTSOF(value_table); j++)
494 if (streq(e, value_table[j].value)) {
495 r = value_table[j].id;
496 goto finish;
497 }
498
499 r = VIRTUALIZATION_CONTAINER_OTHER;
500
501 finish:
502 log_debug("Found container virtualization %s.", virtualization_to_string(r));
503 cached_found = r;
504 return r;
505 }
506
507 int detect_virtualization(void) {
508 int r;
509
510 r = detect_container();
511 if (r == 0)
512 r = detect_vm();
513
514 return r;
515 }
516
517 static int userns_has_mapping(const char *name) {
518 _cleanup_fclose_ FILE *f = NULL;
519 _cleanup_free_ char *buf = NULL;
520 size_t n_allocated = 0;
521 ssize_t n;
522 uint32_t a, b, c;
523 int r;
524
525 f = fopen(name, "re");
526 if (!f) {
527 log_debug_errno(errno, "Failed to open %s: %m", name);
528 return errno == ENOENT ? false : -errno;
529 }
530
531 n = getline(&buf, &n_allocated, f);
532 if (n < 0) {
533 if (feof(f)) {
534 log_debug("%s is empty, we're in an uninitialized user namespace", name);
535 return true;
536 }
537
538 return log_debug_errno(errno, "Failed to read %s: %m", name);
539 }
540
541 r = sscanf(buf, "%"PRIu32" %"PRIu32" %"PRIu32, &a, &b, &c);
542 if (r < 3)
543 return log_debug_errno(errno, "Failed to parse %s: %m", name);
544
545 if (a == 0 && b == 0 && c == UINT32_MAX) {
546 /* The kernel calls mappings_overlap() and does not allow overlaps */
547 log_debug("%s has a full 1:1 mapping", name);
548 return false;
549 }
550
551 /* Anything else implies that we are in a user namespace */
552 log_debug("Mapping found in %s, we're in a user namespace", name);
553 return true;
554 }
555
556 int running_in_userns(void) {
557 _cleanup_free_ char *line = NULL;
558 int r;
559
560 r = userns_has_mapping("/proc/self/uid_map");
561 if (r != 0)
562 return r;
563
564 r = userns_has_mapping("/proc/self/gid_map");
565 if (r != 0)
566 return r;
567
568 /* "setgroups" file was added in kernel v3.18-rc6-15-g9cc46516dd. It is also
569 * possible to compile a kernel without CONFIG_USER_NS, in which case "setgroups"
570 * also does not exist. We cannot distinguish those two cases, so assume that
571 * we're running on a stripped-down recent kernel, rather than on an old one,
572 * and if the file is not found, return false.
573 */
574 r = read_one_line_file("/proc/self/setgroups", &line);
575 if (r < 0) {
576 log_debug_errno(r, "/proc/self/setgroups: %m");
577 return r == -ENOENT ? false : r;
578 }
579
580 truncate_nl(line);
581 r = streq(line, "deny");
582 /* See user_namespaces(7) for a description of this "setgroups" contents. */
583 log_debug("/proc/self/setgroups contains \"%s\", %s user namespace", line, r ? "in" : "not in");
584 return r;
585 }
586
587 int running_in_chroot(void) {
588 int r;
589
590 if (getenv_bool("SYSTEMD_IGNORE_CHROOT") > 0)
591 return 0;
592
593 r = files_same("/proc/1/root", "/", 0);
594 if (r < 0)
595 return r;
596
597 return r == 0;
598 }
599
600 static const char *const virtualization_table[_VIRTUALIZATION_MAX] = {
601 [VIRTUALIZATION_NONE] = "none",
602 [VIRTUALIZATION_KVM] = "kvm",
603 [VIRTUALIZATION_QEMU] = "qemu",
604 [VIRTUALIZATION_BOCHS] = "bochs",
605 [VIRTUALIZATION_XEN] = "xen",
606 [VIRTUALIZATION_UML] = "uml",
607 [VIRTUALIZATION_VMWARE] = "vmware",
608 [VIRTUALIZATION_ORACLE] = "oracle",
609 [VIRTUALIZATION_MICROSOFT] = "microsoft",
610 [VIRTUALIZATION_ZVM] = "zvm",
611 [VIRTUALIZATION_PARALLELS] = "parallels",
612 [VIRTUALIZATION_BHYVE] = "bhyve",
613 [VIRTUALIZATION_QNX] = "qnx",
614 [VIRTUALIZATION_VM_OTHER] = "vm-other",
615
616 [VIRTUALIZATION_SYSTEMD_NSPAWN] = "systemd-nspawn",
617 [VIRTUALIZATION_LXC_LIBVIRT] = "lxc-libvirt",
618 [VIRTUALIZATION_LXC] = "lxc",
619 [VIRTUALIZATION_OPENVZ] = "openvz",
620 [VIRTUALIZATION_DOCKER] = "docker",
621 [VIRTUALIZATION_RKT] = "rkt",
622 [VIRTUALIZATION_CONTAINER_OTHER] = "container-other",
623 };
624
625 DEFINE_STRING_TABLE_LOOKUP(virtualization, int);