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