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