]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/portable/portable.c
Merge pull request #19941 from bluca/condition_os_release
[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 free(m);
91 return NULL;
92 }
93 }
94
95 strcpy(m->name, name);
96 m->fd = fd;
97
98 return TAKE_PTR(m);
99 }
100
101 PortableMetadata *portable_metadata_unref(PortableMetadata *i) {
102 if (!i)
103 return NULL;
104
105 safe_close(i->fd);
106 free(i->source);
107 free(i->image_path);
108
109 return mfree(i);
110 }
111
112 static int compare_metadata(PortableMetadata *const *x, PortableMetadata *const *y) {
113 return strcmp((*x)->name, (*y)->name);
114 }
115
116 int portable_metadata_hashmap_to_sorted_array(Hashmap *unit_files, PortableMetadata ***ret) {
117
118 _cleanup_free_ PortableMetadata **sorted = NULL;
119 PortableMetadata *item;
120 size_t k = 0;
121
122 sorted = new(PortableMetadata*, hashmap_size(unit_files));
123 if (!sorted)
124 return -ENOMEM;
125
126 HASHMAP_FOREACH(item, unit_files)
127 sorted[k++] = item;
128
129 assert(k == hashmap_size(unit_files));
130
131 typesafe_qsort(sorted, k, compare_metadata);
132
133 *ret = TAKE_PTR(sorted);
134 return 0;
135 }
136
137 static int send_item(
138 int socket_fd,
139 const char *name,
140 int fd) {
141
142 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control = {};
143 struct iovec iovec;
144 struct msghdr mh = {
145 .msg_control = &control,
146 .msg_controllen = sizeof(control),
147 .msg_iov = &iovec,
148 .msg_iovlen = 1,
149 };
150 struct cmsghdr *cmsg;
151 _cleanup_close_ int data_fd = -1;
152
153 assert(socket_fd >= 0);
154 assert(name);
155 assert(fd >= 0);
156
157 data_fd = copy_data_fd(fd);
158 if (data_fd < 0)
159 return data_fd;
160
161 cmsg = CMSG_FIRSTHDR(&mh);
162 cmsg->cmsg_level = SOL_SOCKET;
163 cmsg->cmsg_type = SCM_RIGHTS;
164 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
165 memcpy(CMSG_DATA(cmsg), &data_fd, sizeof(int));
166
167 iovec = IOVEC_MAKE_STRING(name);
168
169 if (sendmsg(socket_fd, &mh, MSG_NOSIGNAL) < 0)
170 return -errno;
171
172 return 0;
173 }
174
175 static int recv_item(
176 int socket_fd,
177 char **ret_name,
178 int *ret_fd) {
179
180 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control;
181 char buffer[PATH_MAX+2];
182 struct iovec iov = IOVEC_INIT(buffer, sizeof(buffer)-1);
183 struct msghdr mh = {
184 .msg_control = &control,
185 .msg_controllen = sizeof(control),
186 .msg_iov = &iov,
187 .msg_iovlen = 1,
188 };
189 struct cmsghdr *cmsg;
190 _cleanup_close_ int found_fd = -1;
191 char *copy;
192 ssize_t n;
193
194 assert(socket_fd >= 0);
195 assert(ret_name);
196 assert(ret_fd);
197
198 n = recvmsg_safe(socket_fd, &mh, MSG_CMSG_CLOEXEC);
199 if (n < 0)
200 return (int) n;
201
202 CMSG_FOREACH(cmsg, &mh) {
203 if (cmsg->cmsg_level == SOL_SOCKET &&
204 cmsg->cmsg_type == SCM_RIGHTS) {
205
206 if (cmsg->cmsg_len == CMSG_LEN(sizeof(int))) {
207 assert(found_fd < 0);
208 found_fd = *(int*) CMSG_DATA(cmsg);
209 break;
210 }
211
212 cmsg_close_all(&mh);
213 return -EIO;
214 }
215 }
216
217 buffer[n] = 0;
218
219 copy = strdup(buffer);
220 if (!copy)
221 return -ENOMEM;
222
223 *ret_name = copy;
224 *ret_fd = TAKE_FD(found_fd);
225
226 return 0;
227 }
228
229 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(portable_metadata_hash_ops, char, string_hash_func, string_compare_func,
230 PortableMetadata, portable_metadata_unref);
231
232 static int extract_now(
233 const char *where,
234 char **matches,
235 int socket_fd,
236 PortableMetadata **ret_os_release,
237 Hashmap **ret_unit_files) {
238
239 _cleanup_hashmap_free_ Hashmap *unit_files = NULL;
240 _cleanup_(portable_metadata_unrefp) PortableMetadata *os_release = NULL;
241 _cleanup_(lookup_paths_free) LookupPaths paths = {};
242 _cleanup_close_ int os_release_fd = -1;
243 _cleanup_free_ char *os_release_path = NULL;
244 char **i;
245 int r;
246
247 /* Extracts the metadata from a directory tree 'where'. Extracts two kinds of information: the /etc/os-release
248 * data, and all unit files matching the specified expression. Note that this function is called in two very
249 * different but also similar contexts. When the tool gets invoked on a directory tree, we'll process it
250 * directly, and in-process, and thus can return the requested data directly, via 'ret_os_release' and
251 * 'ret_unit_files'. However, if the tool is invoked on a raw disk image — which needs to be mounted first — we
252 * are invoked in a child process with private mounts and then need to send the collected data to our
253 * parent. To handle both cases in one call this function also gets a 'socket_fd' parameter, which when >= 0 is
254 * used to send the data to the parent. */
255
256 assert(where);
257
258 /* First, find /etc/os-release and send it upstream (or just save it). */
259 r = open_os_release(where, &os_release_path, &os_release_fd);
260 if (r < 0)
261 log_debug_errno(r, "Couldn't acquire os-release file, ignoring: %m");
262 else {
263 if (socket_fd >= 0) {
264 r = send_item(socket_fd, "/etc/os-release", os_release_fd);
265 if (r < 0)
266 return log_debug_errno(r, "Failed to send os-release file: %m");
267 }
268
269 if (ret_os_release) {
270 os_release = portable_metadata_new("/etc/os-release", NULL, os_release_fd);
271 if (!os_release)
272 return -ENOMEM;
273
274 os_release_fd = -1;
275 os_release->source = TAKE_PTR(os_release_path);
276 }
277 }
278
279 /* Then, send unit file data to the parent (or/and add it to the hashmap). For that we use our usual unit
280 * discovery logic. Note that we force looking inside of /lib/systemd/system/ for units too, as we mightbe
281 * compiled for a split-usr system but the image might be a legacy-usr one. */
282 r = lookup_paths_init(&paths, UNIT_FILE_SYSTEM, LOOKUP_PATHS_SPLIT_USR, where);
283 if (r < 0)
284 return log_debug_errno(r, "Failed to acquire lookup paths: %m");
285
286 unit_files = hashmap_new(&portable_metadata_hash_ops);
287 if (!unit_files)
288 return -ENOMEM;
289
290 STRV_FOREACH(i, paths.search_path) {
291 _cleanup_free_ char *resolved = NULL;
292 _cleanup_closedir_ DIR *d = NULL;
293 struct dirent *de;
294
295 r = chase_symlinks_and_opendir(*i, where, 0, &resolved, &d);
296 if (r < 0) {
297 log_debug_errno(r, "Failed to open unit path '%s', ignoring: %m", *i);
298 continue;
299 }
300
301 FOREACH_DIRENT(de, d, return log_debug_errno(errno, "Failed to read directory: %m")) {
302 _cleanup_(portable_metadata_unrefp) PortableMetadata *m = NULL;
303 _cleanup_close_ int fd = -1;
304
305 if (!unit_name_is_valid(de->d_name, UNIT_NAME_ANY))
306 continue;
307
308 if (!unit_match(de->d_name, matches))
309 continue;
310
311 /* Filter out duplicates */
312 if (hashmap_get(unit_files, de->d_name))
313 continue;
314
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, 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);
692
693 if (source) {
694 s = strdup(source);
695 if (!s)
696 return -ENOMEM;
697
698 path_simplify(s);
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 if (!IN_SET(de->d_type, DT_LNK, DT_REG))
1400 continue;
1401
1402 r = test_chroot_dropin(d, where, de->d_name, name_or_path, extension_image_paths, &marker);
1403 if (r < 0)
1404 return r;
1405 if (r == 0)
1406 continue;
1407
1408 r = unit_file_lookup_state(UNIT_FILE_SYSTEM, &paths, de->d_name, &state);
1409 if (r < 0)
1410 return log_debug_errno(r, "Failed to determine unit file state of '%s': %m", de->d_name);
1411 if (!IN_SET(state, UNIT_FILE_STATIC, UNIT_FILE_DISABLED, UNIT_FILE_LINKED, UNIT_FILE_RUNTIME, UNIT_FILE_LINKED_RUNTIME))
1412 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));
1413
1414 r = unit_file_is_active(bus, de->d_name, error);
1415 if (r < 0)
1416 return r;
1417 if (!FLAGS_SET(flags, PORTABLE_REATTACH) && r > 0)
1418 return sd_bus_error_setf(error, BUS_ERROR_UNIT_EXISTS, "Unit file '%s' is active, can't detach.", de->d_name);
1419
1420 r = set_put_strdup(&unit_files, de->d_name);
1421 if (r < 0)
1422 return log_debug_errno(r, "Failed to add unit name '%s' to set: %m", de->d_name);
1423
1424 for (const char *p = marker;;) {
1425 _cleanup_free_ char *image = NULL;
1426
1427 r = extract_first_word(&p, &image, ":", EXTRACT_UNESCAPE_SEPARATORS|EXTRACT_RETAIN_ESCAPE);
1428 if (r < 0)
1429 return log_debug_errno(r, "Failed to parse marker: %s", p);
1430 if (r == 0)
1431 break;
1432
1433 if (path_is_absolute(image) && !image_in_search_path(IMAGE_PORTABLE, NULL, image)) {
1434 r = set_ensure_consume(&markers, &path_hash_ops_free, TAKE_PTR(image));
1435 if (r < 0)
1436 return r;
1437 }
1438 }
1439 }
1440
1441 if (set_isempty(unit_files))
1442 goto not_found;
1443
1444 SET_FOREACH(item, unit_files) {
1445 _cleanup_free_ char *md = NULL;
1446 const char *suffix;
1447
1448 if (unlinkat(dirfd(d), item, 0) < 0) {
1449 log_debug_errno(errno, "Can't remove unit file %s/%s: %m", where, item);
1450
1451 if (errno != ENOENT && ret >= 0)
1452 ret = -errno;
1453 } else
1454 portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, item, NULL);
1455
1456 FOREACH_STRING(suffix, ".d/10-profile.conf", ".d/20-portable.conf") {
1457 _cleanup_free_ char *dropin = NULL;
1458
1459 dropin = strjoin(item, suffix);
1460 if (!dropin)
1461 return -ENOMEM;
1462
1463 if (unlinkat(dirfd(d), dropin, 0) < 0) {
1464 log_debug_errno(errno, "Can't remove drop-in %s/%s: %m", where, dropin);
1465
1466 if (errno != ENOENT && ret >= 0)
1467 ret = -errno;
1468 } else
1469 portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, dropin, NULL);
1470 }
1471
1472 md = strjoin(item, ".d");
1473 if (!md)
1474 return -ENOMEM;
1475
1476 if (unlinkat(dirfd(d), md, AT_REMOVEDIR) < 0) {
1477 log_debug_errno(errno, "Can't remove drop-in directory %s/%s: %m", where, md);
1478
1479 if (errno != ENOENT && ret >= 0)
1480 ret = -errno;
1481 } else
1482 portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, md, NULL);
1483 }
1484
1485 /* Now, also drop any image symlink, for images outside of the sarch path */
1486 SET_FOREACH(item, markers) {
1487 _cleanup_free_ char *sl = NULL;
1488 struct stat st;
1489
1490 r = image_symlink(item, flags, &sl);
1491 if (r < 0) {
1492 log_debug_errno(r, "Failed to determine image symlink for '%s', ignoring: %m", item);
1493 continue;
1494 }
1495
1496 if (lstat(sl, &st) < 0) {
1497 log_debug_errno(errno, "Failed to stat '%s', ignoring: %m", sl);
1498 continue;
1499 }
1500
1501 if (!S_ISLNK(st.st_mode)) {
1502 log_debug("Image '%s' is not a symlink, ignoring.", sl);
1503 continue;
1504 }
1505
1506 if (unlink(sl) < 0) {
1507 log_debug_errno(errno, "Can't remove image symlink '%s': %m", sl);
1508
1509 if (errno != ENOENT && ret >= 0)
1510 ret = -errno;
1511 } else
1512 portable_changes_add(changes, n_changes, PORTABLE_UNLINK, sl, NULL);
1513 }
1514
1515 /* Try to remove the unit file directory, if we can */
1516 if (rmdir(where) >= 0)
1517 portable_changes_add(changes, n_changes, PORTABLE_UNLINK, where, NULL);
1518
1519 return ret;
1520
1521 not_found:
1522 log_debug("No unit files associated with '%s' found. Image not attached?", name_or_path);
1523 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_UNIT, "No unit files associated with '%s' found. Image not attached?", name_or_path);
1524 }
1525
1526 static int portable_get_state_internal(
1527 sd_bus *bus,
1528 const char *name_or_path,
1529 PortableFlags flags,
1530 PortableState *ret,
1531 sd_bus_error *error) {
1532
1533 _cleanup_(lookup_paths_free) LookupPaths paths = {};
1534 bool found_enabled = false, found_running = false;
1535 _cleanup_set_free_ Set *unit_files = NULL;
1536 _cleanup_closedir_ DIR *d = NULL;
1537 const char *where;
1538 struct dirent *de;
1539 int r;
1540
1541 assert(name_or_path);
1542 assert(ret);
1543
1544 r = lookup_paths_init(&paths, UNIT_FILE_SYSTEM, LOOKUP_PATHS_SPLIT_USR, NULL);
1545 if (r < 0)
1546 return r;
1547
1548 where = attached_path(&paths, flags);
1549
1550 d = opendir(where);
1551 if (!d) {
1552 if (errno == ENOENT) {
1553 /* If the 'attached' directory doesn't exist at all, then we know for sure this image isn't attached. */
1554 *ret = PORTABLE_DETACHED;
1555 return 0;
1556 }
1557
1558 return log_debug_errno(errno, "Failed to open '%s' directory: %m", where);
1559 }
1560
1561 FOREACH_DIRENT(de, d, return log_debug_errno(errno, "Failed to enumerate '%s' directory: %m", where)) {
1562 UnitFileState state;
1563
1564 if (!unit_name_is_valid(de->d_name, UNIT_NAME_ANY))
1565 continue;
1566
1567 /* Filter out duplicates */
1568 if (set_contains(unit_files, de->d_name))
1569 continue;
1570
1571 if (!IN_SET(de->d_type, DT_LNK, DT_REG))
1572 continue;
1573
1574 r = test_chroot_dropin(d, where, de->d_name, name_or_path, NULL, NULL);
1575 if (r < 0)
1576 return r;
1577 if (r == 0)
1578 continue;
1579
1580 r = unit_file_lookup_state(UNIT_FILE_SYSTEM, &paths, de->d_name, &state);
1581 if (r < 0)
1582 return log_debug_errno(r, "Failed to determine unit file state of '%s': %m", de->d_name);
1583 if (!IN_SET(state, UNIT_FILE_STATIC, UNIT_FILE_DISABLED, UNIT_FILE_LINKED, UNIT_FILE_LINKED_RUNTIME))
1584 found_enabled = true;
1585
1586 r = unit_file_is_active(bus, de->d_name, error);
1587 if (r < 0)
1588 return r;
1589 if (r > 0)
1590 found_running = true;
1591
1592 r = set_put_strdup(&unit_files, de->d_name);
1593 if (r < 0)
1594 return log_debug_errno(r, "Failed to add unit name '%s' to set: %m", de->d_name);
1595 }
1596
1597 *ret = found_running ? (!set_isempty(unit_files) && (flags & PORTABLE_RUNTIME) ? PORTABLE_RUNNING_RUNTIME : PORTABLE_RUNNING) :
1598 found_enabled ? (flags & PORTABLE_RUNTIME ? PORTABLE_ENABLED_RUNTIME : PORTABLE_ENABLED) :
1599 !set_isempty(unit_files) ? (flags & PORTABLE_RUNTIME ? PORTABLE_ATTACHED_RUNTIME : PORTABLE_ATTACHED) : PORTABLE_DETACHED;
1600
1601 return 0;
1602 }
1603
1604 int portable_get_state(
1605 sd_bus *bus,
1606 const char *name_or_path,
1607 PortableFlags flags,
1608 PortableState *ret,
1609 sd_bus_error *error) {
1610
1611 PortableState state;
1612 int r;
1613
1614 assert(name_or_path);
1615 assert(ret);
1616
1617 /* We look for matching units twice: once in the regular directories, and once in the runtime directories — but
1618 * the latter only if we didn't find anything in the former. */
1619
1620 r = portable_get_state_internal(bus, name_or_path, flags & ~PORTABLE_RUNTIME, &state, error);
1621 if (r < 0)
1622 return r;
1623
1624 if (state == PORTABLE_DETACHED) {
1625 r = portable_get_state_internal(bus, name_or_path, flags | PORTABLE_RUNTIME, &state, error);
1626 if (r < 0)
1627 return r;
1628 }
1629
1630 *ret = state;
1631 return 0;
1632 }
1633
1634 int portable_get_profiles(char ***ret) {
1635 assert(ret);
1636
1637 return conf_files_list_nulstr(ret, NULL, NULL, CONF_FILES_DIRECTORY|CONF_FILES_BASENAME|CONF_FILES_FILTER_MASKED, profile_dirs);
1638 }
1639
1640 static const char* const portable_change_type_table[_PORTABLE_CHANGE_TYPE_MAX] = {
1641 [PORTABLE_COPY] = "copy",
1642 [PORTABLE_MKDIR] = "mkdir",
1643 [PORTABLE_SYMLINK] = "symlink",
1644 [PORTABLE_UNLINK] = "unlink",
1645 [PORTABLE_WRITE] = "write",
1646 };
1647
1648 DEFINE_STRING_TABLE_LOOKUP(portable_change_type, int);
1649
1650 static const char* const portable_state_table[_PORTABLE_STATE_MAX] = {
1651 [PORTABLE_DETACHED] = "detached",
1652 [PORTABLE_ATTACHED] = "attached",
1653 [PORTABLE_ATTACHED_RUNTIME] = "attached-runtime",
1654 [PORTABLE_ENABLED] = "enabled",
1655 [PORTABLE_ENABLED_RUNTIME] = "enabled-runtime",
1656 [PORTABLE_RUNNING] = "running",
1657 [PORTABLE_RUNNING_RUNTIME] = "running-runtime",
1658 };
1659
1660 DEFINE_STRING_TABLE_LOOKUP(portable_state, PortableState);