1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
7 #include "sd-messages.h"
9 #include "alloc-util.h"
10 #include "bus-error.h"
11 #include "bus-locator.h"
12 #include "bus-unit-util.h"
15 #include "errno-util.h"
17 #include "extract-word.h"
20 #include "format-util.h"
23 #include "machine-dbus.h"
25 #include "mkdir-label.h"
26 #include "parse-util.h"
27 #include "path-util.h"
28 #include "process-util.h"
29 #include "serialize.h"
31 #include "stdio-util.h"
32 #include "string-table.h"
33 #include "terminal-util.h"
34 #include "tmpfile-util.h"
35 #include "uid-range.h"
36 #include "unit-name.h"
37 #include "user-util.h"
39 DEFINE_TRIVIAL_CLEANUP_FUNC(Machine
*, machine_free
);
41 int machine_new(Manager
*manager
, MachineClass
class, const char *name
, Machine
**ret
) {
42 _cleanup_(machine_freep
) Machine
*m
= NULL
;
46 assert(class < _MACHINE_CLASS_MAX
);
50 /* Passing class == _MACHINE_CLASS_INVALID here is fine. It
51 * means as much as "we don't know yet", and that we'll figure
52 * it out later when loading the state file. */
59 .leader
= PIDREF_NULL
,
62 m
->name
= strdup(name
);
66 if (class != MACHINE_HOST
) {
67 m
->state_file
= path_join("/run/systemd/machines", m
->name
);
74 r
= hashmap_put(manager
->machines
, m
->name
, m
);
84 Machine
* machine_free(Machine
*m
) {
89 operation_free(m
->operations
);
93 LIST_REMOVE(gc_queue
, m
->manager
->machine_gc_queue
, m
);
96 machine_release_unit(m
);
101 (void) hashmap_remove(m
->manager
->machines
, m
->name
);
103 if (m
->manager
->host_machine
== m
)
104 m
->manager
->host_machine
= NULL
;
107 if (pidref_is_set(&m
->leader
)) {
109 (void) hashmap_remove_value(m
->manager
->machine_leaders
, PID_TO_PTR(m
->leader
.pid
), m
);
110 pidref_done(&m
->leader
);
113 sd_bus_message_unref(m
->create_message
);
118 free(m
->root_directory
);
123 int machine_save(Machine
*m
) {
124 _cleanup_(unlink_and_freep
) char *temp_path
= NULL
;
125 _cleanup_fclose_
FILE *f
= NULL
;
136 r
= mkdir_safe_label("/run/systemd/machines", 0755, 0, 0, MKDIR_WARN_MODE
);
140 r
= fopen_temporary(m
->state_file
, &f
, &temp_path
);
144 (void) fchmod(fileno(f
), 0644);
147 "# This is private data. Do not parse.\n"
152 _cleanup_free_
char *escaped
= NULL
;
154 escaped
= cescape(m
->unit
);
160 fprintf(f
, "SCOPE=%s\n", escaped
); /* We continue to call this "SCOPE=" because it is internal only, and we want to stay compatible with old files */
164 fprintf(f
, "SCOPE_JOB=%s\n", m
->scope_job
);
167 _cleanup_free_
char *escaped
= NULL
;
169 escaped
= cescape(m
->service
);
174 fprintf(f
, "SERVICE=%s\n", escaped
);
177 if (m
->root_directory
) {
178 _cleanup_free_
char *escaped
= NULL
;
180 escaped
= cescape(m
->root_directory
);
185 fprintf(f
, "ROOT=%s\n", escaped
);
188 if (!sd_id128_is_null(m
->id
))
189 fprintf(f
, "ID=" SD_ID128_FORMAT_STR
"\n", SD_ID128_FORMAT_VAL(m
->id
));
191 if (pidref_is_set(&m
->leader
))
192 fprintf(f
, "LEADER="PID_FMT
"\n", m
->leader
.pid
);
194 if (m
->class != _MACHINE_CLASS_INVALID
)
195 fprintf(f
, "CLASS=%s\n", machine_class_to_string(m
->class));
197 if (dual_timestamp_is_set(&m
->timestamp
))
199 "REALTIME="USEC_FMT
"\n"
200 "MONOTONIC="USEC_FMT
"\n",
201 m
->timestamp
.realtime
,
202 m
->timestamp
.monotonic
);
204 if (m
->n_netif
> 0) {
209 for (i
= 0; i
< m
->n_netif
; i
++) {
213 fprintf(f
, "%i", m
->netif
[i
]);
219 r
= fflush_and_check(f
);
223 if (rename(temp_path
, m
->state_file
) < 0) {
228 temp_path
= mfree(temp_path
);
233 /* Create a symlink from the unit name to the machine
234 * name, so that we can quickly find the machine for
235 * each given unit. Ignore error. */
236 sl
= strjoina("/run/systemd/machines/unit:", m
->unit
);
237 (void) symlink(m
->name
, sl
);
243 (void) unlink(m
->state_file
);
245 return log_error_errno(r
, "Failed to save machine data %s: %m", m
->state_file
);
248 static void machine_unlink(Machine
*m
) {
254 sl
= strjoina("/run/systemd/machines/unit:", m
->unit
);
259 (void) unlink(m
->state_file
);
262 int machine_load(Machine
*m
) {
263 _cleanup_free_
char *realtime
= NULL
, *monotonic
= NULL
, *id
= NULL
, *leader
= NULL
, *class = NULL
, *netif
= NULL
;
271 r
= parse_env_file(NULL
, m
->state_file
,
273 "SCOPE_JOB", &m
->scope_job
,
274 "SERVICE", &m
->service
,
275 "ROOT", &m
->root_directory
,
279 "REALTIME", &realtime
,
280 "MONOTONIC", &monotonic
,
285 return log_error_errno(r
, "Failed to read %s: %m", m
->state_file
);
288 (void) sd_id128_from_string(id
, &m
->id
);
291 pidref_done(&m
->leader
);
292 r
= pidref_set_pidstr(&m
->leader
, leader
);
294 log_debug_errno(r
, "Failed to set leader PID to '%s', ignoring: %m", leader
);
300 c
= machine_class_from_string(class);
306 (void) deserialize_usec(realtime
, &m
->timestamp
.realtime
);
308 (void) deserialize_usec(monotonic
, &m
->timestamp
.monotonic
);
311 _cleanup_free_
int *ni
= NULL
;
317 _cleanup_free_
char *word
= NULL
;
319 r
= extract_first_word(&p
, &word
, NULL
, 0);
325 log_warning_errno(r
, "Failed to parse NETIF: %s", netif
);
329 r
= parse_ifindex(word
);
333 if (!GREEDY_REALLOC(ni
, nr
+ 1))
339 free_and_replace(m
->netif
, ni
);
346 static int machine_start_scope(
348 sd_bus_message
*more_properties
,
349 sd_bus_error
*error
) {
351 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
352 _cleanup_free_
char *escaped
= NULL
, *unit
= NULL
;
353 const char *description
;
357 assert(pidref_is_set(&machine
->leader
));
358 assert(!machine
->unit
);
360 escaped
= unit_name_escape(machine
->name
);
364 unit
= strjoin("machine-", escaped
, ".scope");
368 r
= bus_message_new_method_call(
369 machine
->manager
->bus
,
372 "StartTransientUnit");
376 r
= sd_bus_message_append(m
, "ss", unit
, "fail");
380 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
384 r
= sd_bus_message_append(m
, "(sv)", "Slice", "s", SPECIAL_MACHINE_SLICE
);
388 description
= strjoina(machine
->class == MACHINE_VM
? "Virtual Machine " : "Container ", machine
->name
);
389 r
= sd_bus_message_append(m
, "(sv)", "Description", "s", description
);
393 r
= bus_append_scope_pidref(m
, &machine
->leader
, /* allow_pidfd = */ true);
397 r
= sd_bus_message_append(m
, "(sv)(sv)(sv)(sv)",
399 "CollectMode", "s", "inactive-or-failed",
401 "TasksMax", "t", UINT64_C(16384));
405 if (more_properties
) {
406 r
= sd_bus_message_copy(m
, more_properties
, true);
411 r
= sd_bus_message_close_container(m
);
415 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
419 r
= sd_bus_call(NULL
, m
, 0, error
, &reply
);
423 machine
->unit
= TAKE_PTR(unit
);
424 machine
->referenced
= true;
427 r
= sd_bus_message_read(reply
, "o", &job
);
431 return free_and_strdup(&machine
->scope_job
, job
);
434 static int machine_ensure_scope(Machine
*m
, sd_bus_message
*properties
, sd_bus_error
*error
) {
438 assert(m
->class != MACHINE_HOST
);
441 r
= machine_start_scope(m
, properties
, error
);
443 return log_error_errno(r
, "Failed to start machine scope: %s", bus_error_message(error
, r
));
447 hashmap_put(m
->manager
->machine_units
, m
->unit
, m
);
452 int machine_start(Machine
*m
, sd_bus_message
*properties
, sd_bus_error
*error
) {
457 if (!IN_SET(m
->class, MACHINE_CONTAINER
, MACHINE_VM
))
463 r
= hashmap_put(m
->manager
->machine_leaders
, PID_TO_PTR(m
->leader
.pid
), m
);
468 r
= machine_ensure_scope(m
, properties
, error
);
473 "MESSAGE_ID=" SD_MESSAGE_MACHINE_START_STR
,
475 "LEADER="PID_FMT
, m
->leader
.pid
,
476 LOG_MESSAGE("New machine %s.", m
->name
));
478 if (!dual_timestamp_is_set(&m
->timestamp
))
479 dual_timestamp_now(&m
->timestamp
);
483 /* Save new machine data */
486 machine_send_signal(m
, true);
487 (void) manager_enqueue_nscd_cache_flush(m
->manager
);
492 int machine_stop(Machine
*m
) {
497 if (!IN_SET(m
->class, MACHINE_CONTAINER
, MACHINE_VM
))
501 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
504 r
= manager_stop_unit(m
->manager
, m
->unit
, &error
, &job
);
506 return log_error_errno(r
, "Failed to stop machine scope: %s", bus_error_message(&error
, r
));
508 free_and_replace(m
->scope_job
, job
);
514 (void) manager_enqueue_nscd_cache_flush(m
->manager
);
519 int machine_finalize(Machine
*m
) {
524 "MESSAGE_ID=" SD_MESSAGE_MACHINE_STOP_STR
,
526 "LEADER="PID_FMT
, m
->leader
.pid
,
527 LOG_MESSAGE("Machine %s terminated.", m
->name
));
529 m
->stopping
= true; /* The machine is supposed to be going away. Don't try to kill it. */
533 machine_add_to_gc_queue(m
);
536 machine_send_signal(m
, false);
543 bool machine_may_gc(Machine
*m
, bool drop_not_started
) {
546 if (m
->class == MACHINE_HOST
)
549 if (drop_not_started
&& !m
->started
)
552 if (m
->scope_job
&& manager_job_is_active(m
->manager
, m
->scope_job
))
555 if (m
->unit
&& manager_unit_is_active(m
->manager
, m
->unit
))
561 void machine_add_to_gc_queue(Machine
*m
) {
567 LIST_PREPEND(gc_queue
, m
->manager
->machine_gc_queue
, m
);
568 m
->in_gc_queue
= true;
571 MachineState
machine_get_state(Machine
*s
) {
574 if (s
->class == MACHINE_HOST
)
575 return MACHINE_RUNNING
;
578 return MACHINE_CLOSING
;
581 return MACHINE_OPENING
;
583 return MACHINE_RUNNING
;
586 int machine_kill(Machine
*m
, KillWho who
, int signo
) {
589 if (!IN_SET(m
->class, MACHINE_VM
, MACHINE_CONTAINER
))
595 if (who
== KILL_LEADER
) /* If we shall simply kill the leader, do so directly */
596 return pidref_kill(&m
->leader
, signo
);
598 /* Otherwise, make PID 1 do it for us, for the entire cgroup */
599 return manager_kill_unit(m
->manager
, m
->unit
, signo
, NULL
);
602 int machine_openpt(Machine
*m
, int flags
, char **ret_slave
) {
608 return openpt_allocate(flags
, ret_slave
);
610 case MACHINE_CONTAINER
:
611 if (!pidref_is_set(&m
->leader
))
614 return openpt_allocate_in_namespace(m
->leader
.pid
, flags
, ret_slave
);
621 int machine_open_terminal(Machine
*m
, const char *path
, int mode
) {
627 return open_terminal(path
, mode
);
629 case MACHINE_CONTAINER
:
630 if (!pidref_is_set(&m
->leader
))
633 return open_terminal_in_namespace(m
->leader
.pid
, path
, mode
);
640 void machine_release_unit(Machine
*m
) {
647 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
650 r
= manager_unref_unit(m
->manager
, m
->unit
, &error
);
652 log_warning_errno(r
, "Failed to drop reference to machine scope, ignoring: %s",
653 bus_error_message(&error
, r
));
655 m
->referenced
= false;
658 (void) hashmap_remove(m
->manager
->machine_units
, m
->unit
);
659 m
->unit
= mfree(m
->unit
);
662 int machine_get_uid_shift(Machine
*m
, uid_t
*ret
) {
663 char p
[STRLEN("/proc//uid_map") + DECIMAL_STR_MAX(pid_t
) + 1];
664 uid_t uid_base
, uid_shift
, uid_range
;
665 gid_t gid_base
, gid_shift
, gid_range
;
666 _cleanup_fclose_
FILE *f
= NULL
;
672 /* Return the base UID/GID of the specified machine. Note that this only works for containers with simple
673 * mappings. In most cases setups should be simple like this, and administrators should only care about the
674 * basic offset a container has relative to the host. This is what this function exposes.
676 * If we encounter any more complex mappings we politely refuse this with ENXIO. */
678 if (m
->class == MACHINE_HOST
) {
683 if (m
->class != MACHINE_CONTAINER
)
686 xsprintf(p
, "/proc/" PID_FMT
"/uid_map", m
->leader
.pid
);
689 if (errno
== ENOENT
) {
690 /* If the file doesn't exist, user namespacing is off in the kernel, return a zero mapping hence. */
698 /* Read the first line. There's at least one. */
699 r
= uid_map_read_one(f
, &uid_base
, &uid_shift
, &uid_range
);
703 /* Not a mapping starting at 0? Then it's a complex mapping we can't expose here. */
706 /* Insist that at least the nobody user is mapped, everything else is weird, and hence complex, and we don't support it */
707 if (uid_range
< UID_NOBODY
)
710 /* If there's more than one line, then we don't support this mapping. */
711 r
= safe_fgetc(f
, NULL
);
714 if (r
!= 0) /* Insist on EOF */
719 xsprintf(p
, "/proc/" PID_FMT
"/gid_map", m
->leader
.pid
);
724 /* Read the first line. There's at least one. */
726 r
= fscanf(f
, GID_FMT
" " GID_FMT
" " GID_FMT
"\n", &gid_base
, &gid_shift
, &gid_range
);
728 return errno_or_else(ENOMSG
);
733 /* If there's more than one line, then we don't support this file. */
734 r
= safe_fgetc(f
, NULL
);
737 if (r
!= 0) /* Insist on EOF */
740 /* If the UID and GID mapping doesn't match, we don't support this mapping. */
741 if (uid_base
!= (uid_t
) gid_base
)
743 if (uid_shift
!= (uid_t
) gid_shift
)
745 if (uid_range
!= (uid_t
) gid_range
)
752 static int machine_owns_uid_internal(
754 const char *map_file
, /* "uid_map" or "gid_map" */
756 uid_t
*ret_internal_uid
) {
758 _cleanup_fclose_
FILE *f
= NULL
;
762 /* This is a generic implementation for both uids and gids, under the assumptions they have the same types and semantics. */
763 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
767 /* Checks if the specified host UID is owned by the machine, and returns the UID it maps to
768 * internally in the machine */
770 if (machine
->class != MACHINE_CONTAINER
)
773 p
= procfs_file_alloca(machine
->leader
.pid
, map_file
);
776 log_debug_errno(errno
, "Failed to open %s, ignoring.", p
);
781 uid_t uid_base
, uid_shift
, uid_range
, converted
;
783 r
= uid_map_read_one(f
, &uid_base
, &uid_shift
, &uid_range
);
789 /* The private user namespace is disabled, ignoring. */
793 if (uid
< uid_shift
|| uid
>= uid_shift
+ uid_range
)
796 converted
= (uid
- uid_shift
+ uid_base
);
797 if (!uid_is_valid(converted
))
800 if (ret_internal_uid
)
801 *ret_internal_uid
= converted
;
807 if (ret_internal_uid
)
808 *ret_internal_uid
= UID_INVALID
;
813 int machine_owns_uid(Machine
*machine
, uid_t uid
, uid_t
*ret_internal_uid
) {
814 return machine_owns_uid_internal(machine
, "uid_map", uid
, ret_internal_uid
);
817 int machine_owns_gid(Machine
*machine
, gid_t gid
, gid_t
*ret_internal_gid
) {
818 return machine_owns_uid_internal(machine
, "gid_map", (uid_t
) gid
, (uid_t
*) ret_internal_gid
);
821 static int machine_translate_uid_internal(
823 const char *map_file
, /* "uid_map" or "gid_map" */
825 uid_t
*ret_host_uid
) {
827 _cleanup_fclose_
FILE *f
= NULL
;
831 /* This is a generic implementation for both uids and gids, under the assumptions they have the same types and semantics. */
832 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
835 assert(uid_is_valid(uid
));
837 if (machine
->class != MACHINE_CONTAINER
)
840 /* Translates a machine UID into a host UID */
842 p
= procfs_file_alloca(machine
->leader
.pid
, map_file
);
848 uid_t uid_base
, uid_shift
, uid_range
, converted
;
850 r
= uid_map_read_one(f
, &uid_base
, &uid_shift
, &uid_range
);
856 if (uid
< uid_base
|| uid
>= uid_base
+ uid_range
)
859 converted
= uid
- uid_base
+ uid_shift
;
860 if (!uid_is_valid(converted
))
864 *ret_host_uid
= converted
;
872 int machine_translate_uid(Machine
*machine
, gid_t uid
, gid_t
*ret_host_uid
) {
873 return machine_translate_uid_internal(machine
, "uid_map", uid
, ret_host_uid
);
876 int machine_translate_gid(Machine
*machine
, gid_t gid
, gid_t
*ret_host_gid
) {
877 return machine_translate_uid_internal(machine
, "gid_map", (uid_t
) gid
, (uid_t
*) ret_host_gid
);
880 static const char* const machine_class_table
[_MACHINE_CLASS_MAX
] = {
881 [MACHINE_CONTAINER
] = "container",
883 [MACHINE_HOST
] = "host",
886 DEFINE_STRING_TABLE_LOOKUP(machine_class
, MachineClass
);
888 static const char* const machine_state_table
[_MACHINE_STATE_MAX
] = {
889 [MACHINE_OPENING
] = "opening",
890 [MACHINE_RUNNING
] = "running",
891 [MACHINE_CLOSING
] = "closing"
894 DEFINE_STRING_TABLE_LOOKUP(machine_state
, MachineState
);
896 static const char* const kill_who_table
[_KILL_WHO_MAX
] = {
897 [KILL_LEADER
] = "leader",
901 DEFINE_STRING_TABLE_LOOKUP(kill_who
, KillWho
);