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"
14 #include "errno-util.h"
16 #include "extract-word.h"
19 #include "format-util.h"
21 #include "machine-dbus.h"
23 #include "mkdir-label.h"
24 #include "parse-util.h"
25 #include "path-util.h"
26 #include "process-util.h"
27 #include "serialize.h"
29 #include "stdio-util.h"
30 #include "string-table.h"
31 #include "terminal-util.h"
32 #include "tmpfile-util.h"
33 #include "unit-name.h"
34 #include "user-util.h"
37 Machine
* machine_new(Manager
*manager
, MachineClass
class, const char *name
) {
41 assert(class < _MACHINE_CLASS_MAX
);
44 /* Passing class == _MACHINE_CLASS_INVALID here is fine. It
45 * means as much as "we don't know yet", and that we'll figure
46 * it out later when loading the state file. */
52 m
->name
= strdup(name
);
56 if (class != MACHINE_HOST
) {
57 m
->state_file
= path_join("/run/systemd/machines", m
->name
);
64 if (hashmap_put(manager
->machines
, m
->name
, m
) < 0)
77 Machine
* machine_free(Machine
*m
) {
82 operation_free(m
->operations
);
85 LIST_REMOVE(gc_queue
, m
->manager
->machine_gc_queue
, m
);
87 machine_release_unit(m
);
91 (void) hashmap_remove(m
->manager
->machines
, m
->name
);
93 if (m
->manager
->host_machine
== m
)
94 m
->manager
->host_machine
= NULL
;
97 (void) hashmap_remove_value(m
->manager
->machine_leaders
, PID_TO_PTR(m
->leader
), m
);
99 sd_bus_message_unref(m
->create_message
);
104 free(m
->root_directory
);
109 int machine_save(Machine
*m
) {
110 _cleanup_free_
char *temp_path
= NULL
;
111 _cleanup_fclose_
FILE *f
= NULL
;
122 r
= mkdir_safe_label("/run/systemd/machines", 0755, 0, 0, MKDIR_WARN_MODE
);
126 r
= fopen_temporary(m
->state_file
, &f
, &temp_path
);
130 (void) fchmod(fileno(f
), 0644);
133 "# This is private data. Do not parse.\n"
138 _cleanup_free_
char *escaped
= NULL
;
140 escaped
= cescape(m
->unit
);
146 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 */
150 fprintf(f
, "SCOPE_JOB=%s\n", m
->scope_job
);
153 _cleanup_free_
char *escaped
= NULL
;
155 escaped
= cescape(m
->service
);
160 fprintf(f
, "SERVICE=%s\n", escaped
);
163 if (m
->root_directory
) {
164 _cleanup_free_
char *escaped
= NULL
;
166 escaped
= cescape(m
->root_directory
);
171 fprintf(f
, "ROOT=%s\n", escaped
);
174 if (!sd_id128_is_null(m
->id
))
175 fprintf(f
, "ID=" SD_ID128_FORMAT_STR
"\n", SD_ID128_FORMAT_VAL(m
->id
));
178 fprintf(f
, "LEADER="PID_FMT
"\n", m
->leader
);
180 if (m
->class != _MACHINE_CLASS_INVALID
)
181 fprintf(f
, "CLASS=%s\n", machine_class_to_string(m
->class));
183 if (dual_timestamp_is_set(&m
->timestamp
))
185 "REALTIME="USEC_FMT
"\n"
186 "MONOTONIC="USEC_FMT
"\n",
187 m
->timestamp
.realtime
,
188 m
->timestamp
.monotonic
);
190 if (m
->n_netif
> 0) {
195 for (i
= 0; i
< m
->n_netif
; i
++) {
199 fprintf(f
, "%i", m
->netif
[i
]);
205 r
= fflush_and_check(f
);
209 if (rename(temp_path
, m
->state_file
) < 0) {
217 /* Create a symlink from the unit name to the machine
218 * name, so that we can quickly find the machine for
219 * each given unit. Ignore error. */
220 sl
= strjoina("/run/systemd/machines/unit:", m
->unit
);
221 (void) symlink(m
->name
, sl
);
227 (void) unlink(m
->state_file
);
230 (void) unlink(temp_path
);
232 return log_error_errno(r
, "Failed to save machine data %s: %m", m
->state_file
);
235 static void machine_unlink(Machine
*m
) {
241 sl
= strjoina("/run/systemd/machines/unit:", m
->unit
);
246 (void) unlink(m
->state_file
);
249 int machine_load(Machine
*m
) {
250 _cleanup_free_
char *realtime
= NULL
, *monotonic
= NULL
, *id
= NULL
, *leader
= NULL
, *class = NULL
, *netif
= NULL
;
258 r
= parse_env_file(NULL
, m
->state_file
,
260 "SCOPE_JOB", &m
->scope_job
,
261 "SERVICE", &m
->service
,
262 "ROOT", &m
->root_directory
,
266 "REALTIME", &realtime
,
267 "MONOTONIC", &monotonic
,
272 return log_error_errno(r
, "Failed to read %s: %m", m
->state_file
);
275 sd_id128_from_string(id
, &m
->id
);
278 parse_pid(leader
, &m
->leader
);
283 c
= machine_class_from_string(class);
289 (void) deserialize_usec(realtime
, &m
->timestamp
.realtime
);
291 (void) deserialize_usec(monotonic
, &m
->timestamp
.monotonic
);
294 _cleanup_free_
int *ni
= NULL
;
300 _cleanup_free_
char *word
= NULL
;
302 r
= extract_first_word(&p
, &word
, NULL
, 0);
308 log_warning_errno(r
, "Failed to parse NETIF: %s", netif
);
312 r
= parse_ifindex(word
);
316 if (!GREEDY_REALLOC(ni
, nr
+ 1))
322 free_and_replace(m
->netif
, ni
);
329 static int machine_start_scope(
331 sd_bus_message
*more_properties
,
332 sd_bus_error
*error
) {
334 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
335 _cleanup_free_
char *escaped
= NULL
, *unit
= NULL
;
336 const char *description
;
340 assert(machine
->leader
> 0);
341 assert(!machine
->unit
);
343 escaped
= unit_name_escape(machine
->name
);
347 unit
= strjoin("machine-", escaped
, ".scope");
351 r
= bus_message_new_method_call(
352 machine
->manager
->bus
,
355 "StartTransientUnit");
359 r
= sd_bus_message_append(m
, "ss", unit
, "fail");
363 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
367 r
= sd_bus_message_append(m
, "(sv)", "Slice", "s", SPECIAL_MACHINE_SLICE
);
371 description
= strjoina(machine
->class == MACHINE_VM
? "Virtual Machine " : "Container ", machine
->name
);
372 r
= sd_bus_message_append(m
, "(sv)", "Description", "s", description
);
376 r
= sd_bus_message_append(m
, "(sv)(sv)(sv)(sv)(sv)",
377 "PIDs", "au", 1, machine
->leader
,
379 "CollectMode", "s", "inactive-or-failed",
381 "TasksMax", "t", UINT64_C(16384));
385 if (more_properties
) {
386 r
= sd_bus_message_copy(m
, more_properties
, true);
391 r
= sd_bus_message_close_container(m
);
395 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
399 r
= sd_bus_call(NULL
, m
, 0, error
, &reply
);
403 machine
->unit
= TAKE_PTR(unit
);
404 machine
->referenced
= true;
407 r
= sd_bus_message_read(reply
, "o", &job
);
411 return free_and_strdup(&machine
->scope_job
, job
);
414 static int machine_ensure_scope(Machine
*m
, sd_bus_message
*properties
, sd_bus_error
*error
) {
418 assert(m
->class != MACHINE_HOST
);
421 r
= machine_start_scope(m
, properties
, error
);
423 return log_error_errno(r
, "Failed to start machine scope: %s", bus_error_message(error
, r
));
427 hashmap_put(m
->manager
->machine_units
, m
->unit
, m
);
432 int machine_start(Machine
*m
, sd_bus_message
*properties
, sd_bus_error
*error
) {
437 if (!IN_SET(m
->class, MACHINE_CONTAINER
, MACHINE_VM
))
443 r
= hashmap_put(m
->manager
->machine_leaders
, PID_TO_PTR(m
->leader
), m
);
448 r
= machine_ensure_scope(m
, properties
, error
);
453 "MESSAGE_ID=" SD_MESSAGE_MACHINE_START_STR
,
455 "LEADER="PID_FMT
, m
->leader
,
456 LOG_MESSAGE("New machine %s.", m
->name
));
458 if (!dual_timestamp_is_set(&m
->timestamp
))
459 dual_timestamp_get(&m
->timestamp
);
463 /* Save new machine data */
466 machine_send_signal(m
, true);
467 (void) manager_enqueue_nscd_cache_flush(m
->manager
);
472 int machine_stop(Machine
*m
) {
477 if (!IN_SET(m
->class, MACHINE_CONTAINER
, MACHINE_VM
))
481 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
484 r
= manager_stop_unit(m
->manager
, m
->unit
, &error
, &job
);
486 return log_error_errno(r
, "Failed to stop machine scope: %s", bus_error_message(&error
, r
));
488 free_and_replace(m
->scope_job
, job
);
494 (void) manager_enqueue_nscd_cache_flush(m
->manager
);
499 int machine_finalize(Machine
*m
) {
504 "MESSAGE_ID=" SD_MESSAGE_MACHINE_STOP_STR
,
506 "LEADER="PID_FMT
, m
->leader
,
507 LOG_MESSAGE("Machine %s terminated.", m
->name
));
509 m
->stopping
= true; /* The machine is supposed to be going away. Don't try to kill it. */
513 machine_add_to_gc_queue(m
);
516 machine_send_signal(m
, false);
523 bool machine_may_gc(Machine
*m
, bool drop_not_started
) {
526 if (m
->class == MACHINE_HOST
)
529 if (drop_not_started
&& !m
->started
)
532 if (m
->scope_job
&& manager_job_is_active(m
->manager
, m
->scope_job
))
535 if (m
->unit
&& manager_unit_is_active(m
->manager
, m
->unit
))
541 void machine_add_to_gc_queue(Machine
*m
) {
547 LIST_PREPEND(gc_queue
, m
->manager
->machine_gc_queue
, m
);
548 m
->in_gc_queue
= true;
551 MachineState
machine_get_state(Machine
*s
) {
554 if (s
->class == MACHINE_HOST
)
555 return MACHINE_RUNNING
;
558 return MACHINE_CLOSING
;
561 return MACHINE_OPENING
;
563 return MACHINE_RUNNING
;
566 int machine_kill(Machine
*m
, KillWho who
, int signo
) {
569 if (!IN_SET(m
->class, MACHINE_VM
, MACHINE_CONTAINER
))
575 if (who
== KILL_LEADER
) /* If we shall simply kill the leader, do so directly */
576 return RET_NERRNO(kill(m
->leader
, signo
));
578 /* Otherwise, make PID 1 do it for us, for the entire cgroup */
579 return manager_kill_unit(m
->manager
, m
->unit
, signo
, NULL
);
582 int machine_openpt(Machine
*m
, int flags
, char **ret_slave
) {
589 return openpt_allocate(flags
, ret_slave
);
591 case MACHINE_CONTAINER
:
595 return openpt_allocate_in_namespace(m
->leader
, flags
, ret_slave
);
602 int machine_open_terminal(Machine
*m
, const char *path
, int mode
) {
608 return open_terminal(path
, mode
);
610 case MACHINE_CONTAINER
:
614 return open_terminal_in_namespace(m
->leader
, path
, mode
);
621 void machine_release_unit(Machine
*m
) {
628 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
631 r
= manager_unref_unit(m
->manager
, m
->unit
, &error
);
633 log_warning_errno(r
, "Failed to drop reference to machine scope, ignoring: %s",
634 bus_error_message(&error
, r
));
636 m
->referenced
= false;
639 (void) hashmap_remove(m
->manager
->machine_units
, m
->unit
);
640 m
->unit
= mfree(m
->unit
);
643 int machine_get_uid_shift(Machine
*m
, uid_t
*ret
) {
644 char p
[STRLEN("/proc//uid_map") + DECIMAL_STR_MAX(pid_t
) + 1];
645 uid_t uid_base
, uid_shift
, uid_range
;
646 gid_t gid_base
, gid_shift
, gid_range
;
647 _cleanup_fclose_
FILE *f
= NULL
;
653 /* Return the base UID/GID of the specified machine. Note that this only works for containers with simple
654 * mappings. In most cases setups should be simple like this, and administrators should only care about the
655 * basic offset a container has relative to the host. This is what this function exposes.
657 * If we encounter any more complex mappings we politely refuse this with ENXIO. */
659 if (m
->class == MACHINE_HOST
) {
664 if (m
->class != MACHINE_CONTAINER
)
667 xsprintf(p
, "/proc/" PID_FMT
"/uid_map", m
->leader
);
670 if (errno
== ENOENT
) {
671 /* If the file doesn't exist, user namespacing is off in the kernel, return a zero mapping hence. */
679 /* Read the first line. There's at least one. */
681 k
= fscanf(f
, UID_FMT
" " UID_FMT
" " UID_FMT
"\n", &uid_base
, &uid_shift
, &uid_range
);
684 return errno_or_else(EIO
);
689 /* Not a mapping starting at 0? Then it's a complex mapping we can't expose here. */
692 /* Insist that at least the nobody user is mapped, everything else is weird, and hence complex, and we don't support it */
693 if (uid_range
< UID_NOBODY
)
696 /* If there's more than one line, then we don't support this mapping. */
697 r
= safe_fgetc(f
, NULL
);
700 if (r
!= 0) /* Insist on EOF */
705 xsprintf(p
, "/proc/" PID_FMT
"/gid_map", m
->leader
);
710 /* Read the first line. There's at least one. */
712 k
= fscanf(f
, GID_FMT
" " GID_FMT
" " GID_FMT
"\n", &gid_base
, &gid_shift
, &gid_range
);
715 return errno_or_else(EIO
);
720 /* If there's more than one line, then we don't support this file. */
721 r
= safe_fgetc(f
, NULL
);
724 if (r
!= 0) /* Insist on EOF */
727 /* If the UID and GID mapping doesn't match, we don't support this mapping. */
728 if (uid_base
!= (uid_t
) gid_base
)
730 if (uid_shift
!= (uid_t
) gid_shift
)
732 if (uid_range
!= (uid_t
) gid_range
)
739 static int machine_owns_uid_internal(
741 const char *map_file
, /* "uid_map" or "gid_map" */
743 uid_t
*ret_internal_uid
) {
745 _cleanup_fclose_
FILE *f
= NULL
;
748 /* This is a generic implementation for both uids and gids, under the assumptions they have the same types and semantics. */
749 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
753 /* Checks if the specified host UID is owned by the machine, and returns the UID it maps to
754 * internally in the machine */
756 if (machine
->class != MACHINE_CONTAINER
)
759 p
= procfs_file_alloca(machine
->leader
, map_file
);
762 log_debug_errno(errno
, "Failed to open %s, ignoring.", p
);
767 uid_t uid_base
, uid_shift
, uid_range
, converted
;
771 k
= fscanf(f
, UID_FMT
" " UID_FMT
" " UID_FMT
, &uid_base
, &uid_shift
, &uid_range
);
772 if (k
< 0 && feof(f
))
776 return errno_or_else(EIO
);
781 /* The private user namespace is disabled, ignoring. */
785 if (uid
< uid_shift
|| uid
>= uid_shift
+ uid_range
)
788 converted
= (uid
- uid_shift
+ uid_base
);
789 if (!uid_is_valid(converted
))
792 if (ret_internal_uid
)
793 *ret_internal_uid
= converted
;
799 if (ret_internal_uid
)
800 *ret_internal_uid
= UID_INVALID
;
805 int machine_owns_uid(Machine
*machine
, uid_t uid
, uid_t
*ret_internal_uid
) {
806 return machine_owns_uid_internal(machine
, "uid_map", uid
, ret_internal_uid
);
809 int machine_owns_gid(Machine
*machine
, gid_t gid
, gid_t
*ret_internal_gid
) {
810 return machine_owns_uid_internal(machine
, "gid_map", (uid_t
) gid
, (uid_t
*) ret_internal_gid
);
813 static int machine_translate_uid_internal(
815 const char *map_file
, /* "uid_map" or "gid_map" */
817 uid_t
*ret_host_uid
) {
819 _cleanup_fclose_
FILE *f
= NULL
;
822 /* This is a generic implementation for both uids and gids, under the assumptions they have the same types and semantics. */
823 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
826 assert(uid_is_valid(uid
));
828 if (machine
->class != MACHINE_CONTAINER
)
831 /* Translates a machine UID into a host UID */
833 p
= procfs_file_alloca(machine
->leader
, map_file
);
839 uid_t uid_base
, uid_shift
, uid_range
, converted
;
843 k
= fscanf(f
, UID_FMT
" " UID_FMT
" " UID_FMT
, &uid_base
, &uid_shift
, &uid_range
);
844 if (k
< 0 && feof(f
))
848 return errno_or_else(EIO
);
853 if (uid
< uid_base
|| uid
>= uid_base
+ uid_range
)
856 converted
= uid
- uid_base
+ uid_shift
;
857 if (!uid_is_valid(converted
))
861 *ret_host_uid
= converted
;
868 int machine_translate_uid(Machine
*machine
, gid_t uid
, gid_t
*ret_host_uid
) {
869 return machine_translate_uid_internal(machine
, "uid_map", uid
, ret_host_uid
);
872 int machine_translate_gid(Machine
*machine
, gid_t gid
, gid_t
*ret_host_gid
) {
873 return machine_translate_uid_internal(machine
, "gid_map", (uid_t
) gid
, (uid_t
*) ret_host_gid
);
876 static const char* const machine_class_table
[_MACHINE_CLASS_MAX
] = {
877 [MACHINE_CONTAINER
] = "container",
879 [MACHINE_HOST
] = "host",
882 DEFINE_STRING_TABLE_LOOKUP(machine_class
, MachineClass
);
884 static const char* const machine_state_table
[_MACHINE_STATE_MAX
] = {
885 [MACHINE_OPENING
] = "opening",
886 [MACHINE_RUNNING
] = "running",
887 [MACHINE_CLOSING
] = "closing"
890 DEFINE_STRING_TABLE_LOOKUP(machine_state
, MachineState
);
892 static const char* const kill_who_table
[_KILL_WHO_MAX
] = {
893 [KILL_LEADER
] = "leader",
897 DEFINE_STRING_TABLE_LOOKUP(kill_who
, KillWho
);