]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/portable/portable.c
dissect: use DISKSEQ when waiting for block devices
[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->diskseq,
397 d->uevent_seqnum_not_before,
398 d->timestamp_not_before,
399 DISSECT_IMAGE_READ_ONLY |
400 DISSECT_IMAGE_GENERIC_ROOT |
401 DISSECT_IMAGE_REQUIRE_ROOT |
402 DISSECT_IMAGE_DISCARD_ON_LOOP |
403 DISSECT_IMAGE_RELAX_VAR_CHECK |
404 DISSECT_IMAGE_USR_NO_ROOT,
405 &m);
406 if (r == -ENOPKG)
407 sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Couldn't identify a suitable partition table or file system in '%s'.", path);
408 else if (r == -EADDRNOTAVAIL)
409 sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "No root partition for specified root hash found in '%s'.", path);
410 else if (r == -ENOTUNIQ)
411 sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Multiple suitable root partitions found in image '%s'.", path);
412 else if (r == -ENXIO)
413 sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "No suitable root partition found in image '%s'.", path);
414 else if (r == -EPROTONOSUPPORT)
415 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);
416 if (r < 0)
417 return r;
418
419 if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, seq) < 0)
420 return log_debug_errno(errno, "Failed to allocated SOCK_SEQPACKET socket: %m");
421
422 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE|FORK_LOG, &child);
423 if (r < 0)
424 return r;
425 if (r == 0) {
426 seq[0] = safe_close(seq[0]);
427
428 r = dissected_image_mount(m, tmpdir, UID_INVALID, UID_INVALID, DISSECT_IMAGE_READ_ONLY);
429 if (r < 0) {
430 log_debug_errno(r, "Failed to mount dissected image: %m");
431 goto child_finish;
432 }
433
434 r = extract_now(tmpdir, matches, seq[1], NULL, NULL);
435
436 child_finish:
437 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
438 }
439
440 seq[1] = safe_close(seq[1]);
441
442 unit_files = hashmap_new(&portable_metadata_hash_ops);
443 if (!unit_files)
444 return -ENOMEM;
445
446 for (;;) {
447 _cleanup_(portable_metadata_unrefp) PortableMetadata *add = NULL;
448 _cleanup_free_ char *name = NULL;
449 _cleanup_close_ int fd = -1;
450
451 r = recv_item(seq[0], &name, &fd);
452 if (r < 0)
453 return log_debug_errno(r, "Failed to receive item: %m");
454
455 /* We can't really distinguish a zero-length datagram without any fds from EOF (both are signalled the
456 * same way by recvmsg()). Hence, accept either as end notification. */
457 if (isempty(name) && fd < 0)
458 break;
459
460 if (isempty(name) || fd < 0)
461 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
462 "Invalid item sent from child.");
463
464 add = portable_metadata_new(name, path, fd);
465 if (!add)
466 return -ENOMEM;
467 fd = -1;
468
469 /* Note that we do not initialize 'add->source' here, as the source path is not usable here as
470 * it refers to a path only valid in the short-living namespaced child process we forked
471 * here. */
472
473 if (PORTABLE_METADATA_IS_UNIT(add)) {
474 r = hashmap_put(unit_files, add->name, add);
475 if (r < 0)
476 return log_debug_errno(r, "Failed to add item to unit file list: %m");
477
478 add = NULL;
479
480 } else if (PORTABLE_METADATA_IS_OS_RELEASE(add)) {
481
482 assert(!os_release);
483 os_release = TAKE_PTR(add);
484 } else
485 assert_not_reached("Unexpected metadata item from child.");
486 }
487
488 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
489 if (r < 0)
490 return r;
491 child = 0;
492 }
493
494 /* When the portable image is layered, the image with units will not
495 * have a full filesystem, so no os-release - it will be in the root layer */
496 if (extract_os_release && !os_release)
497 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Image '%s' lacks os-release data, refusing.", path);
498
499 if (!extract_os_release && hashmap_isempty(unit_files))
500 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Couldn't find any matching unit files in image '%s', refusing.", path);
501
502 if (ret_unit_files)
503 *ret_unit_files = TAKE_PTR(unit_files);
504
505 if (ret_os_release)
506 *ret_os_release = TAKE_PTR(os_release);
507
508 return 0;
509 }
510
511 int portable_extract(
512 const char *name_or_path,
513 char **matches,
514 char **extension_image_paths,
515 PortableMetadata **ret_os_release,
516 Hashmap **ret_unit_files,
517 sd_bus_error *error) {
518
519 _cleanup_(portable_metadata_unrefp) PortableMetadata *os_release = NULL;
520 _cleanup_ordered_hashmap_free_ OrderedHashmap *extension_images = NULL;
521 _cleanup_hashmap_free_ Hashmap *unit_files = NULL;
522 _cleanup_(image_unrefp) Image *image = NULL;
523 Image *ext;
524 int r;
525
526 assert(name_or_path);
527
528 r = image_find_harder(IMAGE_PORTABLE, name_or_path, NULL, &image);
529 if (r < 0)
530 return r;
531
532 if (!strv_isempty(extension_image_paths)) {
533 char **p;
534
535 extension_images = ordered_hashmap_new(&image_hash_ops);
536 if (!extension_images)
537 return -ENOMEM;
538
539 STRV_FOREACH(p, extension_image_paths) {
540 _cleanup_(image_unrefp) Image *new = NULL;
541
542 r = image_find_harder(IMAGE_PORTABLE, *p, NULL, &new);
543 if (r < 0)
544 return r;
545
546 r = ordered_hashmap_put(extension_images, new->name, new);
547 if (r < 0)
548 return r;
549 TAKE_PTR(new);
550 }
551 }
552
553 r = portable_extract_by_path(image->path, true, matches, &os_release, &unit_files, error);
554 if (r < 0)
555 return r;
556
557 ORDERED_HASHMAP_FOREACH(ext, extension_images) {
558 _cleanup_hashmap_free_ Hashmap *extra_unit_files = NULL;
559
560 r = portable_extract_by_path(ext->path, false, matches, NULL, &extra_unit_files, error);
561 if (r < 0)
562 return r;
563 r = hashmap_move(unit_files, extra_unit_files);
564 if (r < 0)
565 return r;
566 }
567
568 *ret_os_release = TAKE_PTR(os_release);
569 *ret_unit_files = TAKE_PTR(unit_files);
570
571 return 0;
572 }
573
574 static int unit_file_is_active(
575 sd_bus *bus,
576 const char *name,
577 sd_bus_error *error) {
578
579 static const char *const active_states[] = {
580 "activating",
581 "active",
582 "reloading",
583 "deactivating",
584 NULL,
585 };
586 int r;
587
588 if (!bus)
589 return false;
590
591 /* If we are looking at a plain or instance things are easy, we can just query the state */
592 if (unit_name_is_valid(name, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
593 _cleanup_free_ char *path = NULL, *buf = NULL;
594
595 path = unit_dbus_path_from_name(name);
596 if (!path)
597 return -ENOMEM;
598
599 r = sd_bus_get_property_string(
600 bus,
601 "org.freedesktop.systemd1",
602 path,
603 "org.freedesktop.systemd1.Unit",
604 "ActiveState",
605 error,
606 &buf);
607 if (r < 0)
608 return log_debug_errno(r, "Failed to retrieve unit state: %s", bus_error_message(error, r));
609
610 return strv_contains((char**) active_states, buf);
611 }
612
613 /* Otherwise we need to enumerate. But let's build the most restricted query we can */
614 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
615 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
616 const char *at, *prefix, *joined;
617
618 r = sd_bus_message_new_method_call(
619 bus,
620 &m,
621 "org.freedesktop.systemd1",
622 "/org/freedesktop/systemd1",
623 "org.freedesktop.systemd1.Manager",
624 "ListUnitsByPatterns");
625 if (r < 0)
626 return r;
627
628 r = sd_bus_message_append_strv(m, (char**) active_states);
629 if (r < 0)
630 return r;
631
632 at = strchr(name, '@');
633 assert(at);
634
635 prefix = strndupa(name, at + 1 - name);
636 joined = strjoina(prefix, "*", at + 1);
637
638 r = sd_bus_message_append_strv(m, STRV_MAKE(joined));
639 if (r < 0)
640 return r;
641
642 r = sd_bus_call(bus, m, 0, error, &reply);
643 if (r < 0)
644 return log_debug_errno(r, "Failed to list units: %s", bus_error_message(error, r));
645
646 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)");
647 if (r < 0)
648 return r;
649
650 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_STRUCT, "ssssssouso");
651 if (r < 0)
652 return r;
653
654 return r > 0;
655 }
656
657 return -EINVAL;
658 }
659
660 static int portable_changes_add(
661 PortableChange **changes,
662 size_t *n_changes,
663 int type_or_errno, /* PORTABLE_COPY, PORTABLE_SYMLINK, … if positive, or errno if negative */
664 const char *path,
665 const char *source) {
666
667 _cleanup_free_ char *p = NULL, *s = NULL;
668 PortableChange *c;
669
670 assert(path);
671 assert(!changes == !n_changes);
672
673 if (type_or_errno >= 0)
674 assert(type_or_errno < _PORTABLE_CHANGE_TYPE_MAX);
675 else
676 assert(type_or_errno >= -ERRNO_MAX);
677
678 if (!changes)
679 return 0;
680
681 c = reallocarray(*changes, *n_changes + 1, sizeof(PortableChange));
682 if (!c)
683 return -ENOMEM;
684 *changes = c;
685
686 p = strdup(path);
687 if (!p)
688 return -ENOMEM;
689
690 path_simplify(p);
691
692 if (source) {
693 s = strdup(source);
694 if (!s)
695 return -ENOMEM;
696
697 path_simplify(s);
698 }
699
700 c[(*n_changes)++] = (PortableChange) {
701 .type_or_errno = type_or_errno,
702 .path = TAKE_PTR(p),
703 .source = TAKE_PTR(s),
704 };
705
706 return 0;
707 }
708
709 static int portable_changes_add_with_prefix(
710 PortableChange **changes,
711 size_t *n_changes,
712 int type_or_errno,
713 const char *prefix,
714 const char *path,
715 const char *source) {
716
717 assert(path);
718 assert(!changes == !n_changes);
719
720 if (!changes)
721 return 0;
722
723 if (prefix) {
724 path = prefix_roota(prefix, path);
725
726 if (source)
727 source = prefix_roota(prefix, source);
728 }
729
730 return portable_changes_add(changes, n_changes, type_or_errno, path, source);
731 }
732
733 void portable_changes_free(PortableChange *changes, size_t n_changes) {
734 size_t i;
735
736 assert(changes || n_changes == 0);
737
738 for (i = 0; i < n_changes; i++) {
739 free(changes[i].path);
740 free(changes[i].source);
741 }
742
743 free(changes);
744 }
745
746 static const char *root_setting_from_image(ImageType type) {
747 return IN_SET(type, IMAGE_DIRECTORY, IMAGE_SUBVOLUME) ? "RootDirectory=" : "RootImage=";
748 }
749
750 static int make_marker_text(const char *image_path, OrderedHashmap *extension_images, char **ret_text) {
751 _cleanup_free_ char *text = NULL, *escaped_image_path = NULL;
752 Image *ext;
753
754 assert(image_path);
755 assert(ret_text);
756
757 escaped_image_path = xescape(image_path, ":");
758 if (!escaped_image_path)
759 return -ENOMEM;
760
761 /* If the image is layered, include all layers in the marker as a colon-separated
762 * list of paths, so that we can do exact matches on removal. */
763 text = strjoin(PORTABLE_DROPIN_MARKER_BEGIN, escaped_image_path);
764 if (!text)
765 return -ENOMEM;
766
767 ORDERED_HASHMAP_FOREACH(ext, extension_images) {
768 _cleanup_free_ char *escaped = NULL;
769
770 escaped = xescape(ext->path, ":");
771 if (!escaped)
772 return -ENOMEM;
773
774 if (!strextend(&text, ":", escaped))
775 return -ENOMEM;
776 }
777
778 if (!strextend(&text, PORTABLE_DROPIN_MARKER_END "\n"))
779 return -ENOMEM;
780
781 *ret_text = TAKE_PTR(text);
782 return 0;
783 }
784
785 static int install_chroot_dropin(
786 const char *image_path,
787 ImageType type,
788 OrderedHashmap *extension_images,
789 const PortableMetadata *m,
790 const char *dropin_dir,
791 char **ret_dropin,
792 PortableChange **changes,
793 size_t *n_changes) {
794
795 _cleanup_free_ char *text = NULL, *dropin = NULL;
796 Image *ext;
797 int r;
798
799 assert(image_path);
800 assert(m);
801 assert(dropin_dir);
802
803 dropin = path_join(dropin_dir, "20-portable.conf");
804 if (!dropin)
805 return -ENOMEM;
806
807 r = make_marker_text(image_path, extension_images, &text);
808 if (r < 0)
809 return log_debug_errno(r, "Failed to generate marker string for portable drop-in: %m");
810
811 if (endswith(m->name, ".service")) {
812 const char *os_release_source, *root_type;
813 _cleanup_free_ char *base_name = NULL;
814
815 root_type = root_setting_from_image(type);
816
817 if (access("/etc/os-release", F_OK) < 0) {
818 if (errno != ENOENT)
819 return log_debug_errno(errno, "Failed to check if /etc/os-release exists: %m");
820
821 os_release_source = "/usr/lib/os-release";
822 } else
823 os_release_source = "/etc/os-release";
824
825 r = path_extract_filename(m->image_path ?: image_path, &base_name);
826 if (r < 0)
827 return log_debug_errno(r, "Failed to extract basename from '%s': %m", m->image_path ?: image_path);
828
829 if (!strextend(&text,
830 "\n"
831 "[Service]\n",
832 root_type, image_path, "\n"
833 "Environment=PORTABLE=", base_name, "\n"
834 "BindReadOnlyPaths=", os_release_source, ":/run/host/os-release\n"
835 "LogExtraFields=PORTABLE=", base_name, "\n"))
836 return -ENOMEM;
837
838 if (m->image_path && !path_equal(m->image_path, image_path))
839 ORDERED_HASHMAP_FOREACH(ext, extension_images)
840 if (!strextend(&text, "ExtensionImages=", ext->path, "\n"))
841 return -ENOMEM;
842 }
843
844 r = write_string_file(dropin, text, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
845 if (r < 0)
846 return log_debug_errno(r, "Failed to write '%s': %m", dropin);
847
848 (void) portable_changes_add(changes, n_changes, PORTABLE_WRITE, dropin, NULL);
849
850 if (ret_dropin)
851 *ret_dropin = TAKE_PTR(dropin);
852
853 return 0;
854 }
855
856 static int find_profile(const char *name, const char *unit, char **ret) {
857 const char *p, *dot;
858
859 assert(name);
860 assert(ret);
861
862 assert_se(dot = strrchr(unit, '.'));
863
864 NULSTR_FOREACH(p, profile_dirs) {
865 _cleanup_free_ char *joined = NULL;
866
867 joined = strjoin(p, "/", name, "/", dot + 1, ".conf");
868 if (!joined)
869 return -ENOMEM;
870
871 if (laccess(joined, F_OK) >= 0) {
872 *ret = TAKE_PTR(joined);
873 return 0;
874 }
875
876 if (errno != ENOENT)
877 return -errno;
878 }
879
880 return -ENOENT;
881 }
882
883 static int install_profile_dropin(
884 const char *image_path,
885 const PortableMetadata *m,
886 const char *dropin_dir,
887 const char *profile,
888 PortableFlags flags,
889 char **ret_dropin,
890 PortableChange **changes,
891 size_t *n_changes) {
892
893 _cleanup_free_ char *dropin = NULL, *from = NULL;
894 int r;
895
896 assert(image_path);
897 assert(m);
898 assert(dropin_dir);
899
900 if (!profile)
901 return 0;
902
903 r = find_profile(profile, m->name, &from);
904 if (r < 0) {
905 if (r != -ENOENT)
906 return log_debug_errno(errno, "Profile '%s' is not accessible: %m", profile);
907
908 log_debug_errno(errno, "Skipping link to profile '%s', as it does not exist: %m", profile);
909 return 0;
910 }
911
912 dropin = path_join(dropin_dir, "10-profile.conf");
913 if (!dropin)
914 return -ENOMEM;
915
916 if (flags & PORTABLE_PREFER_COPY) {
917
918 r = copy_file_atomic(from, dropin, 0644, 0, 0, COPY_REFLINK);
919 if (r < 0)
920 return log_debug_errno(r, "Failed to copy %s %s %s: %m", from, special_glyph(SPECIAL_GLYPH_ARROW), dropin);
921
922 (void) portable_changes_add(changes, n_changes, PORTABLE_COPY, dropin, from);
923
924 } else {
925
926 if (symlink(from, dropin) < 0)
927 return log_debug_errno(errno, "Failed to link %s %s %s: %m", from, special_glyph(SPECIAL_GLYPH_ARROW), dropin);
928
929 (void) portable_changes_add(changes, n_changes, PORTABLE_SYMLINK, dropin, from);
930 }
931
932 if (ret_dropin)
933 *ret_dropin = TAKE_PTR(dropin);
934
935 return 0;
936 }
937
938 static const char *attached_path(const LookupPaths *paths, PortableFlags flags) {
939 const char *where;
940
941 assert(paths);
942
943 if (flags & PORTABLE_RUNTIME)
944 where = paths->runtime_attached;
945 else
946 where = paths->persistent_attached;
947
948 assert(where);
949 return where;
950 }
951
952 static int attach_unit_file(
953 const LookupPaths *paths,
954 const char *image_path,
955 ImageType type,
956 OrderedHashmap *extension_images,
957 const PortableMetadata *m,
958 const char *profile,
959 PortableFlags flags,
960 PortableChange **changes,
961 size_t *n_changes) {
962
963 _cleanup_(unlink_and_freep) char *chroot_dropin = NULL, *profile_dropin = NULL;
964 _cleanup_(rmdir_and_freep) char *dropin_dir = NULL;
965 const char *where, *path;
966 int r;
967
968 assert(paths);
969 assert(image_path);
970 assert(m);
971 assert(PORTABLE_METADATA_IS_UNIT(m));
972
973 where = attached_path(paths, flags);
974
975 (void) mkdir_parents(where, 0755);
976 if (mkdir(where, 0755) < 0) {
977 if (errno != EEXIST)
978 return -errno;
979 } else
980 (void) portable_changes_add(changes, n_changes, PORTABLE_MKDIR, where, NULL);
981
982 path = prefix_roota(where, m->name);
983 dropin_dir = strjoin(path, ".d");
984 if (!dropin_dir)
985 return -ENOMEM;
986
987 if (mkdir(dropin_dir, 0755) < 0) {
988 if (errno != EEXIST)
989 return -errno;
990 } else
991 (void) portable_changes_add(changes, n_changes, PORTABLE_MKDIR, dropin_dir, NULL);
992
993 /* We install the drop-ins first, and the actual unit file last to achieve somewhat atomic behaviour if PID 1
994 * is reloaded while we are creating things here: as long as only the drop-ins exist the unit doesn't exist at
995 * all for PID 1. */
996
997 r = install_chroot_dropin(image_path, type, extension_images, m, dropin_dir, &chroot_dropin, changes, n_changes);
998 if (r < 0)
999 return r;
1000
1001 r = install_profile_dropin(image_path, m, dropin_dir, profile, flags, &profile_dropin, changes, n_changes);
1002 if (r < 0)
1003 return r;
1004
1005 if ((flags & PORTABLE_PREFER_SYMLINK) && m->source) {
1006
1007 if (symlink(m->source, path) < 0)
1008 return log_debug_errno(errno, "Failed to symlink unit file '%s': %m", path);
1009
1010 (void) portable_changes_add(changes, n_changes, PORTABLE_SYMLINK, path, m->source);
1011
1012 } else {
1013 _cleanup_(unlink_and_freep) char *tmp = NULL;
1014 _cleanup_close_ int fd = -1;
1015
1016 fd = open_tmpfile_linkable(path, O_WRONLY|O_CLOEXEC, &tmp);
1017 if (fd < 0)
1018 return log_debug_errno(fd, "Failed to create unit file '%s': %m", path);
1019
1020 r = copy_bytes(m->fd, fd, UINT64_MAX, COPY_REFLINK);
1021 if (r < 0)
1022 return log_debug_errno(r, "Failed to copy unit file '%s': %m", path);
1023
1024 if (fchmod(fd, 0644) < 0)
1025 return log_debug_errno(errno, "Failed to change unit file access mode for '%s': %m", path);
1026
1027 r = link_tmpfile(fd, tmp, path);
1028 if (r < 0)
1029 return log_debug_errno(r, "Failed to install unit file '%s': %m", path);
1030
1031 tmp = mfree(tmp);
1032
1033 (void) portable_changes_add(changes, n_changes, PORTABLE_COPY, path, m->source);
1034 }
1035
1036 /* All is established now, now let's disable any rollbacks */
1037 chroot_dropin = mfree(chroot_dropin);
1038 profile_dropin = mfree(profile_dropin);
1039 dropin_dir = mfree(dropin_dir);
1040
1041 return 0;
1042 }
1043
1044 static int image_symlink(
1045 const char *image_path,
1046 PortableFlags flags,
1047 char **ret) {
1048
1049 const char *fn, *where;
1050 char *joined = NULL;
1051
1052 assert(image_path);
1053 assert(ret);
1054
1055 fn = last_path_component(image_path);
1056
1057 if (flags & PORTABLE_RUNTIME)
1058 where = "/run/portables/";
1059 else
1060 where = "/etc/portables/";
1061
1062 joined = strjoin(where, fn);
1063 if (!joined)
1064 return -ENOMEM;
1065
1066 *ret = joined;
1067 return 0;
1068 }
1069
1070 static int install_image_symlink(
1071 const char *image_path,
1072 PortableFlags flags,
1073 PortableChange **changes,
1074 size_t *n_changes) {
1075
1076 _cleanup_free_ char *sl = NULL;
1077 int r;
1078
1079 assert(image_path);
1080
1081 /* If the image is outside of the image search also link it into it, so that it can be found with short image
1082 * names and is listed among the images. */
1083
1084 if (image_in_search_path(IMAGE_PORTABLE, NULL, image_path))
1085 return 0;
1086
1087 r = image_symlink(image_path, flags, &sl);
1088 if (r < 0)
1089 return log_debug_errno(r, "Failed to generate image symlink path: %m");
1090
1091 (void) mkdir_parents(sl, 0755);
1092
1093 if (symlink(image_path, sl) < 0)
1094 return log_debug_errno(errno, "Failed to link %s %s %s: %m", image_path, special_glyph(SPECIAL_GLYPH_ARROW), sl);
1095
1096 (void) portable_changes_add(changes, n_changes, PORTABLE_SYMLINK, sl, image_path);
1097 return 0;
1098 }
1099
1100 static int install_image_and_extensions_symlinks(
1101 const Image *image,
1102 OrderedHashmap *extension_images,
1103 PortableFlags flags,
1104 PortableChange **changes,
1105 size_t *n_changes) {
1106
1107 Image *ext;
1108 int r;
1109
1110 assert(image);
1111
1112 ORDERED_HASHMAP_FOREACH(ext, extension_images) {
1113 r = install_image_symlink(ext->path, flags, changes, n_changes);
1114 if (r < 0)
1115 return r;
1116 }
1117
1118 r = install_image_symlink(image->path, flags, changes, n_changes);
1119 if (r < 0)
1120 return r;
1121
1122 return 0;
1123 }
1124
1125 int portable_attach(
1126 sd_bus *bus,
1127 const char *name_or_path,
1128 char **matches,
1129 const char *profile,
1130 char **extension_image_paths,
1131 PortableFlags flags,
1132 PortableChange **changes,
1133 size_t *n_changes,
1134 sd_bus_error *error) {
1135
1136 _cleanup_ordered_hashmap_free_ OrderedHashmap *extension_images = NULL;
1137 _cleanup_hashmap_free_ Hashmap *unit_files = NULL;
1138 _cleanup_(lookup_paths_free) LookupPaths paths = {};
1139 _cleanup_(image_unrefp) Image *image = NULL;
1140 PortableMetadata *item;
1141 Image *ext;
1142 char **p;
1143 int r;
1144
1145 assert(name_or_path);
1146
1147 r = image_find_harder(IMAGE_PORTABLE, name_or_path, NULL, &image);
1148 if (r < 0)
1149 return r;
1150 if (!strv_isempty(extension_image_paths)) {
1151 extension_images = ordered_hashmap_new(&image_hash_ops);
1152 if (!extension_images)
1153 return -ENOMEM;
1154
1155 STRV_FOREACH(p, extension_image_paths) {
1156 _cleanup_(image_unrefp) Image *new = NULL;
1157
1158 r = image_find_harder(IMAGE_PORTABLE, *p, NULL, &new);
1159 if (r < 0)
1160 return r;
1161
1162 r = ordered_hashmap_put(extension_images, new->name, new);
1163 if (r < 0)
1164 return r;
1165 TAKE_PTR(new);
1166 }
1167 }
1168
1169 r = portable_extract_by_path(image->path, true, matches, NULL, &unit_files, error);
1170 if (r < 0)
1171 return r;
1172
1173 ORDERED_HASHMAP_FOREACH(ext, extension_images) {
1174 _cleanup_hashmap_free_ Hashmap *extra_unit_files = NULL;
1175
1176 r = portable_extract_by_path(ext->path, false, matches, NULL, &extra_unit_files, error);
1177 if (r < 0)
1178 return r;
1179 r = hashmap_move(unit_files, extra_unit_files);
1180 if (r < 0)
1181 return r;
1182 }
1183
1184 r = lookup_paths_init(&paths, UNIT_FILE_SYSTEM, LOOKUP_PATHS_SPLIT_USR, NULL);
1185 if (r < 0)
1186 return r;
1187
1188 HASHMAP_FOREACH(item, unit_files) {
1189 r = unit_file_exists(UNIT_FILE_SYSTEM, &paths, item->name);
1190 if (r < 0)
1191 return sd_bus_error_set_errnof(error, r, "Failed to determine whether unit '%s' exists on the host: %m", item->name);
1192 if (!FLAGS_SET(flags, PORTABLE_REATTACH) && r > 0)
1193 return sd_bus_error_setf(error, BUS_ERROR_UNIT_EXISTS, "Unit file '%s' exists on the host already, refusing.", item->name);
1194
1195 r = unit_file_is_active(bus, item->name, error);
1196 if (r < 0)
1197 return r;
1198 if (!FLAGS_SET(flags, PORTABLE_REATTACH) && r > 0)
1199 return sd_bus_error_setf(error, BUS_ERROR_UNIT_EXISTS, "Unit file '%s' is active already, refusing.", item->name);
1200 }
1201
1202 HASHMAP_FOREACH(item, unit_files) {
1203 r = attach_unit_file(&paths, image->path, image->type, extension_images,
1204 item, profile, flags, changes, n_changes);
1205 if (r < 0)
1206 return r;
1207 }
1208
1209 /* We don't care too much for the image symlink, it's just a convenience thing, it's not necessary for proper
1210 * operation otherwise. */
1211 (void) install_image_and_extensions_symlinks(image, extension_images, flags, changes, n_changes);
1212
1213 return 0;
1214 }
1215
1216 static bool marker_matches_images(const char *marker, const char *name_or_path, char **extension_image_paths) {
1217 _cleanup_strv_free_ char **root_and_extensions = NULL;
1218 char **image_name_or_path;
1219 const char *a;
1220 int r;
1221
1222 assert(marker);
1223 assert(name_or_path);
1224
1225 /* If extensions were used when attaching, the marker will be a colon-separated
1226 * list of images/paths. We enforce strict 1:1 matching, so that we are sure
1227 * we are detaching exactly what was attached.
1228 * For each image, starting with the root, we look for a token in the marker,
1229 * and return a negative answer on any non-matching combination. */
1230
1231 root_and_extensions = strv_new(name_or_path);
1232 if (!root_and_extensions)
1233 return -ENOMEM;
1234
1235 r = strv_extend_strv(&root_and_extensions, extension_image_paths, false);
1236 if (r < 0)
1237 return r;
1238
1239 STRV_FOREACH(image_name_or_path, root_and_extensions) {
1240 _cleanup_free_ char *image = NULL;
1241
1242 r = extract_first_word(&marker, &image, ":", EXTRACT_UNQUOTE|EXTRACT_RETAIN_ESCAPE);
1243 if (r < 0)
1244 return log_debug_errno(r, "Failed to parse marker: %s", marker);
1245 if (r == 0)
1246 return false;
1247
1248 a = last_path_component(image);
1249
1250 if (image_name_is_valid(*image_name_or_path)) {
1251 const char *e, *underscore;
1252
1253 /* We shall match against an image name. In that case let's compare the last component, and optionally
1254 * allow either a suffix of ".raw" or a series of "/".
1255 * But allow matching on a different version of the same image, when a "_" is used as a separator. */
1256 underscore = strchr(*image_name_or_path, '_');
1257 if (underscore) {
1258 if (strneq(a, *image_name_or_path, underscore - *image_name_or_path))
1259 continue;
1260 return false;
1261 }
1262
1263 e = startswith(a, *image_name_or_path);
1264 if (!e)
1265 return false;
1266
1267 if(!(e[strspn(e, "/")] == 0 || streq(e, ".raw")))
1268 return false;
1269 } else {
1270 const char *b, *underscore;
1271 size_t l;
1272
1273 /* We shall match against a path. Let's ignore any prefix here though, as often there are many ways to
1274 * reach the same file. However, in this mode, let's validate any file suffix. */
1275
1276 l = strcspn(a, "/");
1277 b = last_path_component(*image_name_or_path);
1278
1279 if (strcspn(b, "/") != l)
1280 return false;
1281
1282 underscore = strchr(b, '_');
1283 if (underscore)
1284 l = underscore - b;
1285
1286 if (!strneq(a, b, l))
1287 return false;
1288 }
1289 }
1290
1291 return true;
1292 }
1293
1294 static int test_chroot_dropin(
1295 DIR *d,
1296 const char *where,
1297 const char *fname,
1298 const char *name_or_path,
1299 char **extension_image_paths,
1300 char **ret_marker) {
1301
1302 _cleanup_free_ char *line = NULL, *marker = NULL;
1303 _cleanup_fclose_ FILE *f = NULL;
1304 _cleanup_close_ int fd = -1;
1305 const char *p, *e, *k;
1306 int r;
1307
1308 assert(d);
1309 assert(where);
1310 assert(fname);
1311
1312 /* We recognize unis created from portable images via the drop-in we created for them */
1313
1314 p = strjoina(fname, ".d/20-portable.conf");
1315 fd = openat(dirfd(d), p, O_RDONLY|O_CLOEXEC);
1316 if (fd < 0) {
1317 if (errno == ENOENT)
1318 return 0;
1319
1320 return log_debug_errno(errno, "Failed to open %s/%s: %m", where, p);
1321 }
1322
1323 r = take_fdopen_unlocked(&fd, "r", &f);
1324 if (r < 0)
1325 return log_debug_errno(r, "Failed to convert file handle: %m");
1326
1327 r = read_line(f, LONG_LINE_MAX, &line);
1328 if (r < 0)
1329 return log_debug_errno(r, "Failed to read from %s/%s: %m", where, p);
1330
1331 e = startswith(line, PORTABLE_DROPIN_MARKER_BEGIN);
1332 if (!e)
1333 return 0;
1334
1335 k = endswith(e, PORTABLE_DROPIN_MARKER_END);
1336 if (!k)
1337 return 0;
1338
1339 marker = strndup(e, k - e);
1340 if (!marker)
1341 return -ENOMEM;
1342
1343 if (!name_or_path)
1344 r = true;
1345 else
1346 r = marker_matches_images(marker, name_or_path, extension_image_paths);
1347
1348 if (ret_marker)
1349 *ret_marker = TAKE_PTR(marker);
1350
1351 return r;
1352 }
1353
1354 int portable_detach(
1355 sd_bus *bus,
1356 const char *name_or_path,
1357 char **extension_image_paths,
1358 PortableFlags flags,
1359 PortableChange **changes,
1360 size_t *n_changes,
1361 sd_bus_error *error) {
1362
1363 _cleanup_(lookup_paths_free) LookupPaths paths = {};
1364 _cleanup_set_free_ Set *unit_files = NULL, *markers = NULL;
1365 _cleanup_closedir_ DIR *d = NULL;
1366 const char *where, *item;
1367 struct dirent *de;
1368 int ret = 0;
1369 int r;
1370
1371 assert(name_or_path);
1372
1373 r = lookup_paths_init(&paths, UNIT_FILE_SYSTEM, LOOKUP_PATHS_SPLIT_USR, NULL);
1374 if (r < 0)
1375 return r;
1376
1377 where = attached_path(&paths, flags);
1378
1379 d = opendir(where);
1380 if (!d) {
1381 if (errno == ENOENT)
1382 goto not_found;
1383
1384 return log_debug_errno(errno, "Failed to open '%s' directory: %m", where);
1385 }
1386
1387 FOREACH_DIRENT(de, d, return log_debug_errno(errno, "Failed to enumerate '%s' directory: %m", where)) {
1388 _cleanup_free_ char *marker = NULL;
1389 UnitFileState state;
1390
1391 if (!unit_name_is_valid(de->d_name, UNIT_NAME_ANY))
1392 continue;
1393
1394 /* Filter out duplicates */
1395 if (set_contains(unit_files, de->d_name))
1396 continue;
1397
1398 if (!IN_SET(de->d_type, DT_LNK, DT_REG))
1399 continue;
1400
1401 r = test_chroot_dropin(d, where, de->d_name, name_or_path, extension_image_paths, &marker);
1402 if (r < 0)
1403 return r;
1404 if (r == 0)
1405 continue;
1406
1407 r = unit_file_lookup_state(UNIT_FILE_SYSTEM, &paths, de->d_name, &state);
1408 if (r < 0)
1409 return log_debug_errno(r, "Failed to determine unit file state of '%s': %m", de->d_name);
1410 if (!IN_SET(state, UNIT_FILE_STATIC, UNIT_FILE_DISABLED, UNIT_FILE_LINKED, UNIT_FILE_RUNTIME, UNIT_FILE_LINKED_RUNTIME))
1411 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));
1412
1413 r = unit_file_is_active(bus, de->d_name, error);
1414 if (r < 0)
1415 return r;
1416 if (!FLAGS_SET(flags, PORTABLE_REATTACH) && r > 0)
1417 return sd_bus_error_setf(error, BUS_ERROR_UNIT_EXISTS, "Unit file '%s' is active, can't detach.", de->d_name);
1418
1419 r = set_put_strdup(&unit_files, de->d_name);
1420 if (r < 0)
1421 return log_debug_errno(r, "Failed to add unit name '%s' to set: %m", de->d_name);
1422
1423 for (const char *p = marker;;) {
1424 _cleanup_free_ char *image = NULL;
1425
1426 r = extract_first_word(&p, &image, ":", EXTRACT_UNESCAPE_SEPARATORS|EXTRACT_RETAIN_ESCAPE);
1427 if (r < 0)
1428 return log_debug_errno(r, "Failed to parse marker: %s", p);
1429 if (r == 0)
1430 break;
1431
1432 if (path_is_absolute(image) && !image_in_search_path(IMAGE_PORTABLE, NULL, image)) {
1433 r = set_ensure_consume(&markers, &path_hash_ops_free, TAKE_PTR(image));
1434 if (r < 0)
1435 return r;
1436 }
1437 }
1438 }
1439
1440 if (set_isempty(unit_files))
1441 goto not_found;
1442
1443 SET_FOREACH(item, unit_files) {
1444 _cleanup_free_ char *md = NULL;
1445 const char *suffix;
1446
1447 if (unlinkat(dirfd(d), item, 0) < 0) {
1448 log_debug_errno(errno, "Can't remove unit file %s/%s: %m", where, item);
1449
1450 if (errno != ENOENT && ret >= 0)
1451 ret = -errno;
1452 } else
1453 portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, item, NULL);
1454
1455 FOREACH_STRING(suffix, ".d/10-profile.conf", ".d/20-portable.conf") {
1456 _cleanup_free_ char *dropin = NULL;
1457
1458 dropin = strjoin(item, suffix);
1459 if (!dropin)
1460 return -ENOMEM;
1461
1462 if (unlinkat(dirfd(d), dropin, 0) < 0) {
1463 log_debug_errno(errno, "Can't remove drop-in %s/%s: %m", where, dropin);
1464
1465 if (errno != ENOENT && ret >= 0)
1466 ret = -errno;
1467 } else
1468 portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, dropin, NULL);
1469 }
1470
1471 md = strjoin(item, ".d");
1472 if (!md)
1473 return -ENOMEM;
1474
1475 if (unlinkat(dirfd(d), md, AT_REMOVEDIR) < 0) {
1476 log_debug_errno(errno, "Can't remove drop-in directory %s/%s: %m", where, md);
1477
1478 if (errno != ENOENT && ret >= 0)
1479 ret = -errno;
1480 } else
1481 portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, md, NULL);
1482 }
1483
1484 /* Now, also drop any image symlink, for images outside of the sarch path */
1485 SET_FOREACH(item, markers) {
1486 _cleanup_free_ char *sl = NULL;
1487 struct stat st;
1488
1489 r = image_symlink(item, flags, &sl);
1490 if (r < 0) {
1491 log_debug_errno(r, "Failed to determine image symlink for '%s', ignoring: %m", item);
1492 continue;
1493 }
1494
1495 if (lstat(sl, &st) < 0) {
1496 log_debug_errno(errno, "Failed to stat '%s', ignoring: %m", sl);
1497 continue;
1498 }
1499
1500 if (!S_ISLNK(st.st_mode)) {
1501 log_debug("Image '%s' is not a symlink, ignoring.", sl);
1502 continue;
1503 }
1504
1505 if (unlink(sl) < 0) {
1506 log_debug_errno(errno, "Can't remove image symlink '%s': %m", sl);
1507
1508 if (errno != ENOENT && ret >= 0)
1509 ret = -errno;
1510 } else
1511 portable_changes_add(changes, n_changes, PORTABLE_UNLINK, sl, NULL);
1512 }
1513
1514 /* Try to remove the unit file directory, if we can */
1515 if (rmdir(where) >= 0)
1516 portable_changes_add(changes, n_changes, PORTABLE_UNLINK, where, NULL);
1517
1518 return ret;
1519
1520 not_found:
1521 log_debug("No unit files associated with '%s' found. Image not attached?", name_or_path);
1522 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_UNIT, "No unit files associated with '%s' found. Image not attached?", name_or_path);
1523 }
1524
1525 static int portable_get_state_internal(
1526 sd_bus *bus,
1527 const char *name_or_path,
1528 PortableFlags flags,
1529 PortableState *ret,
1530 sd_bus_error *error) {
1531
1532 _cleanup_(lookup_paths_free) LookupPaths paths = {};
1533 bool found_enabled = false, found_running = false;
1534 _cleanup_set_free_ Set *unit_files = NULL;
1535 _cleanup_closedir_ DIR *d = NULL;
1536 const char *where;
1537 struct dirent *de;
1538 int r;
1539
1540 assert(name_or_path);
1541 assert(ret);
1542
1543 r = lookup_paths_init(&paths, UNIT_FILE_SYSTEM, LOOKUP_PATHS_SPLIT_USR, NULL);
1544 if (r < 0)
1545 return r;
1546
1547 where = attached_path(&paths, flags);
1548
1549 d = opendir(where);
1550 if (!d) {
1551 if (errno == ENOENT) {
1552 /* If the 'attached' directory doesn't exist at all, then we know for sure this image isn't attached. */
1553 *ret = PORTABLE_DETACHED;
1554 return 0;
1555 }
1556
1557 return log_debug_errno(errno, "Failed to open '%s' directory: %m", where);
1558 }
1559
1560 FOREACH_DIRENT(de, d, return log_debug_errno(errno, "Failed to enumerate '%s' directory: %m", where)) {
1561 UnitFileState state;
1562
1563 if (!unit_name_is_valid(de->d_name, UNIT_NAME_ANY))
1564 continue;
1565
1566 /* Filter out duplicates */
1567 if (set_contains(unit_files, de->d_name))
1568 continue;
1569
1570 if (!IN_SET(de->d_type, DT_LNK, DT_REG))
1571 continue;
1572
1573 r = test_chroot_dropin(d, where, de->d_name, name_or_path, NULL, NULL);
1574 if (r < 0)
1575 return r;
1576 if (r == 0)
1577 continue;
1578
1579 r = unit_file_lookup_state(UNIT_FILE_SYSTEM, &paths, de->d_name, &state);
1580 if (r < 0)
1581 return log_debug_errno(r, "Failed to determine unit file state of '%s': %m", de->d_name);
1582 if (!IN_SET(state, UNIT_FILE_STATIC, UNIT_FILE_DISABLED, UNIT_FILE_LINKED, UNIT_FILE_LINKED_RUNTIME))
1583 found_enabled = true;
1584
1585 r = unit_file_is_active(bus, de->d_name, error);
1586 if (r < 0)
1587 return r;
1588 if (r > 0)
1589 found_running = true;
1590
1591 r = set_put_strdup(&unit_files, de->d_name);
1592 if (r < 0)
1593 return log_debug_errno(r, "Failed to add unit name '%s' to set: %m", de->d_name);
1594 }
1595
1596 *ret = found_running ? (!set_isempty(unit_files) && (flags & PORTABLE_RUNTIME) ? PORTABLE_RUNNING_RUNTIME : PORTABLE_RUNNING) :
1597 found_enabled ? (flags & PORTABLE_RUNTIME ? PORTABLE_ENABLED_RUNTIME : PORTABLE_ENABLED) :
1598 !set_isempty(unit_files) ? (flags & PORTABLE_RUNTIME ? PORTABLE_ATTACHED_RUNTIME : PORTABLE_ATTACHED) : PORTABLE_DETACHED;
1599
1600 return 0;
1601 }
1602
1603 int portable_get_state(
1604 sd_bus *bus,
1605 const char *name_or_path,
1606 PortableFlags flags,
1607 PortableState *ret,
1608 sd_bus_error *error) {
1609
1610 PortableState state;
1611 int r;
1612
1613 assert(name_or_path);
1614 assert(ret);
1615
1616 /* We look for matching units twice: once in the regular directories, and once in the runtime directories — but
1617 * the latter only if we didn't find anything in the former. */
1618
1619 r = portable_get_state_internal(bus, name_or_path, flags & ~PORTABLE_RUNTIME, &state, error);
1620 if (r < 0)
1621 return r;
1622
1623 if (state == PORTABLE_DETACHED) {
1624 r = portable_get_state_internal(bus, name_or_path, flags | PORTABLE_RUNTIME, &state, error);
1625 if (r < 0)
1626 return r;
1627 }
1628
1629 *ret = state;
1630 return 0;
1631 }
1632
1633 int portable_get_profiles(char ***ret) {
1634 assert(ret);
1635
1636 return conf_files_list_nulstr(ret, NULL, NULL, CONF_FILES_DIRECTORY|CONF_FILES_BASENAME|CONF_FILES_FILTER_MASKED, profile_dirs);
1637 }
1638
1639 static const char* const portable_change_type_table[_PORTABLE_CHANGE_TYPE_MAX] = {
1640 [PORTABLE_COPY] = "copy",
1641 [PORTABLE_MKDIR] = "mkdir",
1642 [PORTABLE_SYMLINK] = "symlink",
1643 [PORTABLE_UNLINK] = "unlink",
1644 [PORTABLE_WRITE] = "write",
1645 };
1646
1647 DEFINE_STRING_TABLE_LOOKUP(portable_change_type, int);
1648
1649 static const char* const portable_state_table[_PORTABLE_STATE_MAX] = {
1650 [PORTABLE_DETACHED] = "detached",
1651 [PORTABLE_ATTACHED] = "attached",
1652 [PORTABLE_ATTACHED_RUNTIME] = "attached-runtime",
1653 [PORTABLE_ENABLED] = "enabled",
1654 [PORTABLE_ENABLED_RUNTIME] = "enabled-runtime",
1655 [PORTABLE_RUNNING] = "running",
1656 [PORTABLE_RUNNING_RUNTIME] = "running-runtime",
1657 };
1658
1659 DEFINE_STRING_TABLE_LOOKUP(portable_state, PortableState);