1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010 Lennart Poettering
13 #include "string-table.h"
17 static bool arg_quiet
= false;
24 } arg_mode
= ANY_VIRTUALIZATION
;
26 static void help(void) {
27 printf("%s [OPTIONS...]\n\n"
28 "Detect execution in a virtualized environment.\n\n"
29 " -h --help Show this help\n"
30 " --version Show package version\n"
31 " -c --container Only detect whether we are run in a container\n"
32 " -v --vm Only detect whether we are run in a VM\n"
33 " -r --chroot Detect whether we are run in a chroot() environment\n"
34 " --private-users Only detect whether we are running in a user namespace\n"
35 " -q --quiet Don't output anything, just set return value\n"
36 " --list List all known and detectable types of virtualization\n"
37 , program_invocation_short_name
);
40 static int parse_argv(int argc
, char *argv
[]) {
48 static const struct option options
[] = {
49 { "help", no_argument
, NULL
, 'h' },
50 { "version", no_argument
, NULL
, ARG_VERSION
},
51 { "container", no_argument
, NULL
, 'c' },
52 { "vm", no_argument
, NULL
, 'v' },
53 { "chroot", no_argument
, NULL
, 'r' },
54 { "private-users", no_argument
, NULL
, ARG_PRIVATE_USERS
},
55 { "quiet", no_argument
, NULL
, 'q' },
56 { "list", no_argument
, NULL
, ARG_LIST
},
65 while ((c
= getopt_long(argc
, argv
, "hqcvr", options
, NULL
)) >= 0)
81 arg_mode
= ONLY_CONTAINER
;
84 case ARG_PRIVATE_USERS
:
85 arg_mode
= ONLY_PRIVATE_USERS
;
93 arg_mode
= ONLY_CHROOT
;
97 DUMP_STRING_TABLE(virtualization
, int, _VIRTUALIZATION_MAX
);
104 assert_not_reached("Unhandled option");
108 log_error("%s takes no arguments.", program_invocation_short_name
);
115 int main(int argc
, char *argv
[]) {
118 /* This is mostly intended to be used for scripts which want
119 * to detect whether we are being run in a virtualized
120 * environment or not */
122 log_parse_environment();
125 r
= parse_argv(argc
, argv
);
127 return r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;
134 log_error_errno(r
, "Failed to check for VM: %m");
141 r
= detect_container();
143 log_error_errno(r
, "Failed to check for container: %m");
150 r
= running_in_chroot();
152 log_error_errno(r
, "Failed to check for chroot() environment: %m");
156 return r
? EXIT_SUCCESS
: EXIT_FAILURE
;
158 case ONLY_PRIVATE_USERS
:
159 r
= running_in_userns();
161 log_error_errno(r
, "Failed to check for user namespace: %m");
165 return r
? EXIT_SUCCESS
: EXIT_FAILURE
;
167 case ANY_VIRTUALIZATION
:
169 r
= detect_virtualization();
171 log_error_errno(r
, "Failed to check for virtualization: %m");
179 puts(virtualization_to_string(r
));
181 return r
!= VIRTUALIZATION_NONE
? EXIT_SUCCESS
: EXIT_FAILURE
;