1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2010 Lennart Poettering
11 #include "string-table.h"
15 static bool arg_quiet
= false;
22 } arg_mode
= ANY_VIRTUALIZATION
;
24 static void help(void) {
25 printf("%s [OPTIONS...]\n\n"
26 "Detect execution in a virtualized environment.\n\n"
27 " -h --help Show this help\n"
28 " --version Show package version\n"
29 " -c --container Only detect whether we are run in a container\n"
30 " -v --vm Only detect whether we are run in a VM\n"
31 " -r --chroot Detect whether we are run in a chroot() environment\n"
32 " --private-users Only detect whether we are running in a user namespace\n"
33 " -q --quiet Don't output anything, just set return value\n"
34 " --list List all known and detectable types of virtualization\n"
35 , program_invocation_short_name
);
38 static int parse_argv(int argc
, char *argv
[]) {
46 static const struct option options
[] = {
47 { "help", no_argument
, NULL
, 'h' },
48 { "version", no_argument
, NULL
, ARG_VERSION
},
49 { "container", no_argument
, NULL
, 'c' },
50 { "vm", no_argument
, NULL
, 'v' },
51 { "chroot", no_argument
, NULL
, 'r' },
52 { "private-users", no_argument
, NULL
, ARG_PRIVATE_USERS
},
53 { "quiet", no_argument
, NULL
, 'q' },
54 { "list", no_argument
, NULL
, ARG_LIST
},
63 while ((c
= getopt_long(argc
, argv
, "hqcvr", options
, NULL
)) >= 0)
79 arg_mode
= ONLY_CONTAINER
;
82 case ARG_PRIVATE_USERS
:
83 arg_mode
= ONLY_PRIVATE_USERS
;
91 arg_mode
= ONLY_CHROOT
;
95 DUMP_STRING_TABLE(virtualization
, int, _VIRTUALIZATION_MAX
);
102 assert_not_reached("Unhandled option");
106 log_error("%s takes no arguments.", program_invocation_short_name
);
113 int main(int argc
, char *argv
[]) {
116 /* This is mostly intended to be used for scripts which want
117 * to detect whether we are being run in a virtualized
118 * environment or not */
120 log_parse_environment();
123 r
= parse_argv(argc
, argv
);
125 return r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;
132 log_error_errno(r
, "Failed to check for VM: %m");
139 r
= detect_container();
141 log_error_errno(r
, "Failed to check for container: %m");
148 r
= running_in_chroot();
150 log_error_errno(r
, "Failed to check for chroot() environment: %m");
154 return r
? EXIT_SUCCESS
: EXIT_FAILURE
;
156 case ONLY_PRIVATE_USERS
:
157 r
= running_in_userns();
159 log_error_errno(r
, "Failed to check for user namespace: %m");
163 return r
? EXIT_SUCCESS
: EXIT_FAILURE
;
165 case ANY_VIRTUALIZATION
:
167 r
= detect_virtualization();
169 log_error_errno(r
, "Failed to check for virtualization: %m");
177 puts(virtualization_to_string(r
));
179 return r
!= VIRTUALIZATION_NONE
? EXIT_SUCCESS
: EXIT_FAILURE
;