]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/portable/portable.c
Merge pull request #18481 from keszybz/rpm-restart-post-trans
[thirdparty/systemd.git] / src / portable / portable.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
61d0578b 2
e08f94ac
LP
3#include <linux/loop.h>
4
61d0578b
LP
5#include "bus-common-errors.h"
6#include "bus-error.h"
7#include "conf-files.h"
8#include "copy.h"
9#include "def.h"
10#include "dirent-util.h"
57f1b61b 11#include "discover-image.h"
61d0578b
LP
12#include "dissect-image.h"
13#include "fd-util.h"
14#include "fileio.h"
15#include "fs-util.h"
5cfa33e0 16#include "install.h"
61d0578b
LP
17#include "io-util.h"
18#include "locale-util.h"
19#include "loop-util.h"
61d0578b 20#include "mkdir.h"
d8b4d14d 21#include "nulstr-util.h"
61d0578b
LP
22#include "os-util.h"
23#include "path-lookup.h"
24#include "portable.h"
25#include "process-util.h"
26#include "set.h"
27#include "signal-util.h"
28#include "socket-util.h"
760877e9 29#include "sort-util.h"
61d0578b
LP
30#include "string-table.h"
31#include "strv.h"
e4de7287 32#include "tmpfile-util.h"
61d0578b
LP
33#include "user-util.h"
34
35static const char profile_dirs[] = CONF_PATHS_NULSTR("systemd/portable/profile");
36
37/* Markers used in the first line of our 20-portable.conf unit file drop-in to determine, that a) the unit file was
38 * dropped there by the portable service logic and b) for which image it was dropped there. */
39#define PORTABLE_DROPIN_MARKER_BEGIN "# Drop-in created for image '"
40#define PORTABLE_DROPIN_MARKER_END "', do not edit."
41
42static bool prefix_match(const char *unit, const char *prefix) {
43 const char *p;
44
45 p = startswith(unit, prefix);
46 if (!p)
47 return false;
48
49 /* Only respect prefixes followed by dash or dot or when there's a complete match */
50 return IN_SET(*p, '-', '.', '@', 0);
51}
52
53static bool unit_match(const char *unit, char **matches) {
54 const char *dot;
55 char **i;
56
57 dot = strrchr(unit, '.');
58 if (!dot)
59 return false;
60
61 if (!STR_IN_SET(dot, ".service", ".socket", ".target", ".timer", ".path"))
62 return false;
63
64 /* Empty match expression means: everything */
65 if (strv_isempty(matches))
66 return true;
67
68 /* Otherwise, at least one needs to match */
69 STRV_FOREACH(i, matches)
70 if (prefix_match(unit, *i))
71 return true;
72
73 return false;
74}
75
76static PortableMetadata *portable_metadata_new(const char *name, int fd) {
77 PortableMetadata *m;
78
79 m = malloc0(offsetof(PortableMetadata, name) + strlen(name) + 1);
80 if (!m)
81 return NULL;
82
83 strcpy(m->name, name);
84 m->fd = fd;
85
86 return m;
87}
88
89PortableMetadata *portable_metadata_unref(PortableMetadata *i) {
90 if (!i)
91 return NULL;
92
93 safe_close(i->fd);
94 free(i->source);
95
96 return mfree(i);
97}
98
61d0578b
LP
99static int compare_metadata(PortableMetadata *const *x, PortableMetadata *const *y) {
100 return strcmp((*x)->name, (*y)->name);
101}
102
103int portable_metadata_hashmap_to_sorted_array(Hashmap *unit_files, PortableMetadata ***ret) {
104
105 _cleanup_free_ PortableMetadata **sorted = NULL;
61d0578b
LP
106 PortableMetadata *item;
107 size_t k = 0;
108
109 sorted = new(PortableMetadata*, hashmap_size(unit_files));
110 if (!sorted)
111 return -ENOMEM;
112
90e74a66 113 HASHMAP_FOREACH(item, unit_files)
61d0578b
LP
114 sorted[k++] = item;
115
116 assert(k == hashmap_size(unit_files));
117
118 typesafe_qsort(sorted, k, compare_metadata);
119
120 *ret = TAKE_PTR(sorted);
121 return 0;
122}
123
124static int send_item(
125 int socket_fd,
126 const char *name,
127 int fd) {
128
fb29cdbe 129 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control = {};
61d0578b
LP
130 struct iovec iovec;
131 struct msghdr mh = {
132 .msg_control = &control,
133 .msg_controllen = sizeof(control),
134 .msg_iov = &iovec,
135 .msg_iovlen = 1,
136 };
137 struct cmsghdr *cmsg;
138 _cleanup_close_ int data_fd = -1;
139
140 assert(socket_fd >= 0);
141 assert(name);
142 assert(fd >= 0);
143
144 data_fd = fd_duplicate_data_fd(fd);
145 if (data_fd < 0)
146 return data_fd;
147
148 cmsg = CMSG_FIRSTHDR(&mh);
149 cmsg->cmsg_level = SOL_SOCKET;
150 cmsg->cmsg_type = SCM_RIGHTS;
151 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
152 memcpy(CMSG_DATA(cmsg), &data_fd, sizeof(int));
153
61d0578b
LP
154 iovec = IOVEC_MAKE_STRING(name);
155
156 if (sendmsg(socket_fd, &mh, MSG_NOSIGNAL) < 0)
157 return -errno;
158
159 return 0;
160}
161
162static int recv_item(
163 int socket_fd,
164 char **ret_name,
165 int *ret_fd) {
166
fb29cdbe 167 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control;
61d0578b
LP
168 char buffer[PATH_MAX+2];
169 struct iovec iov = IOVEC_INIT(buffer, sizeof(buffer)-1);
170 struct msghdr mh = {
171 .msg_control = &control,
172 .msg_controllen = sizeof(control),
173 .msg_iov = &iov,
174 .msg_iovlen = 1,
175 };
176 struct cmsghdr *cmsg;
177 _cleanup_close_ int found_fd = -1;
178 char *copy;
179 ssize_t n;
180
181 assert(socket_fd >= 0);
182 assert(ret_name);
183 assert(ret_fd);
184
3691bcf3 185 n = recvmsg_safe(socket_fd, &mh, MSG_CMSG_CLOEXEC);
61d0578b 186 if (n < 0)
3691bcf3 187 return (int) n;
61d0578b
LP
188
189 CMSG_FOREACH(cmsg, &mh) {
190 if (cmsg->cmsg_level == SOL_SOCKET &&
191 cmsg->cmsg_type == SCM_RIGHTS) {
192
193 if (cmsg->cmsg_len == CMSG_LEN(sizeof(int))) {
194 assert(found_fd < 0);
195 found_fd = *(int*) CMSG_DATA(cmsg);
196 break;
197 }
198
199 cmsg_close_all(&mh);
200 return -EIO;
201 }
202 }
203
204 buffer[n] = 0;
205
206 copy = strdup(buffer);
207 if (!copy)
208 return -ENOMEM;
209
210 *ret_name = copy;
211 *ret_fd = TAKE_FD(found_fd);
212
213 return 0;
214}
215
67818055
YW
216DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(portable_metadata_hash_ops, char, string_hash_func, string_compare_func,
217 PortableMetadata, portable_metadata_unref);
218
61d0578b
LP
219static int extract_now(
220 const char *where,
221 char **matches,
222 int socket_fd,
223 PortableMetadata **ret_os_release,
224 Hashmap **ret_unit_files) {
225
67818055 226 _cleanup_hashmap_free_ Hashmap *unit_files = NULL;
61d0578b
LP
227 _cleanup_(portable_metadata_unrefp) PortableMetadata *os_release = NULL;
228 _cleanup_(lookup_paths_free) LookupPaths paths = {};
229 _cleanup_close_ int os_release_fd = -1;
230 _cleanup_free_ char *os_release_path = NULL;
231 char **i;
232 int r;
233
234 /* Extracts the metadata from a directory tree 'where'. Extracts two kinds of information: the /etc/os-release
235 * data, and all unit files matching the specified expression. Note that this function is called in two very
236 * different but also similar contexts. When the tool gets invoked on a directory tree, we'll process it
237 * directly, and in-process, and thus can return the requested data directly, via 'ret_os_release' and
238 * 'ret_unit_files'. However, if the tool is invoked on a raw disk image — which needs to be mounted first — we
239 * are invoked in a child process with private mounts and then need to send the collected data to our
240 * parent. To handle both cases in one call this function also gets a 'socket_fd' parameter, which when >= 0 is
241 * used to send the data to the parent. */
242
243 assert(where);
244
245 /* First, find /etc/os-release and send it upstream (or just save it). */
246 r = open_os_release(where, &os_release_path, &os_release_fd);
247 if (r < 0)
248 log_debug_errno(r, "Couldn't acquire os-release file, ignoring: %m");
249 else {
250 if (socket_fd >= 0) {
251 r = send_item(socket_fd, "/etc/os-release", os_release_fd);
252 if (r < 0)
253 return log_debug_errno(r, "Failed to send os-release file: %m");
254 }
255
256 if (ret_os_release) {
257 os_release = portable_metadata_new("/etc/os-release", os_release_fd);
258 if (!os_release)
259 return -ENOMEM;
260
261 os_release_fd = -1;
262 os_release->source = TAKE_PTR(os_release_path);
263 }
264 }
265
266 /* Then, send unit file data to the parent (or/and add it to the hashmap). For that we use our usual unit
267 * discovery logic. Note that we force looking inside of /lib/systemd/system/ for units too, as we mightbe
268 * compiled for a split-usr system but the image might be a legacy-usr one. */
269 r = lookup_paths_init(&paths, UNIT_FILE_SYSTEM, LOOKUP_PATHS_SPLIT_USR, where);
270 if (r < 0)
271 return log_debug_errno(r, "Failed to acquire lookup paths: %m");
272
67818055 273 unit_files = hashmap_new(&portable_metadata_hash_ops);
61d0578b
LP
274 if (!unit_files)
275 return -ENOMEM;
276
277 STRV_FOREACH(i, paths.search_path) {
278 _cleanup_free_ char *resolved = NULL;
279 _cleanup_closedir_ DIR *d = NULL;
280 struct dirent *de;
281
282 r = chase_symlinks_and_opendir(*i, where, 0, &resolved, &d);
283 if (r < 0) {
284 log_debug_errno(r, "Failed to open unit path '%s', ignoring: %m", *i);
285 continue;
286 }
287
288 FOREACH_DIRENT(de, d, return log_debug_errno(errno, "Failed to read directory: %m")) {
289 _cleanup_(portable_metadata_unrefp) PortableMetadata *m = NULL;
290 _cleanup_close_ int fd = -1;
291
292 if (!unit_name_is_valid(de->d_name, UNIT_NAME_ANY))
293 continue;
294
295 if (!unit_match(de->d_name, matches))
296 continue;
297
298 /* Filter out duplicates */
299 if (hashmap_get(unit_files, de->d_name))
300 continue;
301
302 dirent_ensure_type(d, de);
303 if (!IN_SET(de->d_type, DT_LNK, DT_REG))
304 continue;
305
306 fd = openat(dirfd(d), de->d_name, O_CLOEXEC|O_RDONLY);
307 if (fd < 0) {
308 log_debug_errno(errno, "Failed to open unit file '%s', ignoring: %m", de->d_name);
309 continue;
310 }
311
312 if (socket_fd >= 0) {
313 r = send_item(socket_fd, de->d_name, fd);
314 if (r < 0)
315 return log_debug_errno(r, "Failed to send unit metadata to parent: %m");
316 }
317
318 m = portable_metadata_new(de->d_name, fd);
319 if (!m)
320 return -ENOMEM;
321 fd = -1;
322
657ee2d8 323 m->source = path_join(resolved, de->d_name);
61d0578b
LP
324 if (!m->source)
325 return -ENOMEM;
326
327 r = hashmap_put(unit_files, m->name, m);
328 if (r < 0)
329 return log_debug_errno(r, "Failed to add unit to hashmap: %m");
330 m = NULL;
331 }
332 }
333
334 if (ret_os_release)
335 *ret_os_release = TAKE_PTR(os_release);
336 if (ret_unit_files)
337 *ret_unit_files = TAKE_PTR(unit_files);
338
339 return 0;
340}
341
342static int portable_extract_by_path(
343 const char *path,
344 char **matches,
345 PortableMetadata **ret_os_release,
346 Hashmap **ret_unit_files,
347 sd_bus_error *error) {
348
67818055 349 _cleanup_hashmap_free_ Hashmap *unit_files = NULL;
61d0578b
LP
350 _cleanup_(portable_metadata_unrefp) PortableMetadata* os_release = NULL;
351 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
352 int r;
353
354 assert(path);
355
e08f94ac 356 r = loop_device_make_by_path(path, O_RDONLY, LO_FLAGS_PARTSCAN, &d);
61d0578b
LP
357 if (r == -EISDIR) {
358 /* We can't turn this into a loop-back block device, and this returns EISDIR? Then this is a directory
359 * tree and not a raw device. It's easy then. */
360
361 r = extract_now(path, matches, -1, &os_release, &unit_files);
362 if (r < 0)
363 return r;
364
365 } else if (r < 0)
366 return log_debug_errno(r, "Failed to set up loopback device: %m");
367 else {
368 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
369 _cleanup_(rmdir_and_freep) char *tmpdir = NULL;
370 _cleanup_(close_pairp) int seq[2] = { -1, -1 };
371 _cleanup_(sigkill_waitp) pid_t child = 0;
372
373 /* We now have a loopback block device, let's fork off a child in its own mount namespace, mount it
374 * there, and extract the metadata we need. The metadata is sent from the child back to us. */
375
376 BLOCK_SIGNALS(SIGCHLD);
377
378 r = mkdtemp_malloc("/tmp/inspect-XXXXXX", &tmpdir);
379 if (r < 0)
380 return log_debug_errno(r, "Failed to create temporary directory: %m");
381
89e62e0b 382 r = dissect_image(d->fd, NULL, NULL, DISSECT_IMAGE_READ_ONLY|DISSECT_IMAGE_REQUIRE_ROOT|DISSECT_IMAGE_DISCARD_ON_LOOP|DISSECT_IMAGE_RELAX_VAR_CHECK, &m);
61d0578b
LP
383 if (r == -ENOPKG)
384 sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Couldn't identify a suitable partition table or file system in '%s'.", path);
385 else if (r == -EADDRNOTAVAIL)
386 sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "No root partition for specified root hash found in '%s'.", path);
387 else if (r == -ENOTUNIQ)
388 sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Multiple suitable root partitions found in image '%s'.", path);
389 else if (r == -ENXIO)
390 sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "No suitable root partition found in image '%s'.", path);
391 else if (r == -EPROTONOSUPPORT)
392 sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", path);
393 if (r < 0)
394 return r;
395
396 if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, seq) < 0)
397 return log_debug_errno(errno, "Failed to allocated SOCK_SEQPACKET socket: %m");
398
399 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE|FORK_LOG, &child);
400 if (r < 0)
401 return r;
402 if (r == 0) {
403 seq[0] = safe_close(seq[0]);
404
405 r = dissected_image_mount(m, tmpdir, UID_INVALID, DISSECT_IMAGE_READ_ONLY|DISSECT_IMAGE_VALIDATE_OS);
406 if (r < 0) {
407 log_debug_errno(r, "Failed to mount dissected image: %m");
408 goto child_finish;
409 }
410
411 r = extract_now(tmpdir, matches, seq[1], NULL, NULL);
412
413 child_finish:
414 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
415 }
416
417 seq[1] = safe_close(seq[1]);
418
67818055 419 unit_files = hashmap_new(&portable_metadata_hash_ops);
61d0578b
LP
420 if (!unit_files)
421 return -ENOMEM;
422
423 for (;;) {
424 _cleanup_(portable_metadata_unrefp) PortableMetadata *add = NULL;
425 _cleanup_free_ char *name = NULL;
426 _cleanup_close_ int fd = -1;
427
428 r = recv_item(seq[0], &name, &fd);
429 if (r < 0)
430 return log_debug_errno(r, "Failed to receive item: %m");
431
5238e957 432 /* We can't really distinguish a zero-length datagram without any fds from EOF (both are signalled the
61d0578b
LP
433 * same way by recvmsg()). Hence, accept either as end notification. */
434 if (isempty(name) && fd < 0)
435 break;
436
d7a0f1f4
FS
437 if (isempty(name) || fd < 0)
438 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
439 "Invalid item sent from child.");
61d0578b
LP
440
441 add = portable_metadata_new(name, fd);
442 if (!add)
443 return -ENOMEM;
444 fd = -1;
445
446 /* Note that we do not initialize 'add->source' here, as the source path is not usable here as
447 * it refers to a path only valid in the short-living namespaced child process we forked
448 * here. */
449
450 if (PORTABLE_METADATA_IS_UNIT(add)) {
451 r = hashmap_put(unit_files, add->name, add);
452 if (r < 0)
453 return log_debug_errno(r, "Failed to add item to unit file list: %m");
454
455 add = NULL;
456
457 } else if (PORTABLE_METADATA_IS_OS_RELEASE(add)) {
458
459 assert(!os_release);
460 os_release = TAKE_PTR(add);
461 } else
462 assert_not_reached("Unexpected metadata item from child.");
463 }
464
465 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
466 if (r < 0)
467 return r;
468 child = 0;
469 }
470
471 if (!os_release)
472 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Image '%s' lacks os-release data, refusing.", path);
473
474 if (hashmap_isempty(unit_files))
475 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Couldn't find any matching unit files in image '%s', refusing.", path);
476
477 if (ret_unit_files)
478 *ret_unit_files = TAKE_PTR(unit_files);
479
480 if (ret_os_release)
481 *ret_os_release = TAKE_PTR(os_release);
482
483 return 0;
484}
485
486int portable_extract(
487 const char *name_or_path,
488 char **matches,
489 PortableMetadata **ret_os_release,
490 Hashmap **ret_unit_files,
491 sd_bus_error *error) {
492
493 _cleanup_(image_unrefp) Image *image = NULL;
494 int r;
495
496 assert(name_or_path);
497
d577d4a4 498 r = image_find_harder(IMAGE_PORTABLE, name_or_path, NULL, &image);
61d0578b
LP
499 if (r < 0)
500 return r;
501
502 return portable_extract_by_path(image->path, matches, ret_os_release, ret_unit_files, error);
503}
504
505static int unit_file_is_active(
506 sd_bus *bus,
507 const char *name,
508 sd_bus_error *error) {
509
510 static const char *const active_states[] = {
511 "activating",
512 "active",
513 "reloading",
514 "deactivating",
515 NULL,
516 };
517 int r;
518
519 if (!bus)
520 return false;
521
522 /* If we are looking at a plain or instance things are easy, we can just query the state */
523 if (unit_name_is_valid(name, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
524 _cleanup_free_ char *path = NULL, *buf = NULL;
525
526 path = unit_dbus_path_from_name(name);
527 if (!path)
528 return -ENOMEM;
529
530 r = sd_bus_get_property_string(
531 bus,
532 "org.freedesktop.systemd1",
533 path,
534 "org.freedesktop.systemd1.Unit",
535 "ActiveState",
536 error,
537 &buf);
538 if (r < 0)
539 return log_debug_errno(r, "Failed to retrieve unit state: %s", bus_error_message(error, r));
540
541 return strv_contains((char**) active_states, buf);
542 }
543
544 /* Otherwise we need to enumerate. But let's build the most restricted query we can */
545 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
546 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
547 const char *at, *prefix, *joined;
548
549 r = sd_bus_message_new_method_call(
550 bus,
551 &m,
552 "org.freedesktop.systemd1",
553 "/org/freedesktop/systemd1",
554 "org.freedesktop.systemd1.Manager",
555 "ListUnitsByPatterns");
556 if (r < 0)
557 return r;
558
559 r = sd_bus_message_append_strv(m, (char**) active_states);
560 if (r < 0)
561 return r;
562
563 at = strchr(name, '@');
564 assert(at);
565
566 prefix = strndupa(name, at + 1 - name);
567 joined = strjoina(prefix, "*", at + 1);
568
569 r = sd_bus_message_append_strv(m, STRV_MAKE(joined));
570 if (r < 0)
571 return r;
572
573 r = sd_bus_call(bus, m, 0, error, &reply);
574 if (r < 0)
575 return log_debug_errno(r, "Failed to list units: %s", bus_error_message(error, r));
576
577 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)");
578 if (r < 0)
579 return r;
580
581 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_STRUCT, "ssssssouso");
582 if (r < 0)
583 return r;
584
585 return r > 0;
586 }
587
588 return -EINVAL;
589}
590
591static int portable_changes_add(
592 PortableChange **changes,
593 size_t *n_changes,
594 PortableChangeType type,
595 const char *path,
596 const char *source) {
597
598 _cleanup_free_ char *p = NULL, *s = NULL;
599 PortableChange *c;
600
601 assert(path);
602 assert(!changes == !n_changes);
603
604 if (!changes)
605 return 0;
606
607 c = reallocarray(*changes, *n_changes + 1, sizeof(PortableChange));
608 if (!c)
609 return -ENOMEM;
610 *changes = c;
611
612 p = strdup(path);
613 if (!p)
614 return -ENOMEM;
615
858d36c1 616 path_simplify(p, false);
61d0578b
LP
617
618 if (source) {
619 s = strdup(source);
620 if (!s)
621 return -ENOMEM;
622
858d36c1 623 path_simplify(s, false);
61d0578b
LP
624 }
625
626 c[(*n_changes)++] = (PortableChange) {
627 .type = type,
628 .path = TAKE_PTR(p),
629 .source = TAKE_PTR(s),
630 };
631
632 return 0;
633}
634
635static int portable_changes_add_with_prefix(
636 PortableChange **changes,
637 size_t *n_changes,
638 PortableChangeType type,
639 const char *prefix,
640 const char *path,
641 const char *source) {
642
643 assert(path);
644 assert(!changes == !n_changes);
645
646 if (!changes)
647 return 0;
648
649 if (prefix) {
270384b2 650 path = prefix_roota(prefix, path);
61d0578b
LP
651
652 if (source)
270384b2 653 source = prefix_roota(prefix, source);
61d0578b
LP
654 }
655
656 return portable_changes_add(changes, n_changes, type, path, source);
657}
658
659void portable_changes_free(PortableChange *changes, size_t n_changes) {
660 size_t i;
661
662 assert(changes || n_changes == 0);
663
664 for (i = 0; i < n_changes; i++) {
665 free(changes[i].path);
666 free(changes[i].source);
667 }
668
669 free(changes);
670}
671
672static int install_chroot_dropin(
673 const char *image_path,
674 ImageType type,
675 const PortableMetadata *m,
676 const char *dropin_dir,
677 char **ret_dropin,
678 PortableChange **changes,
679 size_t *n_changes) {
680
681 _cleanup_free_ char *text = NULL, *dropin = NULL;
682 int r;
683
684 assert(image_path);
685 assert(m);
686 assert(dropin_dir);
687
657ee2d8 688 dropin = path_join(dropin_dir, "20-portable.conf");
61d0578b
LP
689 if (!dropin)
690 return -ENOMEM;
691
692 text = strjoin(PORTABLE_DROPIN_MARKER_BEGIN, image_path, PORTABLE_DROPIN_MARKER_END "\n");
693 if (!text)
694 return -ENOMEM;
695
62b0ee9e
LB
696 if (endswith(m->name, ".service")) {
697 const char *os_release_source;
698
699 if (access("/etc/os-release", F_OK) < 0) {
700 if (errno != ENOENT)
701 return log_debug_errno(errno, "Failed to check if /etc/os-release exists: %m");
702
703 os_release_source = "/usr/lib/os-release";
704 } else
705 os_release_source = "/etc/os-release";
706
61d0578b
LP
707 if (!strextend(&text,
708 "\n"
709 "[Service]\n",
710 IN_SET(type, IMAGE_DIRECTORY, IMAGE_SUBVOLUME) ? "RootDirectory=" : "RootImage=", image_path, "\n"
711 "Environment=PORTABLE=", basename(image_path), "\n"
62b0ee9e 712 "BindReadOnlyPaths=", os_release_source, ":/run/host/os-release\n"
c2bc710b 713 "LogExtraFields=PORTABLE=", basename(image_path), "\n"))
61d0578b 714 return -ENOMEM;
62b0ee9e 715 }
61d0578b
LP
716
717 r = write_string_file(dropin, text, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
718 if (r < 0)
719 return log_debug_errno(r, "Failed to write '%s': %m", dropin);
720
721 (void) portable_changes_add(changes, n_changes, PORTABLE_WRITE, dropin, NULL);
722
723 if (ret_dropin)
724 *ret_dropin = TAKE_PTR(dropin);
725
726 return 0;
727}
728
729static int find_profile(const char *name, const char *unit, char **ret) {
730 const char *p, *dot;
731
732 assert(name);
733 assert(ret);
734
735 assert_se(dot = strrchr(unit, '.'));
736
737 NULSTR_FOREACH(p, profile_dirs) {
738 _cleanup_free_ char *joined;
739
740 joined = strjoin(p, "/", name, "/", dot + 1, ".conf");
741 if (!joined)
742 return -ENOMEM;
743
744 if (laccess(joined, F_OK) >= 0) {
745 *ret = TAKE_PTR(joined);
746 return 0;
747 }
748
749 if (errno != ENOENT)
750 return -errno;
751 }
752
753 return -ENOENT;
754}
755
756static int install_profile_dropin(
757 const char *image_path,
758 const PortableMetadata *m,
759 const char *dropin_dir,
760 const char *profile,
761 PortableFlags flags,
762 char **ret_dropin,
763 PortableChange **changes,
764 size_t *n_changes) {
765
766 _cleanup_free_ char *dropin = NULL, *from = NULL;
767 int r;
768
769 assert(image_path);
770 assert(m);
771 assert(dropin_dir);
772
773 if (!profile)
774 return 0;
775
776 r = find_profile(profile, m->name, &from);
777 if (r < 0) {
99c89da0 778 if (r != -ENOENT)
61d0578b
LP
779 return log_debug_errno(errno, "Profile '%s' is not accessible: %m", profile);
780
781 log_debug_errno(errno, "Skipping link to profile '%s', as it does not exist: %m", profile);
782 return 0;
783 }
784
657ee2d8 785 dropin = path_join(dropin_dir, "10-profile.conf");
61d0578b
LP
786 if (!dropin)
787 return -ENOMEM;
788
789 if (flags & PORTABLE_PREFER_COPY) {
790
8a016c74 791 r = copy_file_atomic(from, dropin, 0644, 0, 0, COPY_REFLINK);
61d0578b 792 if (r < 0)
9a6f746f 793 return log_debug_errno(r, "Failed to copy %s %s %s: %m", from, special_glyph(SPECIAL_GLYPH_ARROW), dropin);
61d0578b
LP
794
795 (void) portable_changes_add(changes, n_changes, PORTABLE_COPY, dropin, from);
796
797 } else {
798
799 if (symlink(from, dropin) < 0)
9a6f746f 800 return log_debug_errno(errno, "Failed to link %s %s %s: %m", from, special_glyph(SPECIAL_GLYPH_ARROW), dropin);
61d0578b
LP
801
802 (void) portable_changes_add(changes, n_changes, PORTABLE_SYMLINK, dropin, from);
803 }
804
805 if (ret_dropin)
806 *ret_dropin = TAKE_PTR(dropin);
807
808 return 0;
809}
810
40a7b232 811static const char *attached_path(const LookupPaths *paths, PortableFlags flags) {
61d0578b
LP
812 const char *where;
813
814 assert(paths);
815
816 if (flags & PORTABLE_RUNTIME)
40a7b232 817 where = paths->runtime_attached;
61d0578b 818 else
40a7b232 819 where = paths->persistent_attached;
61d0578b
LP
820
821 assert(where);
822 return where;
823}
824
825static int attach_unit_file(
826 const LookupPaths *paths,
827 const char *image_path,
828 ImageType type,
829 const PortableMetadata *m,
830 const char *profile,
831 PortableFlags flags,
832 PortableChange **changes,
833 size_t *n_changes) {
834
835 _cleanup_(unlink_and_freep) char *chroot_dropin = NULL, *profile_dropin = NULL;
836 _cleanup_(rmdir_and_freep) char *dropin_dir = NULL;
837 const char *where, *path;
838 int r;
839
840 assert(paths);
841 assert(image_path);
842 assert(m);
843 assert(PORTABLE_METADATA_IS_UNIT(m));
844
40a7b232 845 where = attached_path(paths, flags);
61d0578b 846
d09d85a2
LP
847 (void) mkdir_parents(where, 0755);
848 if (mkdir(where, 0755) < 0) {
849 if (errno != EEXIST)
850 return -errno;
851 } else
852 (void) portable_changes_add(changes, n_changes, PORTABLE_MKDIR, where, NULL);
853
270384b2 854 path = prefix_roota(where, m->name);
61d0578b
LP
855 dropin_dir = strjoin(path, ".d");
856 if (!dropin_dir)
857 return -ENOMEM;
858
d09d85a2
LP
859 if (mkdir(dropin_dir, 0755) < 0) {
860 if (errno != EEXIST)
861 return -errno;
862 } else
863 (void) portable_changes_add(changes, n_changes, PORTABLE_MKDIR, dropin_dir, NULL);
61d0578b
LP
864
865 /* We install the drop-ins first, and the actual unit file last to achieve somewhat atomic behaviour if PID 1
866 * is reloaded while we are creating things here: as long as only the drop-ins exist the unit doesn't exist at
867 * all for PID 1. */
868
869 r = install_chroot_dropin(image_path, type, m, dropin_dir, &chroot_dropin, changes, n_changes);
870 if (r < 0)
871 return r;
872
873 r = install_profile_dropin(image_path, m, dropin_dir, profile, flags, &profile_dropin, changes, n_changes);
874 if (r < 0)
875 return r;
876
877 if ((flags & PORTABLE_PREFER_SYMLINK) && m->source) {
878
879 if (symlink(m->source, path) < 0)
880 return log_debug_errno(errno, "Failed to symlink unit file '%s': %m", path);
881
882 (void) portable_changes_add(changes, n_changes, PORTABLE_SYMLINK, path, m->source);
883
884 } else {
885 _cleanup_(unlink_and_freep) char *tmp = NULL;
886 _cleanup_close_ int fd = -1;
887
6d88513e 888 fd = open_tmpfile_linkable(path, O_WRONLY|O_CLOEXEC, &tmp);
61d0578b
LP
889 if (fd < 0)
890 return log_debug_errno(fd, "Failed to create unit file '%s': %m", path);
891
892 r = copy_bytes(m->fd, fd, UINT64_MAX, COPY_REFLINK);
893 if (r < 0)
894 return log_debug_errno(r, "Failed to copy unit file '%s': %m", path);
895
896 if (fchmod(fd, 0644) < 0)
897 return log_debug_errno(errno, "Failed to change unit file access mode for '%s': %m", path);
898
899 r = link_tmpfile(fd, tmp, path);
900 if (r < 0)
901 return log_debug_errno(r, "Failed to install unit file '%s': %m", path);
902
903 tmp = mfree(tmp);
904
905 (void) portable_changes_add(changes, n_changes, PORTABLE_COPY, path, m->source);
906 }
907
908 /* All is established now, now let's disable any rollbacks */
909 chroot_dropin = mfree(chroot_dropin);
910 profile_dropin = mfree(profile_dropin);
911 dropin_dir = mfree(dropin_dir);
912
913 return 0;
914}
915
916static int image_symlink(
917 const char *image_path,
918 PortableFlags flags,
919 char **ret) {
920
921 const char *fn, *where;
922 char *joined = NULL;
923
924 assert(image_path);
925 assert(ret);
926
927 fn = last_path_component(image_path);
928
929 if (flags & PORTABLE_RUNTIME)
930 where = "/run/portables/";
931 else
932 where = "/etc/portables/";
933
934 joined = strjoin(where, fn);
935 if (!joined)
936 return -ENOMEM;
937
938 *ret = joined;
939 return 0;
940}
941
942static int install_image_symlink(
943 const char *image_path,
944 PortableFlags flags,
945 PortableChange **changes,
946 size_t *n_changes) {
947
948 _cleanup_free_ char *sl = NULL;
949 int r;
950
951 assert(image_path);
952
953 /* If the image is outside of the image search also link it into it, so that it can be found with short image
954 * names and is listed among the images. */
955
d577d4a4 956 if (image_in_search_path(IMAGE_PORTABLE, NULL, image_path))
61d0578b
LP
957 return 0;
958
959 r = image_symlink(image_path, flags, &sl);
960 if (r < 0)
961 return log_debug_errno(r, "Failed to generate image symlink path: %m");
962
963 (void) mkdir_parents(sl, 0755);
964
965 if (symlink(image_path, sl) < 0)
9a6f746f 966 return log_debug_errno(errno, "Failed to link %s %s %s: %m", image_path, special_glyph(SPECIAL_GLYPH_ARROW), sl);
61d0578b
LP
967
968 (void) portable_changes_add(changes, n_changes, PORTABLE_SYMLINK, sl, image_path);
969 return 0;
970}
971
972int portable_attach(
973 sd_bus *bus,
974 const char *name_or_path,
975 char **matches,
976 const char *profile,
977 PortableFlags flags,
978 PortableChange **changes,
979 size_t *n_changes,
980 sd_bus_error *error) {
981
67818055 982 _cleanup_hashmap_free_ Hashmap *unit_files = NULL;
61d0578b
LP
983 _cleanup_(lookup_paths_free) LookupPaths paths = {};
984 _cleanup_(image_unrefp) Image *image = NULL;
985 PortableMetadata *item;
61d0578b
LP
986 int r;
987
988 assert(name_or_path);
989
d577d4a4 990 r = image_find_harder(IMAGE_PORTABLE, name_or_path, NULL, &image);
61d0578b
LP
991 if (r < 0)
992 return r;
993
994 r = portable_extract_by_path(image->path, matches, NULL, &unit_files, error);
995 if (r < 0)
996 return r;
997
998 r = lookup_paths_init(&paths, UNIT_FILE_SYSTEM, LOOKUP_PATHS_SPLIT_USR, NULL);
999 if (r < 0)
1000 return r;
1001
90e74a66 1002 HASHMAP_FOREACH(item, unit_files) {
61d0578b
LP
1003 r = unit_file_exists(UNIT_FILE_SYSTEM, &paths, item->name);
1004 if (r < 0)
1005 return sd_bus_error_set_errnof(error, r, "Failed to determine whether unit '%s' exists on the host: %m", item->name);
e26fe5f9 1006 if (!FLAGS_SET(flags, PORTABLE_REATTACH) && r > 0)
61d0578b
LP
1007 return sd_bus_error_setf(error, BUS_ERROR_UNIT_EXISTS, "Unit file '%s' exists on the host already, refusing.", item->name);
1008
1009 r = unit_file_is_active(bus, item->name, error);
1010 if (r < 0)
1011 return r;
e26fe5f9 1012 if (!FLAGS_SET(flags, PORTABLE_REATTACH) && r > 0)
61d0578b
LP
1013 return sd_bus_error_setf(error, BUS_ERROR_UNIT_EXISTS, "Unit file '%s' is active already, refusing.", item->name);
1014 }
1015
90e74a66 1016 HASHMAP_FOREACH(item, unit_files) {
61d0578b
LP
1017 r = attach_unit_file(&paths, image->path, image->type, item, profile, flags, changes, n_changes);
1018 if (r < 0)
1019 return r;
1020 }
1021
1022 /* We don't care too much for the image symlink, it's just a convenience thing, it's not necessary for proper
1023 * operation otherwise. */
1024 (void) install_image_symlink(image->path, flags, changes, n_changes);
1025
1026 return 0;
1027}
1028
1029static bool marker_matches_image(const char *marker, const char *name_or_path) {
1030 const char *a;
1031
1032 assert(marker);
1033 assert(name_or_path);
1034
1035 a = last_path_component(marker);
1036
1037 if (image_name_is_valid(name_or_path)) {
9e4079d4 1038 const char *e, *underscore;
61d0578b
LP
1039
1040 /* We shall match against an image name. In that case let's compare the last component, and optionally
9e4079d4
LB
1041 * allow either a suffix of ".raw" or a series of "/".
1042 * But allow matching on a different version of the same image, when a "_" is used as a separator. */
1043 underscore = strchr(name_or_path, '_');
1044 if (underscore)
1045 return strneq(a, name_or_path, underscore - name_or_path);
61d0578b
LP
1046
1047 e = startswith(a, name_or_path);
1048 if (!e)
1049 return false;
1050
1051 return
1052 e[strspn(e, "/")] == 0 ||
1053 streq(e, ".raw");
1054 } else {
9e4079d4 1055 const char *b, *underscore;
61d0578b
LP
1056 size_t l;
1057
1058 /* We shall match against a path. Let's ignore any prefix here though, as often there are many ways to
1059 * reach the same file. However, in this mode, let's validate any file suffix. */
1060
1061 l = strcspn(a, "/");
1062 b = last_path_component(name_or_path);
1063
1064 if (strcspn(b, "/") != l)
1065 return false;
1066
9e4079d4
LB
1067 underscore = strchr(b, '_');
1068 if (underscore)
1069 l = underscore - b;
1070
1071 return strneq(a, b, l);
61d0578b
LP
1072 }
1073}
1074
1075static int test_chroot_dropin(
1076 DIR *d,
1077 const char *where,
1078 const char *fname,
1079 const char *name_or_path,
1080 char **ret_marker) {
1081
1082 _cleanup_free_ char *line = NULL, *marker = NULL;
1083 _cleanup_fclose_ FILE *f = NULL;
1084 _cleanup_close_ int fd = -1;
1085 const char *p, *e, *k;
1086 int r;
1087
1088 assert(d);
1089 assert(where);
1090 assert(fname);
1091
1092 /* We recognize unis created from portable images via the drop-in we created for them */
1093
1094 p = strjoina(fname, ".d/20-portable.conf");
1095 fd = openat(dirfd(d), p, O_RDONLY|O_CLOEXEC);
1096 if (fd < 0) {
1097 if (errno == ENOENT)
1098 return 0;
1099
1100 return log_debug_errno(errno, "Failed to open %s/%s: %m", where, p);
1101 }
1102
4fa744a3 1103 r = take_fdopen_unlocked(&fd, "r", &f);
02e23d1a
ZJS
1104 if (r < 0)
1105 return log_debug_errno(r, "Failed to convert file handle: %m");
61d0578b
LP
1106
1107 r = read_line(f, LONG_LINE_MAX, &line);
1108 if (r < 0)
1109 return log_debug_errno(r, "Failed to read from %s/%s: %m", where, p);
1110
1111 e = startswith(line, PORTABLE_DROPIN_MARKER_BEGIN);
1112 if (!e)
1113 return 0;
1114
1115 k = endswith(e, PORTABLE_DROPIN_MARKER_END);
1116 if (!k)
1117 return 0;
1118
1119 marker = strndup(e, k - e);
1120 if (!marker)
1121 return -ENOMEM;
1122
1123 if (!name_or_path)
1124 r = true;
1125 else
1126 r = marker_matches_image(marker, name_or_path);
1127
1128 if (ret_marker)
1129 *ret_marker = TAKE_PTR(marker);
1130
1131 return r;
1132}
1133
1134int portable_detach(
1135 sd_bus *bus,
1136 const char *name_or_path,
1137 PortableFlags flags,
1138 PortableChange **changes,
1139 size_t *n_changes,
1140 sd_bus_error *error) {
1141
1142 _cleanup_(lookup_paths_free) LookupPaths paths = {};
d378ef70 1143 _cleanup_set_free_ Set *unit_files = NULL, *markers = NULL;
61d0578b
LP
1144 _cleanup_closedir_ DIR *d = NULL;
1145 const char *where, *item;
61d0578b
LP
1146 struct dirent *de;
1147 int ret = 0;
1148 int r;
1149
1150 assert(name_or_path);
1151
1152 r = lookup_paths_init(&paths, UNIT_FILE_SYSTEM, LOOKUP_PATHS_SPLIT_USR, NULL);
1153 if (r < 0)
1154 return r;
1155
40a7b232 1156 where = attached_path(&paths, flags);
61d0578b
LP
1157
1158 d = opendir(where);
339731db
LP
1159 if (!d) {
1160 if (errno == ENOENT)
1161 goto not_found;
1162
61d0578b 1163 return log_debug_errno(errno, "Failed to open '%s' directory: %m", where);
339731db 1164 }
61d0578b 1165
61d0578b
LP
1166 FOREACH_DIRENT(de, d, return log_debug_errno(errno, "Failed to enumerate '%s' directory: %m", where)) {
1167 _cleanup_free_ char *marker = NULL;
1168 UnitFileState state;
1169
1170 if (!unit_name_is_valid(de->d_name, UNIT_NAME_ANY))
1171 continue;
1172
1173 /* Filter out duplicates */
be327321 1174 if (set_contains(unit_files, de->d_name))
61d0578b
LP
1175 continue;
1176
1177 dirent_ensure_type(d, de);
1178 if (!IN_SET(de->d_type, DT_LNK, DT_REG))
1179 continue;
1180
1181 r = test_chroot_dropin(d, where, de->d_name, name_or_path, &marker);
1182 if (r < 0)
1183 return r;
1184 if (r == 0)
1185 continue;
1186
1187 r = unit_file_lookup_state(UNIT_FILE_SYSTEM, &paths, de->d_name, &state);
1188 if (r < 0)
1189 return log_debug_errno(r, "Failed to determine unit file state of '%s': %m", de->d_name);
c3d809ef 1190 if (!IN_SET(state, UNIT_FILE_STATIC, UNIT_FILE_DISABLED, UNIT_FILE_LINKED, UNIT_FILE_RUNTIME, UNIT_FILE_LINKED_RUNTIME))
61d0578b
LP
1191 return sd_bus_error_setf(error, BUS_ERROR_UNIT_EXISTS, "Unit file '%s' is in state '%s', can't detach.", de->d_name, unit_file_state_to_string(state));
1192
1193 r = unit_file_is_active(bus, de->d_name, error);
1194 if (r < 0)
1195 return r;
e26fe5f9 1196 if (!FLAGS_SET(flags, PORTABLE_REATTACH) && r > 0)
61d0578b
LP
1197 return sd_bus_error_setf(error, BUS_ERROR_UNIT_EXISTS, "Unit file '%s' is active, can't detach.", de->d_name);
1198
be327321 1199 r = set_put_strdup(&unit_files, de->d_name);
61d0578b
LP
1200 if (r < 0)
1201 return log_debug_errno(r, "Failed to add unit name '%s' to set: %m", de->d_name);
1202
1203 if (path_is_absolute(marker) &&
d577d4a4 1204 !image_in_search_path(IMAGE_PORTABLE, NULL, marker)) {
61d0578b 1205
d378ef70
ZJS
1206 r = set_ensure_consume(&markers, &path_hash_ops_free, TAKE_PTR(marker));
1207 if (r < 0)
61d0578b
LP
1208 return r;
1209 }
1210 }
1211
339731db
LP
1212 if (set_isempty(unit_files))
1213 goto not_found;
61d0578b 1214
90e74a66 1215 SET_FOREACH(item, unit_files) {
61d0578b
LP
1216 _cleanup_free_ char *md = NULL;
1217 const char *suffix;
1218
1219 if (unlinkat(dirfd(d), item, 0) < 0) {
1220 log_debug_errno(errno, "Can't remove unit file %s/%s: %m", where, item);
1221
1222 if (errno != ENOENT && ret >= 0)
1223 ret = -errno;
1224 } else
1225 portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, item, NULL);
1226
1227 FOREACH_STRING(suffix, ".d/10-profile.conf", ".d/20-portable.conf") {
1228 _cleanup_free_ char *dropin = NULL;
1229
1230 dropin = strjoin(item, suffix);
1231 if (!dropin)
1232 return -ENOMEM;
1233
1234 if (unlinkat(dirfd(d), dropin, 0) < 0) {
1235 log_debug_errno(errno, "Can't remove drop-in %s/%s: %m", where, dropin);
1236
1237 if (errno != ENOENT && ret >= 0)
1238 ret = -errno;
1239 } else
1240 portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, dropin, NULL);
1241 }
1242
1243 md = strjoin(item, ".d");
1244 if (!md)
1245 return -ENOMEM;
1246
1247 if (unlinkat(dirfd(d), md, AT_REMOVEDIR) < 0) {
1248 log_debug_errno(errno, "Can't remove drop-in directory %s/%s: %m", where, md);
1249
1250 if (errno != ENOENT && ret >= 0)
1251 ret = -errno;
1252 } else
1253 portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, md, NULL);
1254 }
1255
1256 /* Now, also drop any image symlink, for images outside of the sarch path */
90e74a66 1257 SET_FOREACH(item, markers) {
61d0578b
LP
1258 _cleanup_free_ char *sl = NULL;
1259 struct stat st;
1260
1261 r = image_symlink(item, flags, &sl);
1262 if (r < 0) {
1263 log_debug_errno(r, "Failed to determine image symlink for '%s', ignoring: %m", item);
1264 continue;
1265 }
1266
1267 if (lstat(sl, &st) < 0) {
1268 log_debug_errno(errno, "Failed to stat '%s', ignoring: %m", sl);
1269 continue;
1270 }
1271
1272 if (!S_ISLNK(st.st_mode)) {
1273 log_debug("Image '%s' is not a symlink, ignoring.", sl);
1274 continue;
1275 }
1276
1277 if (unlink(sl) < 0) {
1278 log_debug_errno(errno, "Can't remove image symlink '%s': %m", sl);
1279
1280 if (errno != ENOENT && ret >= 0)
1281 ret = -errno;
1282 } else
1283 portable_changes_add(changes, n_changes, PORTABLE_UNLINK, sl, NULL);
1284 }
1285
d09d85a2
LP
1286 /* Try to remove the unit file directory, if we can */
1287 if (rmdir(where) >= 0)
1288 portable_changes_add(changes, n_changes, PORTABLE_UNLINK, where, NULL);
1289
61d0578b 1290 return ret;
339731db
LP
1291
1292not_found:
1293 log_debug("No unit files associated with '%s' found. Image not attached?", name_or_path);
1294 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_UNIT, "No unit files associated with '%s' found. Image not attached?", name_or_path);
61d0578b
LP
1295}
1296
1297static int portable_get_state_internal(
1298 sd_bus *bus,
1299 const char *name_or_path,
1300 PortableFlags flags,
1301 PortableState *ret,
1302 sd_bus_error *error) {
1303
1304 _cleanup_(lookup_paths_free) LookupPaths paths = {};
1305 bool found_enabled = false, found_running = false;
be327321 1306 _cleanup_set_free_ Set *unit_files = NULL;
61d0578b
LP
1307 _cleanup_closedir_ DIR *d = NULL;
1308 const char *where;
1309 struct dirent *de;
1310 int r;
1311
1312 assert(name_or_path);
1313 assert(ret);
1314
1315 r = lookup_paths_init(&paths, UNIT_FILE_SYSTEM, LOOKUP_PATHS_SPLIT_USR, NULL);
1316 if (r < 0)
1317 return r;
1318
40a7b232 1319 where = attached_path(&paths, flags);
61d0578b
LP
1320
1321 d = opendir(where);
339731db
LP
1322 if (!d) {
1323 if (errno == ENOENT) {
1324 /* If the 'attached' directory doesn't exist at all, then we know for sure this image isn't attached. */
1325 *ret = PORTABLE_DETACHED;
1326 return 0;
1327 }
1328
61d0578b 1329 return log_debug_errno(errno, "Failed to open '%s' directory: %m", where);
339731db 1330 }
61d0578b 1331
61d0578b
LP
1332 FOREACH_DIRENT(de, d, return log_debug_errno(errno, "Failed to enumerate '%s' directory: %m", where)) {
1333 UnitFileState state;
1334
1335 if (!unit_name_is_valid(de->d_name, UNIT_NAME_ANY))
1336 continue;
1337
1338 /* Filter out duplicates */
be327321 1339 if (set_contains(unit_files, de->d_name))
61d0578b
LP
1340 continue;
1341
1342 dirent_ensure_type(d, de);
1343 if (!IN_SET(de->d_type, DT_LNK, DT_REG))
1344 continue;
1345
1346 r = test_chroot_dropin(d, where, de->d_name, name_or_path, NULL);
1347 if (r < 0)
1348 return r;
1349 if (r == 0)
1350 continue;
1351
1352 r = unit_file_lookup_state(UNIT_FILE_SYSTEM, &paths, de->d_name, &state);
1353 if (r < 0)
1354 return log_debug_errno(r, "Failed to determine unit file state of '%s': %m", de->d_name);
1355 if (!IN_SET(state, UNIT_FILE_STATIC, UNIT_FILE_DISABLED, UNIT_FILE_LINKED, UNIT_FILE_LINKED_RUNTIME))
1356 found_enabled = true;
1357
1358 r = unit_file_is_active(bus, de->d_name, error);
1359 if (r < 0)
1360 return r;
1361 if (r > 0)
1362 found_running = true;
1363
be327321 1364 r = set_put_strdup(&unit_files, de->d_name);
61d0578b
LP
1365 if (r < 0)
1366 return log_debug_errno(r, "Failed to add unit name '%s' to set: %m", de->d_name);
1367 }
1368
1369 *ret = found_running ? (!set_isempty(unit_files) && (flags & PORTABLE_RUNTIME) ? PORTABLE_RUNNING_RUNTIME : PORTABLE_RUNNING) :
1370 found_enabled ? (flags & PORTABLE_RUNTIME ? PORTABLE_ENABLED_RUNTIME : PORTABLE_ENABLED) :
1371 !set_isempty(unit_files) ? (flags & PORTABLE_RUNTIME ? PORTABLE_ATTACHED_RUNTIME : PORTABLE_ATTACHED) : PORTABLE_DETACHED;
1372
1373 return 0;
1374}
1375
1376int portable_get_state(
1377 sd_bus *bus,
1378 const char *name_or_path,
1379 PortableFlags flags,
1380 PortableState *ret,
1381 sd_bus_error *error) {
1382
1383 PortableState state;
1384 int r;
1385
1386 assert(name_or_path);
1387 assert(ret);
1388
1389 /* We look for matching units twice: once in the regular directories, and once in the runtime directories — but
1390 * the latter only if we didn't find anything in the former. */
1391
1392 r = portable_get_state_internal(bus, name_or_path, flags & ~PORTABLE_RUNTIME, &state, error);
1393 if (r < 0)
1394 return r;
1395
1396 if (state == PORTABLE_DETACHED) {
1397 r = portable_get_state_internal(bus, name_or_path, flags | PORTABLE_RUNTIME, &state, error);
1398 if (r < 0)
1399 return r;
1400 }
1401
1402 *ret = state;
1403 return 0;
1404}
1405
1406int portable_get_profiles(char ***ret) {
1407 assert(ret);
1408
1409 return conf_files_list_nulstr(ret, NULL, NULL, CONF_FILES_DIRECTORY|CONF_FILES_BASENAME|CONF_FILES_FILTER_MASKED, profile_dirs);
1410}
1411
1412static const char* const portable_change_type_table[_PORTABLE_CHANGE_TYPE_MAX] = {
1413 [PORTABLE_COPY] = "copy",
1414 [PORTABLE_MKDIR] = "mkdir",
1415 [PORTABLE_SYMLINK] = "symlink",
1416 [PORTABLE_UNLINK] = "unlink",
1417 [PORTABLE_WRITE] = "write",
1418};
1419
1420DEFINE_STRING_TABLE_LOOKUP(portable_change_type, PortableChangeType);
1421
1422static const char* const portable_state_table[_PORTABLE_STATE_MAX] = {
1423 [PORTABLE_DETACHED] = "detached",
1424 [PORTABLE_ATTACHED] = "attached",
1425 [PORTABLE_ATTACHED_RUNTIME] = "attached-runtime",
1426 [PORTABLE_ENABLED] = "enabled",
1427 [PORTABLE_ENABLED_RUNTIME] = "enabled-runtime",
1428 [PORTABLE_RUNNING] = "running",
1429 [PORTABLE_RUNNING_RUNTIME] = "running-runtime",
1430};
1431
1432DEFINE_STRING_TABLE_LOOKUP(portable_state, PortableState);