1 /* SPDX-License-Identifier: LGPL-2.1+ */
8 #include "alloc-util.h"
9 #include "string-table.h"
10 #include "terminal-util.h"
14 static bool arg_quiet
= false;
21 } arg_mode
= ANY_VIRTUALIZATION
;
23 static int help(void) {
24 _cleanup_free_
char *link
= NULL
;
27 r
= terminal_urlify_man("systemd-detect-virt", "1", &link
);
31 printf("%s [OPTIONS...]\n\n"
32 "Detect execution in a virtualized environment.\n\n"
33 " -h --help Show this help\n"
34 " --version Show package version\n"
35 " -c --container Only detect whether we are run in a container\n"
36 " -v --vm Only detect whether we are run in a VM\n"
37 " -r --chroot Detect whether we are run in a chroot() environment\n"
38 " --private-users Only detect whether we are running in a user namespace\n"
39 " -q --quiet Don't output anything, just set return value\n"
40 " --list List all known and detectable types of virtualization\n"
41 "\nSee the %s for details.\n"
42 , program_invocation_short_name
49 static int parse_argv(int argc
, char *argv
[]) {
57 static const struct option options
[] = {
58 { "help", no_argument
, NULL
, 'h' },
59 { "version", no_argument
, NULL
, ARG_VERSION
},
60 { "container", no_argument
, NULL
, 'c' },
61 { "vm", no_argument
, NULL
, 'v' },
62 { "chroot", no_argument
, NULL
, 'r' },
63 { "private-users", no_argument
, NULL
, ARG_PRIVATE_USERS
},
64 { "quiet", no_argument
, NULL
, 'q' },
65 { "list", no_argument
, NULL
, ARG_LIST
},
74 while ((c
= getopt_long(argc
, argv
, "hqcvr", options
, NULL
)) >= 0)
89 arg_mode
= ONLY_CONTAINER
;
92 case ARG_PRIVATE_USERS
:
93 arg_mode
= ONLY_PRIVATE_USERS
;
101 arg_mode
= ONLY_CHROOT
;
105 DUMP_STRING_TABLE(virtualization
, int, _VIRTUALIZATION_MAX
);
112 assert_not_reached("Unhandled option");
116 log_error("%s takes no arguments.", program_invocation_short_name
);
123 int main(int argc
, char *argv
[]) {
126 /* This is mostly intended to be used for scripts which want
127 * to detect whether we are being run in a virtualized
128 * environment or not */
130 log_parse_environment();
133 r
= parse_argv(argc
, argv
);
135 return r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;
142 log_error_errno(r
, "Failed to check for VM: %m");
149 r
= detect_container();
151 log_error_errno(r
, "Failed to check for container: %m");
158 r
= running_in_chroot();
160 log_error_errno(r
, "Failed to check for chroot() environment: %m");
164 return r
? EXIT_SUCCESS
: EXIT_FAILURE
;
166 case ONLY_PRIVATE_USERS
:
167 r
= running_in_userns();
169 log_error_errno(r
, "Failed to check for user namespace: %m");
173 return r
? EXIT_SUCCESS
: EXIT_FAILURE
;
175 case ANY_VIRTUALIZATION
:
177 r
= detect_virtualization();
179 log_error_errno(r
, "Failed to check for virtualization: %m");
187 puts(virtualization_to_string(r
));
189 return r
!= VIRTUALIZATION_NONE
? EXIT_SUCCESS
: EXIT_FAILURE
;