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