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