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