]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/portable/portable.c
Make fopen_temporary and fopen_temporary_label unlocked
[thirdparty/systemd.git] / src / portable / portable.c
CommitLineData
61d0578b
LP
1/* SPDX-License-Identifier: LGPL-2.1+ */
2
3#include <stdio_ext.h>
4
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"
15#include "io-util.h"
16#include "locale-util.h"
17#include "loop-util.h"
18#include "machine-image.h"
19#include "mkdir.h"
d8b4d14d 20#include "nulstr-util.h"
61d0578b
LP
21#include "os-util.h"
22#include "path-lookup.h"
23#include "portable.h"
24#include "process-util.h"
25#include "set.h"
26#include "signal-util.h"
27#include "socket-util.h"
760877e9 28#include "sort-util.h"
61d0578b
LP
29#include "string-table.h"
30#include "strv.h"
e4de7287 31#include "tmpfile-util.h"
61d0578b
LP
32#include "user-util.h"
33
34static const char profile_dirs[] = CONF_PATHS_NULSTR("systemd/portable/profile");
35
36/* Markers used in the first line of our 20-portable.conf unit file drop-in to determine, that a) the unit file was
37 * dropped there by the portable service logic and b) for which image it was dropped there. */
38#define PORTABLE_DROPIN_MARKER_BEGIN "# Drop-in created for image '"
39#define PORTABLE_DROPIN_MARKER_END "', do not edit."
40
41static bool prefix_match(const char *unit, const char *prefix) {
42 const char *p;
43
44 p = startswith(unit, prefix);
45 if (!p)
46 return false;
47
48 /* Only respect prefixes followed by dash or dot or when there's a complete match */
49 return IN_SET(*p, '-', '.', '@', 0);
50}
51
52static bool unit_match(const char *unit, char **matches) {
53 const char *dot;
54 char **i;
55
56 dot = strrchr(unit, '.');
57 if (!dot)
58 return false;
59
60 if (!STR_IN_SET(dot, ".service", ".socket", ".target", ".timer", ".path"))
61 return false;
62
63 /* Empty match expression means: everything */
64 if (strv_isempty(matches))
65 return true;
66
67 /* Otherwise, at least one needs to match */
68 STRV_FOREACH(i, matches)
69 if (prefix_match(unit, *i))
70 return true;
71
72 return false;
73}
74
75static PortableMetadata *portable_metadata_new(const char *name, int fd) {
76 PortableMetadata *m;
77
78 m = malloc0(offsetof(PortableMetadata, name) + strlen(name) + 1);
79 if (!m)
80 return NULL;
81
82 strcpy(m->name, name);
83 m->fd = fd;
84
85 return m;
86}
87
88PortableMetadata *portable_metadata_unref(PortableMetadata *i) {
89 if (!i)
90 return NULL;
91
92 safe_close(i->fd);
93 free(i->source);
94
95 return mfree(i);
96}
97
61d0578b
LP
98static int compare_metadata(PortableMetadata *const *x, PortableMetadata *const *y) {
99 return strcmp((*x)->name, (*y)->name);
100}
101
102int portable_metadata_hashmap_to_sorted_array(Hashmap *unit_files, PortableMetadata ***ret) {
103
104 _cleanup_free_ PortableMetadata **sorted = NULL;
105 Iterator iterator;
106 PortableMetadata *item;
107 size_t k = 0;
108
109 sorted = new(PortableMetadata*, hashmap_size(unit_files));
110 if (!sorted)
111 return -ENOMEM;
112
113 HASHMAP_FOREACH(item, unit_files, iterator)
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
129 union {
130 struct cmsghdr cmsghdr;
131 uint8_t buf[CMSG_SPACE(sizeof(int))];
132 } control = {};
133 struct iovec iovec;
134 struct msghdr mh = {
135 .msg_control = &control,
136 .msg_controllen = sizeof(control),
137 .msg_iov = &iovec,
138 .msg_iovlen = 1,
139 };
140 struct cmsghdr *cmsg;
141 _cleanup_close_ int data_fd = -1;
142
143 assert(socket_fd >= 0);
144 assert(name);
145 assert(fd >= 0);
146
147 data_fd = fd_duplicate_data_fd(fd);
148 if (data_fd < 0)
149 return data_fd;
150
151 cmsg = CMSG_FIRSTHDR(&mh);
152 cmsg->cmsg_level = SOL_SOCKET;
153 cmsg->cmsg_type = SCM_RIGHTS;
154 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
155 memcpy(CMSG_DATA(cmsg), &data_fd, sizeof(int));
156
157 mh.msg_controllen = CMSG_SPACE(sizeof(int));
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
a6887cc0 192 n = recvmsg(socket_fd, &mh, MSG_CMSG_CLOEXEC);
61d0578b
LP
193 if (n < 0)
194 return -errno;
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
330 m->source = strjoin(resolved, "/", de->d_name);
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
363 r = loop_device_make_by_path(path, O_RDONLY, &d);
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
389 r = dissect_image(d->fd, NULL, 0, DISSECT_IMAGE_READ_ONLY|DISSECT_IMAGE_REQUIRE_ROOT|DISSECT_IMAGE_DISCARD_ON_LOOP, &m);
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
439 /* We can't really distuingish a zero-length datagram without any fds from EOF (both are signalled the
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) {
658 path = strjoina(prefix, "/", path);
659
660 if (source)
661 source = strjoina(prefix, "/", source);
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
696 dropin = strjoin(dropin_dir, "/20-portable.conf");
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
783 dropin = strjoin(dropin_dir, "/10-profile.conf");
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
852 path = strjoina(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
e92aaed3 1094 f = fdopen(fd, "r");
61d0578b
LP
1095 if (!f)
1096 return log_debug_errno(errno, "Failed to convert file handle: %m");
1097 fd = -1;
1098
1099 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
1100
1101 r = read_line(f, LONG_LINE_MAX, &line);
1102 if (r < 0)
1103 return log_debug_errno(r, "Failed to read from %s/%s: %m", where, p);
1104
1105 e = startswith(line, PORTABLE_DROPIN_MARKER_BEGIN);
1106 if (!e)
1107 return 0;
1108
1109 k = endswith(e, PORTABLE_DROPIN_MARKER_END);
1110 if (!k)
1111 return 0;
1112
1113 marker = strndup(e, k - e);
1114 if (!marker)
1115 return -ENOMEM;
1116
1117 if (!name_or_path)
1118 r = true;
1119 else
1120 r = marker_matches_image(marker, name_or_path);
1121
1122 if (ret_marker)
1123 *ret_marker = TAKE_PTR(marker);
1124
1125 return r;
1126}
1127
1128int portable_detach(
1129 sd_bus *bus,
1130 const char *name_or_path,
1131 PortableFlags flags,
1132 PortableChange **changes,
1133 size_t *n_changes,
1134 sd_bus_error *error) {
1135
1136 _cleanup_(lookup_paths_free) LookupPaths paths = {};
1137 _cleanup_set_free_free_ Set *unit_files = NULL, *markers = NULL;
1138 _cleanup_closedir_ DIR *d = NULL;
1139 const char *where, *item;
1140 Iterator iterator;
1141 struct dirent *de;
1142 int ret = 0;
1143 int r;
1144
1145 assert(name_or_path);
1146
1147 r = lookup_paths_init(&paths, UNIT_FILE_SYSTEM, LOOKUP_PATHS_SPLIT_USR, NULL);
1148 if (r < 0)
1149 return r;
1150
40a7b232 1151 where = attached_path(&paths, flags);
61d0578b
LP
1152
1153 d = opendir(where);
339731db
LP
1154 if (!d) {
1155 if (errno == ENOENT)
1156 goto not_found;
1157
61d0578b 1158 return log_debug_errno(errno, "Failed to open '%s' directory: %m", where);
339731db 1159 }
61d0578b
LP
1160
1161 unit_files = set_new(&string_hash_ops);
1162 if (!unit_files)
1163 return -ENOMEM;
1164
1165 markers = set_new(&path_hash_ops);
1166 if (!markers)
1167 return -ENOMEM;
1168
1169 FOREACH_DIRENT(de, d, return log_debug_errno(errno, "Failed to enumerate '%s' directory: %m", where)) {
1170 _cleanup_free_ char *marker = NULL;
1171 UnitFileState state;
1172
1173 if (!unit_name_is_valid(de->d_name, UNIT_NAME_ANY))
1174 continue;
1175
1176 /* Filter out duplicates */
1177 if (set_get(unit_files, de->d_name))
1178 continue;
1179
1180 dirent_ensure_type(d, de);
1181 if (!IN_SET(de->d_type, DT_LNK, DT_REG))
1182 continue;
1183
1184 r = test_chroot_dropin(d, where, de->d_name, name_or_path, &marker);
1185 if (r < 0)
1186 return r;
1187 if (r == 0)
1188 continue;
1189
1190 r = unit_file_lookup_state(UNIT_FILE_SYSTEM, &paths, de->d_name, &state);
1191 if (r < 0)
1192 return log_debug_errno(r, "Failed to determine unit file state of '%s': %m", de->d_name);
1193 if (!IN_SET(state, UNIT_FILE_STATIC, UNIT_FILE_DISABLED, UNIT_FILE_LINKED, UNIT_FILE_RUNTIME))
1194 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));
1195
1196 r = unit_file_is_active(bus, de->d_name, error);
1197 if (r < 0)
1198 return r;
1199 if (r > 0)
1200 return sd_bus_error_setf(error, BUS_ERROR_UNIT_EXISTS, "Unit file '%s' is active, can't detach.", de->d_name);
1201
1202 r = set_put_strdup(unit_files, de->d_name);
1203 if (r < 0)
1204 return log_debug_errno(r, "Failed to add unit name '%s' to set: %m", de->d_name);
1205
1206 if (path_is_absolute(marker) &&
1207 !image_in_search_path(IMAGE_PORTABLE, marker)) {
1208
1209 r = set_ensure_allocated(&markers, &path_hash_ops);
1210 if (r < 0)
1211 return r;
1212
1213 r = set_put(markers, marker);
1214 if (r >= 0)
1215 marker = NULL;
1216 else if (r != -EEXIST)
1217 return r;
1218 }
1219 }
1220
339731db
LP
1221 if (set_isempty(unit_files))
1222 goto not_found;
61d0578b
LP
1223
1224 SET_FOREACH(item, unit_files, iterator) {
1225 _cleanup_free_ char *md = NULL;
1226 const char *suffix;
1227
1228 if (unlinkat(dirfd(d), item, 0) < 0) {
1229 log_debug_errno(errno, "Can't remove unit file %s/%s: %m", where, item);
1230
1231 if (errno != ENOENT && ret >= 0)
1232 ret = -errno;
1233 } else
1234 portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, item, NULL);
1235
1236 FOREACH_STRING(suffix, ".d/10-profile.conf", ".d/20-portable.conf") {
1237 _cleanup_free_ char *dropin = NULL;
1238
1239 dropin = strjoin(item, suffix);
1240 if (!dropin)
1241 return -ENOMEM;
1242
1243 if (unlinkat(dirfd(d), dropin, 0) < 0) {
1244 log_debug_errno(errno, "Can't remove drop-in %s/%s: %m", where, dropin);
1245
1246 if (errno != ENOENT && ret >= 0)
1247 ret = -errno;
1248 } else
1249 portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, dropin, NULL);
1250 }
1251
1252 md = strjoin(item, ".d");
1253 if (!md)
1254 return -ENOMEM;
1255
1256 if (unlinkat(dirfd(d), md, AT_REMOVEDIR) < 0) {
1257 log_debug_errno(errno, "Can't remove drop-in directory %s/%s: %m", where, md);
1258
1259 if (errno != ENOENT && ret >= 0)
1260 ret = -errno;
1261 } else
1262 portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, md, NULL);
1263 }
1264
1265 /* Now, also drop any image symlink, for images outside of the sarch path */
1266 SET_FOREACH(item, markers, iterator) {
1267 _cleanup_free_ char *sl = NULL;
1268 struct stat st;
1269
1270 r = image_symlink(item, flags, &sl);
1271 if (r < 0) {
1272 log_debug_errno(r, "Failed to determine image symlink for '%s', ignoring: %m", item);
1273 continue;
1274 }
1275
1276 if (lstat(sl, &st) < 0) {
1277 log_debug_errno(errno, "Failed to stat '%s', ignoring: %m", sl);
1278 continue;
1279 }
1280
1281 if (!S_ISLNK(st.st_mode)) {
1282 log_debug("Image '%s' is not a symlink, ignoring.", sl);
1283 continue;
1284 }
1285
1286 if (unlink(sl) < 0) {
1287 log_debug_errno(errno, "Can't remove image symlink '%s': %m", sl);
1288
1289 if (errno != ENOENT && ret >= 0)
1290 ret = -errno;
1291 } else
1292 portable_changes_add(changes, n_changes, PORTABLE_UNLINK, sl, NULL);
1293 }
1294
d09d85a2
LP
1295 /* Try to remove the unit file directory, if we can */
1296 if (rmdir(where) >= 0)
1297 portable_changes_add(changes, n_changes, PORTABLE_UNLINK, where, NULL);
1298
61d0578b 1299 return ret;
339731db
LP
1300
1301not_found:
1302 log_debug("No unit files associated with '%s' found. Image not attached?", name_or_path);
1303 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
1304}
1305
1306static int portable_get_state_internal(
1307 sd_bus *bus,
1308 const char *name_or_path,
1309 PortableFlags flags,
1310 PortableState *ret,
1311 sd_bus_error *error) {
1312
1313 _cleanup_(lookup_paths_free) LookupPaths paths = {};
1314 bool found_enabled = false, found_running = false;
1315 _cleanup_set_free_free_ Set *unit_files = NULL;
1316 _cleanup_closedir_ DIR *d = NULL;
1317 const char *where;
1318 struct dirent *de;
1319 int r;
1320
1321 assert(name_or_path);
1322 assert(ret);
1323
1324 r = lookup_paths_init(&paths, UNIT_FILE_SYSTEM, LOOKUP_PATHS_SPLIT_USR, NULL);
1325 if (r < 0)
1326 return r;
1327
40a7b232 1328 where = attached_path(&paths, flags);
61d0578b
LP
1329
1330 d = opendir(where);
339731db
LP
1331 if (!d) {
1332 if (errno == ENOENT) {
1333 /* If the 'attached' directory doesn't exist at all, then we know for sure this image isn't attached. */
1334 *ret = PORTABLE_DETACHED;
1335 return 0;
1336 }
1337
61d0578b 1338 return log_debug_errno(errno, "Failed to open '%s' directory: %m", where);
339731db 1339 }
61d0578b
LP
1340
1341 unit_files = set_new(&string_hash_ops);
1342 if (!unit_files)
1343 return -ENOMEM;
1344
1345 FOREACH_DIRENT(de, d, return log_debug_errno(errno, "Failed to enumerate '%s' directory: %m", where)) {
1346 UnitFileState state;
1347
1348 if (!unit_name_is_valid(de->d_name, UNIT_NAME_ANY))
1349 continue;
1350
1351 /* Filter out duplicates */
1352 if (set_get(unit_files, de->d_name))
1353 continue;
1354
1355 dirent_ensure_type(d, de);
1356 if (!IN_SET(de->d_type, DT_LNK, DT_REG))
1357 continue;
1358
1359 r = test_chroot_dropin(d, where, de->d_name, name_or_path, NULL);
1360 if (r < 0)
1361 return r;
1362 if (r == 0)
1363 continue;
1364
1365 r = unit_file_lookup_state(UNIT_FILE_SYSTEM, &paths, de->d_name, &state);
1366 if (r < 0)
1367 return log_debug_errno(r, "Failed to determine unit file state of '%s': %m", de->d_name);
1368 if (!IN_SET(state, UNIT_FILE_STATIC, UNIT_FILE_DISABLED, UNIT_FILE_LINKED, UNIT_FILE_LINKED_RUNTIME))
1369 found_enabled = true;
1370
1371 r = unit_file_is_active(bus, de->d_name, error);
1372 if (r < 0)
1373 return r;
1374 if (r > 0)
1375 found_running = true;
1376
1377 r = set_put_strdup(unit_files, de->d_name);
1378 if (r < 0)
1379 return log_debug_errno(r, "Failed to add unit name '%s' to set: %m", de->d_name);
1380 }
1381
1382 *ret = found_running ? (!set_isempty(unit_files) && (flags & PORTABLE_RUNTIME) ? PORTABLE_RUNNING_RUNTIME : PORTABLE_RUNNING) :
1383 found_enabled ? (flags & PORTABLE_RUNTIME ? PORTABLE_ENABLED_RUNTIME : PORTABLE_ENABLED) :
1384 !set_isempty(unit_files) ? (flags & PORTABLE_RUNTIME ? PORTABLE_ATTACHED_RUNTIME : PORTABLE_ATTACHED) : PORTABLE_DETACHED;
1385
1386 return 0;
1387}
1388
1389int portable_get_state(
1390 sd_bus *bus,
1391 const char *name_or_path,
1392 PortableFlags flags,
1393 PortableState *ret,
1394 sd_bus_error *error) {
1395
1396 PortableState state;
1397 int r;
1398
1399 assert(name_or_path);
1400 assert(ret);
1401
1402 /* We look for matching units twice: once in the regular directories, and once in the runtime directories — but
1403 * the latter only if we didn't find anything in the former. */
1404
1405 r = portable_get_state_internal(bus, name_or_path, flags & ~PORTABLE_RUNTIME, &state, error);
1406 if (r < 0)
1407 return r;
1408
1409 if (state == PORTABLE_DETACHED) {
1410 r = portable_get_state_internal(bus, name_or_path, flags | PORTABLE_RUNTIME, &state, error);
1411 if (r < 0)
1412 return r;
1413 }
1414
1415 *ret = state;
1416 return 0;
1417}
1418
1419int portable_get_profiles(char ***ret) {
1420 assert(ret);
1421
1422 return conf_files_list_nulstr(ret, NULL, NULL, CONF_FILES_DIRECTORY|CONF_FILES_BASENAME|CONF_FILES_FILTER_MASKED, profile_dirs);
1423}
1424
1425static const char* const portable_change_type_table[_PORTABLE_CHANGE_TYPE_MAX] = {
1426 [PORTABLE_COPY] = "copy",
1427 [PORTABLE_MKDIR] = "mkdir",
1428 [PORTABLE_SYMLINK] = "symlink",
1429 [PORTABLE_UNLINK] = "unlink",
1430 [PORTABLE_WRITE] = "write",
1431};
1432
1433DEFINE_STRING_TABLE_LOOKUP(portable_change_type, PortableChangeType);
1434
1435static const char* const portable_state_table[_PORTABLE_STATE_MAX] = {
1436 [PORTABLE_DETACHED] = "detached",
1437 [PORTABLE_ATTACHED] = "attached",
1438 [PORTABLE_ATTACHED_RUNTIME] = "attached-runtime",
1439 [PORTABLE_ENABLED] = "enabled",
1440 [PORTABLE_ENABLED_RUNTIME] = "enabled-runtime",
1441 [PORTABLE_RUNNING] = "running",
1442 [PORTABLE_RUNNING_RUNTIME] = "running-runtime",
1443};
1444
1445DEFINE_STRING_TABLE_LOOKUP(portable_state, PortableState);