1 /* SPDX-License-Identifier: LGPL-2.1+ */
8 #include "alloc-util.h"
10 #include "pretty-print.h"
11 #include "string-table.h"
15 static bool arg_quiet
= false;
22 } arg_mode
= ANY_VIRTUALIZATION
;
24 static int help(void) {
25 _cleanup_free_
char *link
= NULL
;
28 r
= terminal_urlify_man("systemd-detect-virt", "1", &link
);
32 printf("%s [OPTIONS...]\n\n"
33 "Detect execution in a virtualized environment.\n\n"
34 " -h --help Show this help\n"
35 " --version Show package version\n"
36 " -c --container Only detect whether we are run in a container\n"
37 " -v --vm Only detect whether we are run in a VM\n"
38 " -r --chroot Detect whether we are run in a chroot() environment\n"
39 " --private-users Only detect whether we are running in a user namespace\n"
40 " -q --quiet Don't output anything, just set return value\n"
41 " --list List all known and detectable types of virtualization\n"
42 "\nSee the %s for details.\n"
43 , program_invocation_short_name
50 static int parse_argv(int argc
, char *argv
[]) {
58 static const struct option options
[] = {
59 { "help", no_argument
, NULL
, 'h' },
60 { "version", no_argument
, NULL
, ARG_VERSION
},
61 { "container", no_argument
, NULL
, 'c' },
62 { "vm", no_argument
, NULL
, 'v' },
63 { "chroot", no_argument
, NULL
, 'r' },
64 { "private-users", no_argument
, NULL
, ARG_PRIVATE_USERS
},
65 { "quiet", no_argument
, NULL
, 'q' },
66 { "list", no_argument
, NULL
, ARG_LIST
},
75 while ((c
= getopt_long(argc
, argv
, "hqcvr", options
, NULL
)) >= 0)
90 arg_mode
= ONLY_CONTAINER
;
93 case ARG_PRIVATE_USERS
:
94 arg_mode
= ONLY_PRIVATE_USERS
;
102 arg_mode
= ONLY_CHROOT
;
106 DUMP_STRING_TABLE(virtualization
, int, _VIRTUALIZATION_MAX
);
113 assert_not_reached("Unhandled option");
117 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
118 "%s takes no arguments.",
119 program_invocation_short_name
);
124 static int run(int argc
, char *argv
[]) {
127 /* This is mostly intended to be used for scripts which want
128 * to detect whether we are being run in a virtualized
129 * environment or not */
131 log_parse_environment();
134 r
= parse_argv(argc
, argv
);
142 return log_error_errno(r
, "Failed to check for VM: %m");
146 r
= detect_container();
148 return log_error_errno(r
, "Failed to check for container: %m");
152 r
= running_in_chroot();
154 return log_error_errno(r
, "Failed to check for chroot() environment: %m");
157 case ONLY_PRIVATE_USERS
:
158 r
= running_in_userns();
160 return log_error_errno(r
, "Failed to check for user namespace: %m");
163 case ANY_VIRTUALIZATION
:
165 r
= detect_virtualization();
167 return log_error_errno(r
, "Failed to check for virtualization: %m");
172 puts(virtualization_to_string(r
));
174 return r
== VIRTUALIZATION_NONE
;
177 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);