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 "unit-name.h"
36 #include "user-util.h"
38 DEFINE_TRIVIAL_CLEANUP_FUNC(Machine
*, machine_free
);
40 int machine_new(Manager
*manager
, MachineClass
class, const char *name
, Machine
**ret
) {
41 _cleanup_(machine_freep
) Machine
*m
= NULL
;
45 assert(class < _MACHINE_CLASS_MAX
);
49 /* Passing class == _MACHINE_CLASS_INVALID here is fine. It
50 * means as much as "we don't know yet", and that we'll figure
51 * it out later when loading the state file. */
58 .leader
= PIDREF_NULL
,
61 m
->name
= strdup(name
);
65 if (class != MACHINE_HOST
) {
66 m
->state_file
= path_join("/run/systemd/machines", m
->name
);
73 r
= hashmap_put(manager
->machines
, m
->name
, m
);
83 Machine
* machine_free(Machine
*m
) {
88 operation_free(m
->operations
);
91 LIST_REMOVE(gc_queue
, m
->manager
->machine_gc_queue
, m
);
93 machine_release_unit(m
);
97 (void) hashmap_remove(m
->manager
->machines
, m
->name
);
99 if (m
->manager
->host_machine
== m
)
100 m
->manager
->host_machine
= NULL
;
102 if (pidref_is_set(&m
->leader
)) {
103 (void) hashmap_remove_value(m
->manager
->machine_leaders
, PID_TO_PTR(m
->leader
.pid
), m
);
104 pidref_done(&m
->leader
);
107 sd_bus_message_unref(m
->create_message
);
112 free(m
->root_directory
);
117 int machine_save(Machine
*m
) {
118 _cleanup_(unlink_and_freep
) char *temp_path
= NULL
;
119 _cleanup_fclose_
FILE *f
= NULL
;
130 r
= mkdir_safe_label("/run/systemd/machines", 0755, 0, 0, MKDIR_WARN_MODE
);
134 r
= fopen_temporary(m
->state_file
, &f
, &temp_path
);
138 (void) fchmod(fileno(f
), 0644);
141 "# This is private data. Do not parse.\n"
146 _cleanup_free_
char *escaped
= NULL
;
148 escaped
= cescape(m
->unit
);
154 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 */
158 fprintf(f
, "SCOPE_JOB=%s\n", m
->scope_job
);
161 _cleanup_free_
char *escaped
= NULL
;
163 escaped
= cescape(m
->service
);
168 fprintf(f
, "SERVICE=%s\n", escaped
);
171 if (m
->root_directory
) {
172 _cleanup_free_
char *escaped
= NULL
;
174 escaped
= cescape(m
->root_directory
);
179 fprintf(f
, "ROOT=%s\n", escaped
);
182 if (!sd_id128_is_null(m
->id
))
183 fprintf(f
, "ID=" SD_ID128_FORMAT_STR
"\n", SD_ID128_FORMAT_VAL(m
->id
));
185 if (pidref_is_set(&m
->leader
))
186 fprintf(f
, "LEADER="PID_FMT
"\n", m
->leader
.pid
);
188 if (m
->class != _MACHINE_CLASS_INVALID
)
189 fprintf(f
, "CLASS=%s\n", machine_class_to_string(m
->class));
191 if (dual_timestamp_is_set(&m
->timestamp
))
193 "REALTIME="USEC_FMT
"\n"
194 "MONOTONIC="USEC_FMT
"\n",
195 m
->timestamp
.realtime
,
196 m
->timestamp
.monotonic
);
198 if (m
->n_netif
> 0) {
203 for (i
= 0; i
< m
->n_netif
; i
++) {
207 fprintf(f
, "%i", m
->netif
[i
]);
213 r
= fflush_and_check(f
);
217 if (rename(temp_path
, m
->state_file
) < 0) {
222 temp_path
= mfree(temp_path
);
227 /* Create a symlink from the unit name to the machine
228 * name, so that we can quickly find the machine for
229 * each given unit. Ignore error. */
230 sl
= strjoina("/run/systemd/machines/unit:", m
->unit
);
231 (void) symlink(m
->name
, sl
);
237 (void) unlink(m
->state_file
);
239 return log_error_errno(r
, "Failed to save machine data %s: %m", m
->state_file
);
242 static void machine_unlink(Machine
*m
) {
248 sl
= strjoina("/run/systemd/machines/unit:", m
->unit
);
253 (void) unlink(m
->state_file
);
256 int machine_load(Machine
*m
) {
257 _cleanup_free_
char *realtime
= NULL
, *monotonic
= NULL
, *id
= NULL
, *leader
= NULL
, *class = NULL
, *netif
= NULL
;
265 r
= parse_env_file(NULL
, m
->state_file
,
267 "SCOPE_JOB", &m
->scope_job
,
268 "SERVICE", &m
->service
,
269 "ROOT", &m
->root_directory
,
273 "REALTIME", &realtime
,
274 "MONOTONIC", &monotonic
,
279 return log_error_errno(r
, "Failed to read %s: %m", m
->state_file
);
282 (void) sd_id128_from_string(id
, &m
->id
);
285 pidref_done(&m
->leader
);
286 r
= pidref_set_pidstr(&m
->leader
, leader
);
288 log_debug_errno(r
, "Failed to set leader PID to '%s', ignoring: %m", leader
);
294 c
= machine_class_from_string(class);
300 (void) deserialize_usec(realtime
, &m
->timestamp
.realtime
);
302 (void) deserialize_usec(monotonic
, &m
->timestamp
.monotonic
);
305 _cleanup_free_
int *ni
= NULL
;
311 _cleanup_free_
char *word
= NULL
;
313 r
= extract_first_word(&p
, &word
, NULL
, 0);
319 log_warning_errno(r
, "Failed to parse NETIF: %s", netif
);
323 r
= parse_ifindex(word
);
327 if (!GREEDY_REALLOC(ni
, nr
+ 1))
333 free_and_replace(m
->netif
, ni
);
340 static int machine_start_scope(
342 sd_bus_message
*more_properties
,
343 sd_bus_error
*error
) {
345 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
346 _cleanup_free_
char *escaped
= NULL
, *unit
= NULL
;
347 const char *description
;
351 assert(pidref_is_set(&machine
->leader
));
352 assert(!machine
->unit
);
354 escaped
= unit_name_escape(machine
->name
);
358 unit
= strjoin("machine-", escaped
, ".scope");
362 r
= bus_message_new_method_call(
363 machine
->manager
->bus
,
366 "StartTransientUnit");
370 r
= sd_bus_message_append(m
, "ss", unit
, "fail");
374 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
378 r
= sd_bus_message_append(m
, "(sv)", "Slice", "s", SPECIAL_MACHINE_SLICE
);
382 description
= strjoina(machine
->class == MACHINE_VM
? "Virtual Machine " : "Container ", machine
->name
);
383 r
= sd_bus_message_append(m
, "(sv)", "Description", "s", description
);
387 r
= bus_append_scope_pidref(m
, &machine
->leader
);
391 r
= sd_bus_message_append(m
, "(sv)(sv)(sv)(sv)",
393 "CollectMode", "s", "inactive-or-failed",
395 "TasksMax", "t", UINT64_C(16384));
399 if (more_properties
) {
400 r
= sd_bus_message_copy(m
, more_properties
, true);
405 r
= sd_bus_message_close_container(m
);
409 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
413 r
= sd_bus_call(NULL
, m
, 0, error
, &reply
);
417 machine
->unit
= TAKE_PTR(unit
);
418 machine
->referenced
= true;
421 r
= sd_bus_message_read(reply
, "o", &job
);
425 return free_and_strdup(&machine
->scope_job
, job
);
428 static int machine_ensure_scope(Machine
*m
, sd_bus_message
*properties
, sd_bus_error
*error
) {
432 assert(m
->class != MACHINE_HOST
);
435 r
= machine_start_scope(m
, properties
, error
);
437 return log_error_errno(r
, "Failed to start machine scope: %s", bus_error_message(error
, r
));
441 hashmap_put(m
->manager
->machine_units
, m
->unit
, m
);
446 int machine_start(Machine
*m
, sd_bus_message
*properties
, sd_bus_error
*error
) {
451 if (!IN_SET(m
->class, MACHINE_CONTAINER
, MACHINE_VM
))
457 r
= hashmap_put(m
->manager
->machine_leaders
, PID_TO_PTR(m
->leader
.pid
), m
);
462 r
= machine_ensure_scope(m
, properties
, error
);
467 "MESSAGE_ID=" SD_MESSAGE_MACHINE_START_STR
,
469 "LEADER="PID_FMT
, m
->leader
.pid
,
470 LOG_MESSAGE("New machine %s.", m
->name
));
472 if (!dual_timestamp_is_set(&m
->timestamp
))
473 dual_timestamp_get(&m
->timestamp
);
477 /* Save new machine data */
480 machine_send_signal(m
, true);
481 (void) manager_enqueue_nscd_cache_flush(m
->manager
);
486 int machine_stop(Machine
*m
) {
491 if (!IN_SET(m
->class, MACHINE_CONTAINER
, MACHINE_VM
))
495 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
498 r
= manager_stop_unit(m
->manager
, m
->unit
, &error
, &job
);
500 return log_error_errno(r
, "Failed to stop machine scope: %s", bus_error_message(&error
, r
));
502 free_and_replace(m
->scope_job
, job
);
508 (void) manager_enqueue_nscd_cache_flush(m
->manager
);
513 int machine_finalize(Machine
*m
) {
518 "MESSAGE_ID=" SD_MESSAGE_MACHINE_STOP_STR
,
520 "LEADER="PID_FMT
, m
->leader
.pid
,
521 LOG_MESSAGE("Machine %s terminated.", m
->name
));
523 m
->stopping
= true; /* The machine is supposed to be going away. Don't try to kill it. */
527 machine_add_to_gc_queue(m
);
530 machine_send_signal(m
, false);
537 bool machine_may_gc(Machine
*m
, bool drop_not_started
) {
540 if (m
->class == MACHINE_HOST
)
543 if (drop_not_started
&& !m
->started
)
546 if (m
->scope_job
&& manager_job_is_active(m
->manager
, m
->scope_job
))
549 if (m
->unit
&& manager_unit_is_active(m
->manager
, m
->unit
))
555 void machine_add_to_gc_queue(Machine
*m
) {
561 LIST_PREPEND(gc_queue
, m
->manager
->machine_gc_queue
, m
);
562 m
->in_gc_queue
= true;
565 MachineState
machine_get_state(Machine
*s
) {
568 if (s
->class == MACHINE_HOST
)
569 return MACHINE_RUNNING
;
572 return MACHINE_CLOSING
;
575 return MACHINE_OPENING
;
577 return MACHINE_RUNNING
;
580 int machine_kill(Machine
*m
, KillWho who
, int signo
) {
583 if (!IN_SET(m
->class, MACHINE_VM
, MACHINE_CONTAINER
))
589 if (who
== KILL_LEADER
) /* If we shall simply kill the leader, do so directly */
590 return pidref_kill(&m
->leader
, signo
);
592 /* Otherwise, make PID 1 do it for us, for the entire cgroup */
593 return manager_kill_unit(m
->manager
, m
->unit
, signo
, NULL
);
596 int machine_openpt(Machine
*m
, int flags
, char **ret_slave
) {
602 return openpt_allocate(flags
, ret_slave
);
604 case MACHINE_CONTAINER
:
605 if (!pidref_is_set(&m
->leader
))
608 return openpt_allocate_in_namespace(m
->leader
.pid
, flags
, ret_slave
);
615 int machine_open_terminal(Machine
*m
, const char *path
, int mode
) {
621 return open_terminal(path
, mode
);
623 case MACHINE_CONTAINER
:
624 if (!pidref_is_set(&m
->leader
))
627 return open_terminal_in_namespace(m
->leader
.pid
, path
, mode
);
634 void machine_release_unit(Machine
*m
) {
641 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
644 r
= manager_unref_unit(m
->manager
, m
->unit
, &error
);
646 log_warning_errno(r
, "Failed to drop reference to machine scope, ignoring: %s",
647 bus_error_message(&error
, r
));
649 m
->referenced
= false;
652 (void) hashmap_remove(m
->manager
->machine_units
, m
->unit
);
653 m
->unit
= mfree(m
->unit
);
656 int machine_get_uid_shift(Machine
*m
, uid_t
*ret
) {
657 char p
[STRLEN("/proc//uid_map") + DECIMAL_STR_MAX(pid_t
) + 1];
658 uid_t uid_base
, uid_shift
, uid_range
;
659 gid_t gid_base
, gid_shift
, gid_range
;
660 _cleanup_fclose_
FILE *f
= NULL
;
666 /* Return the base UID/GID of the specified machine. Note that this only works for containers with simple
667 * mappings. In most cases setups should be simple like this, and administrators should only care about the
668 * basic offset a container has relative to the host. This is what this function exposes.
670 * If we encounter any more complex mappings we politely refuse this with ENXIO. */
672 if (m
->class == MACHINE_HOST
) {
677 if (m
->class != MACHINE_CONTAINER
)
680 xsprintf(p
, "/proc/" PID_FMT
"/uid_map", m
->leader
.pid
);
683 if (errno
== ENOENT
) {
684 /* If the file doesn't exist, user namespacing is off in the kernel, return a zero mapping hence. */
692 /* Read the first line. There's at least one. */
694 k
= fscanf(f
, UID_FMT
" " UID_FMT
" " UID_FMT
"\n", &uid_base
, &uid_shift
, &uid_range
);
697 return errno_or_else(EIO
);
702 /* Not a mapping starting at 0? Then it's a complex mapping we can't expose here. */
705 /* Insist that at least the nobody user is mapped, everything else is weird, and hence complex, and we don't support it */
706 if (uid_range
< UID_NOBODY
)
709 /* If there's more than one line, then we don't support this mapping. */
710 r
= safe_fgetc(f
, NULL
);
713 if (r
!= 0) /* Insist on EOF */
718 xsprintf(p
, "/proc/" PID_FMT
"/gid_map", m
->leader
.pid
);
723 /* Read the first line. There's at least one. */
725 k
= fscanf(f
, GID_FMT
" " GID_FMT
" " GID_FMT
"\n", &gid_base
, &gid_shift
, &gid_range
);
728 return errno_or_else(EIO
);
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
;
761 /* This is a generic implementation for both uids and gids, under the assumptions they have the same types and semantics. */
762 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
766 /* Checks if the specified host UID is owned by the machine, and returns the UID it maps to
767 * internally in the machine */
769 if (machine
->class != MACHINE_CONTAINER
)
772 p
= procfs_file_alloca(machine
->leader
.pid
, map_file
);
775 log_debug_errno(errno
, "Failed to open %s, ignoring.", p
);
780 uid_t uid_base
, uid_shift
, uid_range
, converted
;
784 k
= fscanf(f
, UID_FMT
" " UID_FMT
" " UID_FMT
, &uid_base
, &uid_shift
, &uid_range
);
785 if (k
< 0 && feof(f
))
789 return errno_or_else(EIO
);
794 /* The private user namespace is disabled, ignoring. */
798 if (uid
< uid_shift
|| uid
>= uid_shift
+ uid_range
)
801 converted
= (uid
- uid_shift
+ uid_base
);
802 if (!uid_is_valid(converted
))
805 if (ret_internal_uid
)
806 *ret_internal_uid
= converted
;
812 if (ret_internal_uid
)
813 *ret_internal_uid
= UID_INVALID
;
818 int machine_owns_uid(Machine
*machine
, uid_t uid
, uid_t
*ret_internal_uid
) {
819 return machine_owns_uid_internal(machine
, "uid_map", uid
, ret_internal_uid
);
822 int machine_owns_gid(Machine
*machine
, gid_t gid
, gid_t
*ret_internal_gid
) {
823 return machine_owns_uid_internal(machine
, "gid_map", (uid_t
) gid
, (uid_t
*) ret_internal_gid
);
826 static int machine_translate_uid_internal(
828 const char *map_file
, /* "uid_map" or "gid_map" */
830 uid_t
*ret_host_uid
) {
832 _cleanup_fclose_
FILE *f
= NULL
;
835 /* This is a generic implementation for both uids and gids, under the assumptions they have the same types and semantics. */
836 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
839 assert(uid_is_valid(uid
));
841 if (machine
->class != MACHINE_CONTAINER
)
844 /* Translates a machine UID into a host UID */
846 p
= procfs_file_alloca(machine
->leader
.pid
, map_file
);
852 uid_t uid_base
, uid_shift
, uid_range
, converted
;
856 k
= fscanf(f
, UID_FMT
" " UID_FMT
" " UID_FMT
, &uid_base
, &uid_shift
, &uid_range
);
857 if (k
< 0 && feof(f
))
861 return errno_or_else(EIO
);
866 if (uid
< uid_base
|| uid
>= uid_base
+ uid_range
)
869 converted
= uid
- uid_base
+ uid_shift
;
870 if (!uid_is_valid(converted
))
874 *ret_host_uid
= converted
;
881 int machine_translate_uid(Machine
*machine
, gid_t uid
, gid_t
*ret_host_uid
) {
882 return machine_translate_uid_internal(machine
, "uid_map", uid
, ret_host_uid
);
885 int machine_translate_gid(Machine
*machine
, gid_t gid
, gid_t
*ret_host_gid
) {
886 return machine_translate_uid_internal(machine
, "gid_map", (uid_t
) gid
, (uid_t
*) ret_host_gid
);
889 static const char* const machine_class_table
[_MACHINE_CLASS_MAX
] = {
890 [MACHINE_CONTAINER
] = "container",
892 [MACHINE_HOST
] = "host",
895 DEFINE_STRING_TABLE_LOOKUP(machine_class
, MachineClass
);
897 static const char* const machine_state_table
[_MACHINE_STATE_MAX
] = {
898 [MACHINE_OPENING
] = "opening",
899 [MACHINE_RUNNING
] = "running",
900 [MACHINE_CLOSING
] = "closing"
903 DEFINE_STRING_TABLE_LOOKUP(machine_state
, MachineState
);
905 static const char* const kill_who_table
[_KILL_WHO_MAX
] = {
906 [KILL_LEADER
] = "leader",
910 DEFINE_STRING_TABLE_LOOKUP(kill_who
, KillWho
);