chiark / gitweb /
bus: reuse more code
[elogind.git] / src / shared / virt.c
index 6e447944967a115a2e7b0b596254a2d5d9bebc2f..78016eec8927d3e3245141e9f11144dfd8566401 100644 (file)
@@ -25,6 +25,7 @@
 
 #include "util.h"
 #include "virt.h"
+#include "fileio.h"
 
 /* Returns a short identifier for the various VM implementations */
 int detect_vm(const char **id) {
@@ -65,6 +66,22 @@ int detect_vm(const char **id) {
         unsigned i;
         const char *j, *k;
         bool hypervisor;
+        _cleanup_free_ char *hvtype = NULL;
+        int r;
+
+        /* Try high-level hypervisor sysfs file first:
+         *
+         * https://bugs.freedesktop.org/show_bug.cgi?id=61491 */
+        r = read_one_line_file("/sys/hypervisor/type", &hvtype);
+        if (r >= 0) {
+                if (streq(hvtype, "xen")) {
+                        if (id)
+                                *id = "xen";
+
+                        return 1;
+                }
+        } else if (r != -ENOENT)
+                return r;
 
         /* http://lwn.net/Articles/301888/ */
         zero(sig);
@@ -117,11 +134,11 @@ int detect_vm(const char **id) {
         }
 
         for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
-                char *s;
-                int r;
+                _cleanup_free_ char *s = NULL;
                 const char *found = NULL;
 
-                if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
+                r = read_one_line_file(dmi_vendors[i], &s);
+                if (r < 0) {
                         if (r != -ENOENT)
                                 return r;
 
@@ -131,7 +148,6 @@ int detect_vm(const char **id) {
                 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
                         if (startswith(s, j))
                                 found = k;
-                free(s);
 
                 if (found) {
                         if (id)
@@ -141,7 +157,7 @@ int detect_vm(const char **id) {
                 }
         }
 
-        if (hypervisor) {
+        if (hypervisor || hvtype) {
                 if (id)
                         *id = "other";
 
@@ -159,10 +175,10 @@ int detect_container(const char **id) {
         /* Unfortunately many of these operations require root access
          * in one way or another */
 
-        if (geteuid() != 0)
-                return -EPERM;
-
-        if (running_in_chroot() > 0) {
+        r = running_in_chroot();
+        if (r < 0)
+                return r;
+        if (r > 0) {
 
                 if (id)
                         *id = "chroot";