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"
36 DEFINE_TRIVIAL_CLEANUP_FUNC(Machine
*, machine_free
);
38 Machine
* machine_new(Manager
*manager
, MachineClass
class, const char *name
) {
39 _cleanup_(machine_freep
) Machine
*m
= NULL
;
42 assert(class < _MACHINE_CLASS_MAX
);
45 /* Passing class == _MACHINE_CLASS_INVALID here is fine. It
46 * means as much as "we don't know yet", and that we'll figure
47 * it out later when loading the state file. */
53 m
->name
= strdup(name
);
57 if (class != MACHINE_HOST
) {
58 m
->state_file
= path_join("/run/systemd/machines", m
->name
);
65 if (hashmap_put(manager
->machines
, m
->name
, m
) < 0)
73 Machine
* machine_free(Machine
*m
) {
78 operation_free(m
->operations
);
81 LIST_REMOVE(gc_queue
, m
->manager
->machine_gc_queue
, m
);
83 machine_release_unit(m
);
87 (void) hashmap_remove(m
->manager
->machines
, m
->name
);
89 if (m
->manager
->host_machine
== m
)
90 m
->manager
->host_machine
= NULL
;
93 (void) hashmap_remove_value(m
->manager
->machine_leaders
, PID_TO_PTR(m
->leader
), m
);
95 sd_bus_message_unref(m
->create_message
);
100 free(m
->root_directory
);
105 int machine_save(Machine
*m
) {
106 _cleanup_free_
char *temp_path
= NULL
;
107 _cleanup_fclose_
FILE *f
= NULL
;
118 r
= mkdir_safe_label("/run/systemd/machines", 0755, 0, 0, MKDIR_WARN_MODE
);
122 r
= fopen_temporary(m
->state_file
, &f
, &temp_path
);
126 (void) fchmod(fileno(f
), 0644);
129 "# This is private data. Do not parse.\n"
134 _cleanup_free_
char *escaped
= NULL
;
136 escaped
= cescape(m
->unit
);
142 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 */
146 fprintf(f
, "SCOPE_JOB=%s\n", m
->scope_job
);
149 _cleanup_free_
char *escaped
= NULL
;
151 escaped
= cescape(m
->service
);
156 fprintf(f
, "SERVICE=%s\n", escaped
);
159 if (m
->root_directory
) {
160 _cleanup_free_
char *escaped
= NULL
;
162 escaped
= cescape(m
->root_directory
);
167 fprintf(f
, "ROOT=%s\n", escaped
);
170 if (!sd_id128_is_null(m
->id
))
171 fprintf(f
, "ID=" SD_ID128_FORMAT_STR
"\n", SD_ID128_FORMAT_VAL(m
->id
));
174 fprintf(f
, "LEADER="PID_FMT
"\n", m
->leader
);
176 if (m
->class != _MACHINE_CLASS_INVALID
)
177 fprintf(f
, "CLASS=%s\n", machine_class_to_string(m
->class));
179 if (dual_timestamp_is_set(&m
->timestamp
))
181 "REALTIME="USEC_FMT
"\n"
182 "MONOTONIC="USEC_FMT
"\n",
183 m
->timestamp
.realtime
,
184 m
->timestamp
.monotonic
);
186 if (m
->n_netif
> 0) {
191 for (i
= 0; i
< m
->n_netif
; i
++) {
195 fprintf(f
, "%i", m
->netif
[i
]);
201 r
= fflush_and_check(f
);
205 if (rename(temp_path
, m
->state_file
) < 0) {
213 /* Create a symlink from the unit name to the machine
214 * name, so that we can quickly find the machine for
215 * each given unit. Ignore error. */
216 sl
= strjoina("/run/systemd/machines/unit:", m
->unit
);
217 (void) symlink(m
->name
, sl
);
223 (void) unlink(m
->state_file
);
226 (void) unlink(temp_path
);
228 return log_error_errno(r
, "Failed to save machine data %s: %m", m
->state_file
);
231 static void machine_unlink(Machine
*m
) {
237 sl
= strjoina("/run/systemd/machines/unit:", m
->unit
);
242 (void) unlink(m
->state_file
);
245 int machine_load(Machine
*m
) {
246 _cleanup_free_
char *realtime
= NULL
, *monotonic
= NULL
, *id
= NULL
, *leader
= NULL
, *class = NULL
, *netif
= NULL
;
254 r
= parse_env_file(NULL
, m
->state_file
,
256 "SCOPE_JOB", &m
->scope_job
,
257 "SERVICE", &m
->service
,
258 "ROOT", &m
->root_directory
,
262 "REALTIME", &realtime
,
263 "MONOTONIC", &monotonic
,
268 return log_error_errno(r
, "Failed to read %s: %m", m
->state_file
);
271 sd_id128_from_string(id
, &m
->id
);
274 parse_pid(leader
, &m
->leader
);
279 c
= machine_class_from_string(class);
285 (void) deserialize_usec(realtime
, &m
->timestamp
.realtime
);
287 (void) deserialize_usec(monotonic
, &m
->timestamp
.monotonic
);
290 _cleanup_free_
int *ni
= NULL
;
296 _cleanup_free_
char *word
= NULL
;
298 r
= extract_first_word(&p
, &word
, NULL
, 0);
304 log_warning_errno(r
, "Failed to parse NETIF: %s", netif
);
308 r
= parse_ifindex(word
);
312 if (!GREEDY_REALLOC(ni
, nr
+ 1))
318 free_and_replace(m
->netif
, ni
);
325 static int machine_start_scope(
327 sd_bus_message
*more_properties
,
328 sd_bus_error
*error
) {
330 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
331 _cleanup_free_
char *escaped
= NULL
, *unit
= NULL
;
332 const char *description
;
336 assert(machine
->leader
> 0);
337 assert(!machine
->unit
);
339 escaped
= unit_name_escape(machine
->name
);
343 unit
= strjoin("machine-", escaped
, ".scope");
347 r
= bus_message_new_method_call(
348 machine
->manager
->bus
,
351 "StartTransientUnit");
355 r
= sd_bus_message_append(m
, "ss", unit
, "fail");
359 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
363 r
= sd_bus_message_append(m
, "(sv)", "Slice", "s", SPECIAL_MACHINE_SLICE
);
367 description
= strjoina(machine
->class == MACHINE_VM
? "Virtual Machine " : "Container ", machine
->name
);
368 r
= sd_bus_message_append(m
, "(sv)", "Description", "s", description
);
372 r
= sd_bus_message_append(m
, "(sv)(sv)(sv)(sv)(sv)",
373 "PIDs", "au", 1, machine
->leader
,
375 "CollectMode", "s", "inactive-or-failed",
377 "TasksMax", "t", UINT64_C(16384));
381 if (more_properties
) {
382 r
= sd_bus_message_copy(m
, more_properties
, true);
387 r
= sd_bus_message_close_container(m
);
391 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
395 r
= sd_bus_call(NULL
, m
, 0, error
, &reply
);
399 machine
->unit
= TAKE_PTR(unit
);
400 machine
->referenced
= true;
403 r
= sd_bus_message_read(reply
, "o", &job
);
407 return free_and_strdup(&machine
->scope_job
, job
);
410 static int machine_ensure_scope(Machine
*m
, sd_bus_message
*properties
, sd_bus_error
*error
) {
414 assert(m
->class != MACHINE_HOST
);
417 r
= machine_start_scope(m
, properties
, error
);
419 return log_error_errno(r
, "Failed to start machine scope: %s", bus_error_message(error
, r
));
423 hashmap_put(m
->manager
->machine_units
, m
->unit
, m
);
428 int machine_start(Machine
*m
, sd_bus_message
*properties
, sd_bus_error
*error
) {
433 if (!IN_SET(m
->class, MACHINE_CONTAINER
, MACHINE_VM
))
439 r
= hashmap_put(m
->manager
->machine_leaders
, PID_TO_PTR(m
->leader
), m
);
444 r
= machine_ensure_scope(m
, properties
, error
);
449 "MESSAGE_ID=" SD_MESSAGE_MACHINE_START_STR
,
451 "LEADER="PID_FMT
, m
->leader
,
452 LOG_MESSAGE("New machine %s.", m
->name
));
454 if (!dual_timestamp_is_set(&m
->timestamp
))
455 dual_timestamp_get(&m
->timestamp
);
459 /* Save new machine data */
462 machine_send_signal(m
, true);
463 (void) manager_enqueue_nscd_cache_flush(m
->manager
);
468 int machine_stop(Machine
*m
) {
473 if (!IN_SET(m
->class, MACHINE_CONTAINER
, MACHINE_VM
))
477 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
480 r
= manager_stop_unit(m
->manager
, m
->unit
, &error
, &job
);
482 return log_error_errno(r
, "Failed to stop machine scope: %s", bus_error_message(&error
, r
));
484 free_and_replace(m
->scope_job
, job
);
490 (void) manager_enqueue_nscd_cache_flush(m
->manager
);
495 int machine_finalize(Machine
*m
) {
500 "MESSAGE_ID=" SD_MESSAGE_MACHINE_STOP_STR
,
502 "LEADER="PID_FMT
, m
->leader
,
503 LOG_MESSAGE("Machine %s terminated.", m
->name
));
505 m
->stopping
= true; /* The machine is supposed to be going away. Don't try to kill it. */
509 machine_add_to_gc_queue(m
);
512 machine_send_signal(m
, false);
519 bool machine_may_gc(Machine
*m
, bool drop_not_started
) {
522 if (m
->class == MACHINE_HOST
)
525 if (drop_not_started
&& !m
->started
)
528 if (m
->scope_job
&& manager_job_is_active(m
->manager
, m
->scope_job
))
531 if (m
->unit
&& manager_unit_is_active(m
->manager
, m
->unit
))
537 void machine_add_to_gc_queue(Machine
*m
) {
543 LIST_PREPEND(gc_queue
, m
->manager
->machine_gc_queue
, m
);
544 m
->in_gc_queue
= true;
547 MachineState
machine_get_state(Machine
*s
) {
550 if (s
->class == MACHINE_HOST
)
551 return MACHINE_RUNNING
;
554 return MACHINE_CLOSING
;
557 return MACHINE_OPENING
;
559 return MACHINE_RUNNING
;
562 int machine_kill(Machine
*m
, KillWho who
, int signo
) {
565 if (!IN_SET(m
->class, MACHINE_VM
, MACHINE_CONTAINER
))
571 if (who
== KILL_LEADER
) /* If we shall simply kill the leader, do so directly */
572 return RET_NERRNO(kill(m
->leader
, signo
));
574 /* Otherwise, make PID 1 do it for us, for the entire cgroup */
575 return manager_kill_unit(m
->manager
, m
->unit
, signo
, NULL
);
578 int machine_openpt(Machine
*m
, int flags
, char **ret_slave
) {
585 return openpt_allocate(flags
, ret_slave
);
587 case MACHINE_CONTAINER
:
591 return openpt_allocate_in_namespace(m
->leader
, flags
, ret_slave
);
598 int machine_open_terminal(Machine
*m
, const char *path
, int mode
) {
604 return open_terminal(path
, mode
);
606 case MACHINE_CONTAINER
:
610 return open_terminal_in_namespace(m
->leader
, path
, mode
);
617 void machine_release_unit(Machine
*m
) {
624 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
627 r
= manager_unref_unit(m
->manager
, m
->unit
, &error
);
629 log_warning_errno(r
, "Failed to drop reference to machine scope, ignoring: %s",
630 bus_error_message(&error
, r
));
632 m
->referenced
= false;
635 (void) hashmap_remove(m
->manager
->machine_units
, m
->unit
);
636 m
->unit
= mfree(m
->unit
);
639 int machine_get_uid_shift(Machine
*m
, uid_t
*ret
) {
640 char p
[STRLEN("/proc//uid_map") + DECIMAL_STR_MAX(pid_t
) + 1];
641 uid_t uid_base
, uid_shift
, uid_range
;
642 gid_t gid_base
, gid_shift
, gid_range
;
643 _cleanup_fclose_
FILE *f
= NULL
;
649 /* Return the base UID/GID of the specified machine. Note that this only works for containers with simple
650 * mappings. In most cases setups should be simple like this, and administrators should only care about the
651 * basic offset a container has relative to the host. This is what this function exposes.
653 * If we encounter any more complex mappings we politely refuse this with ENXIO. */
655 if (m
->class == MACHINE_HOST
) {
660 if (m
->class != MACHINE_CONTAINER
)
663 xsprintf(p
, "/proc/" PID_FMT
"/uid_map", m
->leader
);
666 if (errno
== ENOENT
) {
667 /* If the file doesn't exist, user namespacing is off in the kernel, return a zero mapping hence. */
675 /* Read the first line. There's at least one. */
677 k
= fscanf(f
, UID_FMT
" " UID_FMT
" " UID_FMT
"\n", &uid_base
, &uid_shift
, &uid_range
);
680 return errno_or_else(EIO
);
685 /* Not a mapping starting at 0? Then it's a complex mapping we can't expose here. */
688 /* Insist that at least the nobody user is mapped, everything else is weird, and hence complex, and we don't support it */
689 if (uid_range
< UID_NOBODY
)
692 /* If there's more than one line, then we don't support this mapping. */
693 r
= safe_fgetc(f
, NULL
);
696 if (r
!= 0) /* Insist on EOF */
701 xsprintf(p
, "/proc/" PID_FMT
"/gid_map", m
->leader
);
706 /* Read the first line. There's at least one. */
708 k
= fscanf(f
, GID_FMT
" " GID_FMT
" " GID_FMT
"\n", &gid_base
, &gid_shift
, &gid_range
);
711 return errno_or_else(EIO
);
716 /* If there's more than one line, then we don't support this file. */
717 r
= safe_fgetc(f
, NULL
);
720 if (r
!= 0) /* Insist on EOF */
723 /* If the UID and GID mapping doesn't match, we don't support this mapping. */
724 if (uid_base
!= (uid_t
) gid_base
)
726 if (uid_shift
!= (uid_t
) gid_shift
)
728 if (uid_range
!= (uid_t
) gid_range
)
735 static int machine_owns_uid_internal(
737 const char *map_file
, /* "uid_map" or "gid_map" */
739 uid_t
*ret_internal_uid
) {
741 _cleanup_fclose_
FILE *f
= NULL
;
744 /* This is a generic implementation for both uids and gids, under the assumptions they have the same types and semantics. */
745 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
749 /* Checks if the specified host UID is owned by the machine, and returns the UID it maps to
750 * internally in the machine */
752 if (machine
->class != MACHINE_CONTAINER
)
755 p
= procfs_file_alloca(machine
->leader
, map_file
);
758 log_debug_errno(errno
, "Failed to open %s, ignoring.", p
);
763 uid_t uid_base
, uid_shift
, uid_range
, converted
;
767 k
= fscanf(f
, UID_FMT
" " UID_FMT
" " UID_FMT
, &uid_base
, &uid_shift
, &uid_range
);
768 if (k
< 0 && feof(f
))
772 return errno_or_else(EIO
);
777 /* The private user namespace is disabled, ignoring. */
781 if (uid
< uid_shift
|| uid
>= uid_shift
+ uid_range
)
784 converted
= (uid
- uid_shift
+ uid_base
);
785 if (!uid_is_valid(converted
))
788 if (ret_internal_uid
)
789 *ret_internal_uid
= converted
;
795 if (ret_internal_uid
)
796 *ret_internal_uid
= UID_INVALID
;
801 int machine_owns_uid(Machine
*machine
, uid_t uid
, uid_t
*ret_internal_uid
) {
802 return machine_owns_uid_internal(machine
, "uid_map", uid
, ret_internal_uid
);
805 int machine_owns_gid(Machine
*machine
, gid_t gid
, gid_t
*ret_internal_gid
) {
806 return machine_owns_uid_internal(machine
, "gid_map", (uid_t
) gid
, (uid_t
*) ret_internal_gid
);
809 static int machine_translate_uid_internal(
811 const char *map_file
, /* "uid_map" or "gid_map" */
813 uid_t
*ret_host_uid
) {
815 _cleanup_fclose_
FILE *f
= NULL
;
818 /* This is a generic implementation for both uids and gids, under the assumptions they have the same types and semantics. */
819 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
822 assert(uid_is_valid(uid
));
824 if (machine
->class != MACHINE_CONTAINER
)
827 /* Translates a machine UID into a host UID */
829 p
= procfs_file_alloca(machine
->leader
, map_file
);
835 uid_t uid_base
, uid_shift
, uid_range
, converted
;
839 k
= fscanf(f
, UID_FMT
" " UID_FMT
" " UID_FMT
, &uid_base
, &uid_shift
, &uid_range
);
840 if (k
< 0 && feof(f
))
844 return errno_or_else(EIO
);
849 if (uid
< uid_base
|| uid
>= uid_base
+ uid_range
)
852 converted
= uid
- uid_base
+ uid_shift
;
853 if (!uid_is_valid(converted
))
857 *ret_host_uid
= converted
;
864 int machine_translate_uid(Machine
*machine
, gid_t uid
, gid_t
*ret_host_uid
) {
865 return machine_translate_uid_internal(machine
, "uid_map", uid
, ret_host_uid
);
868 int machine_translate_gid(Machine
*machine
, gid_t gid
, gid_t
*ret_host_gid
) {
869 return machine_translate_uid_internal(machine
, "gid_map", (uid_t
) gid
, (uid_t
*) ret_host_gid
);
872 static const char* const machine_class_table
[_MACHINE_CLASS_MAX
] = {
873 [MACHINE_CONTAINER
] = "container",
875 [MACHINE_HOST
] = "host",
878 DEFINE_STRING_TABLE_LOOKUP(machine_class
, MachineClass
);
880 static const char* const machine_state_table
[_MACHINE_STATE_MAX
] = {
881 [MACHINE_OPENING
] = "opening",
882 [MACHINE_RUNNING
] = "running",
883 [MACHINE_CLOSING
] = "closing"
886 DEFINE_STRING_TABLE_LOOKUP(machine_state
, MachineState
);
888 static const char* const kill_who_table
[_KILL_WHO_MAX
] = {
889 [KILL_LEADER
] = "leader",
893 DEFINE_STRING_TABLE_LOOKUP(kill_who
, KillWho
);