1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010 Lennart Poettering
16 static bool arg_quiet
= false;
23 } arg_mode
= ANY_VIRTUALIZATION
;
25 static void help(void) {
26 printf("%s [OPTIONS...]\n\n"
27 "Detect execution in a virtualized environment.\n\n"
28 " -h --help Show this help\n"
29 " --version Show package version\n"
30 " -c --container Only detect whether we are run in a container\n"
31 " -v --vm Only detect whether we are run in a VM\n"
32 " -r --chroot Detect whether we are run in a chroot() environment\n"
33 " --private-users Only detect whether we are running in a user namespace\n"
34 " -q --quiet Don't output anything, just set return value\n"
35 , program_invocation_short_name
);
38 static int parse_argv(int argc
, char *argv
[]) {
45 static const struct option options
[] = {
46 { "help", no_argument
, NULL
, 'h' },
47 { "version", no_argument
, NULL
, ARG_VERSION
},
48 { "container", no_argument
, NULL
, 'c' },
49 { "vm", no_argument
, NULL
, 'v' },
50 { "chroot", no_argument
, NULL
, 'r' },
51 { "private-users", no_argument
, NULL
, ARG_PRIVATE_USERS
},
52 { "quiet", no_argument
, NULL
, 'q' },
61 while ((c
= getopt_long(argc
, argv
, "hqcvr", options
, NULL
)) >= 0)
77 arg_mode
= ONLY_CONTAINER
;
80 case ARG_PRIVATE_USERS
:
81 arg_mode
= ONLY_PRIVATE_USERS
;
89 arg_mode
= ONLY_CHROOT
;
96 assert_not_reached("Unhandled option");
100 log_error("%s takes no arguments.", program_invocation_short_name
);
107 int main(int argc
, char *argv
[]) {
110 /* This is mostly intended to be used for scripts which want
111 * to detect whether we are being run in a virtualized
112 * environment or not */
114 log_parse_environment();
117 r
= parse_argv(argc
, argv
);
119 return r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;
126 log_error_errno(r
, "Failed to check for VM: %m");
133 r
= detect_container();
135 log_error_errno(r
, "Failed to check for container: %m");
142 r
= running_in_chroot();
144 log_error_errno(r
, "Failed to check for chroot() environment: %m");
148 return r
? EXIT_SUCCESS
: EXIT_FAILURE
;
150 case ONLY_PRIVATE_USERS
:
151 r
= running_in_userns();
153 log_error_errno(r
, "Failed to check for user namespace: %m");
157 return r
? EXIT_SUCCESS
: EXIT_FAILURE
;
159 case ANY_VIRTUALIZATION
:
161 r
= detect_virtualization();
163 log_error_errno(r
, "Failed to check for virtualization: %m");
171 puts(virtualization_to_string(r
));
173 return r
!= VIRTUALIZATION_NONE
? EXIT_SUCCESS
: EXIT_FAILURE
;