HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/vmspawn/vmspawn.c

198,981 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 1258b35c7ded8fefe9ea7f21e6147dfd8810fc39

Lines 4001–4443 of 4,443

        } else {
                if (arg_runtime_scope == RUNTIME_SCOPE_SYSTEM)
                        r = cg_pid_get_unit(0, &unit);
                else
                        r = cg_pid_get_user_unit(0, &unit);
                if (r < 0)
                        return log_error_errno(r, "Failed to get our own unit: %m");
        }
 
        MachineRegistrationContext machine_ctx = {
                .scope      = arg_runtime_scope == RUNTIME_SCOPE_SYSTEM ? RUNTIME_SCOPE_SYSTEM : _RUNTIME_SCOPE_INVALID,
                .system_bus = system_bus,
                .user_bus   = runtime_bus,
        };
        if (arg_register != 0) {
                char vm_address[STRLEN("vsock/") + DECIMAL_STR_MAX(unsigned)];
                xsprintf(vm_address, "vsock/%u", child_cid);
 
                const MachineRegistration reg = {
                        .name                 = arg_machine,
                        .id                   = arg_uuid,
                        .service              = "systemd-vmspawn",
                        .class                = "vm",
                        .pidref               = &child_pidref,
                        .root_directory       = arg_directory,
                        .vsock_cid            = child_cid,
                        .ssh_address          = child_cid != VMADDR_CID_ANY ? vm_address : NULL,
                        .ssh_private_key_path = ssh_private_key_path,
                        .control_address      = control_address,
                        .allocate_unit        = !arg_keep_unit,
                };
 
                r = register_machine_with_fallback_and_log(
                                &machine_ctx,
                                &reg,
                                /* graceful= */ arg_register < 0);
                if (r < 0)
                        return r;
        }
 
        /* Report that the VM is now set up */
        (void) sd_notifyf(/* unset_environment= */ false,
                          "STATUS=VM started.\n"
                          "X_VMSPAWN_LEADER_PID=" PID_FMT, child_pidref.pid);
        if (!arg_notify_ready) {
                r = sd_notify(/* unset_environment= */ false, "READY=1\n");
                if (r < 0)
                        log_warning_errno(r, "Failed to send readiness notification, ignoring: %m");
        }
 
        /* All operations that might need Polkit authorizations (i.e. machine registration, netif
         * acquisition, …) are complete now, get rid of the agent again, so that we retain exclusive control
         * of the TTY from now on. */
        polkit_agent_close();
 
        _cleanup_(sd_event_source_unrefp) sd_event_source *notify_event_source = NULL;
 
        if (system_bus) {
                r = sd_bus_attach_event(system_bus, event, 0);
                if (r < 0)
                        return log_error_errno(r, "Failed to attach system bus to event loop: %m");
        }
 
        if (user_bus) {
                r = sd_bus_attach_event(user_bus, event, 0);
                if (r < 0)
                        return log_error_errno(r, "Failed to attach user bus to event loop: %m");
        }
 
        int exit_status = INT_MAX;
        if (use_vsock) {
                r = setup_notify_parent(event, notify_sock_fd, &exit_status, &notify_event_source);
                if (r < 0)
                        return log_error_errno(r, "Failed to setup event loop to handle VSOCK notify events: %m");
        }
 
        /* Used when talking to pid1 via SSH, but must survive until the function ends. */
        SSHInfo ssh_info = {
                .cid = child_cid,
                .private_key_path = ssh_private_key_path,
                .port = 22,
        };
        ShutdownInfo shutdown_info = {
                .ssh_info = &ssh_info,
                .pidref = &child_pidref,
        };
 
        (void) sd_event_add_signal(event, NULL, SIGINT | SD_EVENT_SIGNAL_PROCMASK, shutdown_vm_graceful, &shutdown_info);
        (void) sd_event_add_signal(event, NULL, SIGTERM | SD_EVENT_SIGNAL_PROCMASK, shutdown_vm_graceful, &shutdown_info);
        (void) sd_event_add_signal(event, NULL, (SIGRTMIN+4) | SD_EVENT_SIGNAL_PROCMASK, shutdown_vm_graceful, &shutdown_info);
 
        (void) sd_event_add_signal(event, NULL, (SIGRTMIN+18) | SD_EVENT_SIGNAL_PROCMASK, sigrtmin18_handler, NULL);
 
        r = sd_event_add_memory_pressure(event, NULL, NULL, NULL);
        if (r < 0)
                log_debug_errno(r, "Failed to allocate memory pressure event source, ignoring: %m");
 
        /* Exit when the child exits */
        r = event_add_child_pidref(event, /* ret= */ NULL, &child_pidref, WEXITED, on_child_exit, /* userdata= */ NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to watch qemu process: %m");
 
        _cleanup_(osc_context_closep) sd_id128_t osc_context_id = SD_ID128_NULL;
        _cleanup_(pty_forward_freep) PTYForward *forward = NULL;
        if (master >= 0) {
                r = pty_forward_new(event, master, ptyfwd_flags, &forward);
                if (r < 0)
                        return log_error_errno(r, "Failed to create PTY forwarder: %m");
 
                if (!FLAGS_SET(ptyfwd_flags, PTY_FORWARD_DUMB_TERMINAL)) {
                        if (!terminal_is_dumb()) {
                                r = osc_context_open_vm(arg_machine, /* ret_seq= */ NULL, &osc_context_id);
                                if (r < 0)
                                        return r;
                        }
 
                        if (!arg_background) {
                                _cleanup_free_ char *bg = NULL;
 
                                r = terminal_tint_color(130 /* green */, &bg);
                                if (r < 0)
                                        log_debug_errno(r, "Failed to determine terminal background color, not tinting.");
                                else
                                        (void) pty_forward_set_background_color(forward, bg);
                        } else if (!isempty(arg_background))
                                (void) pty_forward_set_background_color(forward, arg_background);
 
                        (void) pty_forward_set_window_title(forward, GLYPH_GREEN_CIRCLE, /* hostname= */ NULL,
                                                            STRV_MAKE("Virtual Machine", arg_machine));
                }
        }
 
        r = sd_event_loop(event);
        if (r < 0)
                return log_error_errno(r, "Failed to run event loop: %m");
 
        /* Kill if it is not dead yet anyway */
        if (scope_allocated)
                terminate_scope(runtime_bus, arg_machine);
 
        unregister_machine_with_fallback_and_log(&machine_ctx, arg_machine);
 
        if (use_vsock) {
                if (exit_status == INT_MAX) {
                        log_debug("Couldn't retrieve inner EXIT_STATUS from VSOCK");
                        return EXIT_SUCCESS;
                }
                if (exit_status != 0)
                        log_warning("Non-zero exit code received: %d", exit_status);
                return exit_status;
        }
 
        return 0;
}
 
static int determine_names(void) {
        int r;
 
        if (!arg_directory && !arg_image) {
                if (arg_machine) {
                        _cleanup_(image_unrefp) Image *i = NULL;
 
                        /* Use both user and system images in user mode, use only system images in system mode. */
                        r = image_find(arg_runtime_scope == RUNTIME_SCOPE_USER ? _RUNTIME_SCOPE_INVALID : arg_runtime_scope,
                                       IMAGE_MACHINE,
                                       arg_machine,
                                       /* root= */ NULL,
                                       &i);
                        if (r == -ENOENT)
                                return log_error_errno(r, "No image for machine '%s'.", arg_machine);
                        if (r < 0)
                                return log_error_errno(r, "Failed to find image for machine '%s': %m", arg_machine);
 
                        switch (i->type) {
                        case IMAGE_RAW:
                        case IMAGE_BLOCK:
                                r = free_and_strdup(&arg_image, i->path);
                                break;
 
                        case IMAGE_DIRECTORY:
                        case IMAGE_SUBVOLUME:
                                r = free_and_strdup(&arg_directory, i->path);
                                break;
 
                        default:
                                return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                                       "Image '%s' at '%s' has unsupported type '%s'. "
                                                       "Please use 'systemd-nspawn -M %s' instead.",
                                                       arg_machine, i->path, image_type_to_string(i->type), arg_machine);
                        }
                        if (r < 0)
                                return log_oom();
                } else {
                        r = safe_getcwd(&arg_directory);
                        if (r < 0)
                                return log_error_errno(r, "Failed to determine current directory: %m");
                }
        }
 
        if (!arg_machine) {
                if (arg_directory && path_equal(arg_directory, "/")) {
                        arg_machine = gethostname_malloc();
                        if (!arg_machine)
                                return log_oom();
                } else if (arg_image) {
                        char *e;
 
                        r = path_extract_filename(arg_image, &arg_machine);
                        if (r < 0)
                                return log_error_errno(r, "Failed to extract file name from '%s': %m", arg_image);
 
                        /* Truncate suffix if there is one */
                        e = endswith(arg_machine, ".raw");
                        if (e)
                                *e = 0;
                } else {
                        r = path_extract_filename(arg_directory, &arg_machine);
                        if (r < 0)
                                return log_error_errno(r, "Failed to extract file name from '%s': %m", arg_directory);
                }
                /* Add a random suffix when this is an ephemeral machine, so that we can run many
                 * instances at once without manually having to specify -M each time. */
                if (arg_ephemeral)
                        if (strextendf(&arg_machine, "-%016" PRIx64, random_u64()) < 0)
                                return log_oom();
 
                hostname_cleanup(arg_machine);
                if (!hostname_is_valid(arg_machine, 0))
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine machine name automatically, please use -M.");
        }
 
        return 0;
}
 
static int determine_kernel(void) {
        int r;
 
        if (!arg_linux && arg_directory) {
                /* A kernel is required for directory type images so attempt to find one under /boot and /efi.
                 * Reject a user --initrd= first: discovery would overwrite (and leak) it, and the
                 * --initrd=/--linux= consistency check in verify_arguments() is bypassed once discovery
                 * sets arg_linux. */
                if (!strv_isempty(arg_initrds))
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "--initrd= cannot be used with --directory= unless --linux= is also specified.");
 
                r = discover_boot_entry(arg_directory, &arg_linux, &arg_initrds);
                if (r < 0)
                        return log_error_errno(r, "Failed to locate UKI in directory type image, please specify one with --linux=.");
 
                log_debug("Discovered UKI image at %s", arg_linux);
        }
 
        if (!arg_linux) {
                if (arg_firmware_type == _FIRMWARE_INVALID)
                        arg_firmware_type = FIRMWARE_UEFI;
                return 0;
        }
 
        r = inspect_kernel(AT_FDCWD, arg_linux, &arg_linux_image_type);
        if (r < 0)
                return log_error_errno(r, "Failed to determine '%s' kernel image type: %m", arg_linux);
 
        if (arg_linux_image_type == KERNEL_IMAGE_TYPE_UNKNOWN) {
                if (arg_firmware_type == FIRMWARE_UEFI)
                        return log_error_errno(
                                        SYNTHETIC_ERRNO(EINVAL),
                                        "Kernel image '%s' is not a PE binary, --firmware=uefi (or a firmware path) is not supported.",
                                        arg_linux);
                if (arg_firmware_type == _FIRMWARE_INVALID)
                        arg_firmware_type = FIRMWARE_NONE;
        }
 
        if (arg_firmware_type == _FIRMWARE_INVALID)
                arg_firmware_type = FIRMWARE_UEFI;
 
        return 0;
}
 
static int verify_arguments(void) {
        if (!strv_isempty(arg_initrds) && !arg_linux)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Option --initrd= cannot be used without --linux=.");
 
        if (arg_firmware_type != FIRMWARE_UEFI && arg_linux_image_type == KERNEL_IMAGE_TYPE_UKI)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Booting a UKI requires --firmware=uefi.");
 
        if (arg_firmware_type == FIRMWARE_NONE && !arg_linux)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "--firmware=none requires --linux= to be specified.");
 
        if (arg_image_disk_type == DISK_TYPE_VIRTIO_SCSI_CDROM) {
                if (arg_ephemeral)
                        log_warning("--ephemeral has no effect with --image-disk-type=scsi-cd (CD-ROMs are read-only).");
                if (arg_discard_disk)
                        log_warning("--discard-disk has no effect with --image-disk-type=scsi-cd (CD-ROMs are read-only).");
                if (arg_grow_image)
                        log_warning("--grow-image has no effect with --image-disk-type=scsi-cd (CD-ROMs are read-only).");
        }
 
        /* In ephemeral mode the size is picked when creating the qcow2 overlay, so the base image format
         * doesn't matter. */
        if (arg_grow_image && arg_image_format == IMAGE_FORMAT_QCOW2 && !arg_ephemeral)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "--grow-image is not supported for qcow2 images, use 'qemu-img resize FILE SIZE'.");
 
        if (arg_confidential_computing != COCO_NO) {
                /* Confidential computing firmware is stateless, there is no NVRAM to instantiate from a
                 * template or to persist. */
                if (arg_efi_nvram_template)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "--efi-nvram-template= cannot be used with --coco=, "
                                               "confidential computing firmware is stateless.");
                if (arg_efi_nvram_state_mode == STATE_PATH)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "An explicit --efi-nvram-state= path cannot be used with --coco=, "
                                               "confidential computing firmware is stateless. Use 'off' or 'auto'.");
        }
 
        if (arg_confidential_computing == COCO_SEV_SNP) {
                if (native_architecture() != ARCHITECTURE_X86_64)
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                               "--coco=sev-snp is only supported on x86_64.");
                if (arg_kvm == 0)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "--coco=sev-snp requires KVM, remove --kvm=no.");
                if (arg_firmware_type != FIRMWARE_UEFI)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "--coco=sev-snp can't be used with %s firmware",
                                               firmware_to_string(arg_firmware_type));
                if (arg_tpm > 0)
                        log_warning("TPM can't be trusted by the confidential computing guest");
                /* kernel-hashes=on only covers what QEMU itself loads via -kernel/-initrd/-append.
                 * Without --linux= the kernel and initrd come off disk via OVMF and aren't part
                 * of the launch measurement, leaving the guest unattestable in any meaningful
                 * way. Require direct kernel boot so the boot chain starts from a measured state. */
                if (!arg_linux)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "--coco=sev-snp requires --linux= "
                                               "so kernel, initrd and cmdline are covered by the launch measurement.");
        }
 
        if (arg_confidential_computing == COCO_TDX) {
                if (native_architecture() != ARCHITECTURE_X86_64)
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                               "--coco=tdx is only supported on x86_64.");
                if (arg_kvm == 0)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "--coco=tdx requires KVM, remove --kvm=no.");
                if (arg_firmware_type != FIRMWARE_UEFI)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "--coco=tdx can't be used with %s firmware",
                                               firmware_to_string(arg_firmware_type));
                if (arg_tpm > 0)
                        log_warning("TPM can't be trusted by the confidential computing guest");
        }
 
        return 0;
}
 
static int run(int argc, char *argv[]) {
        int r, kvm_device_fd = -EBADF, vhost_device_fd = -EBADF;
        _cleanup_strv_free_ char **names = NULL;
 
        LIBBLKID_NOTE(recommended);
        LIBSELINUX_NOTE(recommended);
 
        log_setup();
 
        arg_runtime_scope = getuid() == 0 ? RUNTIME_SCOPE_SYSTEM : RUNTIME_SCOPE_USER;
 
        r = parse_environment();
        if (r < 0)
                return r;
 
        r = parse_argv(argc, argv);
        if (r <= 0)
                return r;
 
        if (arg_firmware_describe) {
                _cleanup_(ovmf_config_freep) OvmfConfig *ovmf_config = NULL;
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *json = NULL;
 
                r = discover_ovmf_config(&ovmf_config, &json);
                if (r < 0)
                        return r;
 
                r = sd_json_variant_dump(json, SD_JSON_FORMAT_PRETTY|SD_JSON_FORMAT_COLOR_AUTO, stdout, /* prefix= */ NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to output JSON: %m");
 
                return 0;
        }
 
        r = determine_names();
        if (r < 0)
                return r;
 
        r = determine_kernel();
        if (r < 0)
                return r;
 
        r = verify_arguments();
        if (r < 0)
                return r;
 
        if (!arg_quiet && arg_console_mode != CONSOLE_GUI) {
                _cleanup_free_ char *u = NULL;
                const char *vm_path = arg_image ?: arg_directory;
                (void) terminal_urlify_path(vm_path, vm_path, &u);
 
                log_info("%s %sSpawning VM %s on %s.%s",
                         glyph(GLYPH_LIGHT_SHADE), ansi_grey(), arg_machine, u ?: vm_path, ansi_normal());
 
                if (arg_console_mode == CONSOLE_INTERACTIVE)
                        log_info("%s %sPress %sCtrl-]%s three times within 1s to kill VM.%s",
                                 glyph(GLYPH_LIGHT_SHADE), ansi_grey(), ansi_highlight(), ansi_grey(), ansi_normal());
                else if (arg_console_mode == CONSOLE_NATIVE)
                        log_info("%s %sPress %sCtrl-a x%s to kill VM.%s",
                                 glyph(GLYPH_LIGHT_SHADE), ansi_grey(), ansi_highlight(), ansi_grey(), ansi_normal());
        }
 
        int n = sd_listen_fds_with_names(true, &names);
        if (n < 0)
                return log_error_errno(n, "Failed to get passed file descriptors: %m");
 
        for (int i = 0; i < n; i++) {
                int fd = SD_LISTEN_FDS_START + i;
                if (streq(names[i], "kvm"))
                        kvm_device_fd = fd;
                else if (streq(names[i], "vhost-vsock"))
                        vhost_device_fd = fd;
                else {
                        log_notice("Couldn't recognize passed fd %d (%s), closing fd and ignoring...", fd, names[i]);
                        safe_close(fd);
                }
        }
 
        return run_virtual_machine(kvm_device_fd, vhost_device_fd);
}
 
DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);