Debian Codegraph @

src/storage/storage-fs.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <fnmatch.h>
5 #include <sys/mount.h>
6 #include <sys/stat.h>
7 #include <unistd.h>
8
9 #include "sd-device.h"
10 #include "sd-json.h"
11
12 #include "alloc-util.h"
13 #include "build.h"
14 #include "bus-polkit.h"
15 #include "chase.h"
16 #include "chattr-util.h"
17 #include "device-private.h"
18 #include "device-util.h"
19 #include "errno-util.h"
20 #include "fd-util.h"
21 #include "format-table.h"
22 #include "fs-util.h"
23 #include "hashmap.h"
24 #include "help-util.h"
25 #include "log.h"
26 #include "main-func.h"
27 #include "mount-util.h"
28 #include "options.h"
29 #include "path-lookup.h"
30 #include "path-util.h"
31 #include "recurse-dir.h"
32 #include "runtime-scope.h"
33 #include "stat-util.h"
34 #include "storage-util.h"
35 #include "string-table.h"
36 #include "tmpfile-util.h"
37 #include "uid-classification.h"
38 #include "varlink-io.systemd.StorageProvider.h"
39 #include "varlink-util.h"
40
41 static RuntimeScope arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
42
43 /* For now we maintain a simple, compiled-in list of templates. One of those days we might want to move these
44 * into configurable drop-in files on disk. */
45 typedef enum Template {
46 TEMPLATE_SPARSE_FILE,
47 TEMPLATE_ALLOCATED_FILE,
48 TEMPLATE_DIRECTORY,
49 TEMPLATE_SUBVOLUME,
50 _TEMPLATE_MAX,
51 _TEMPLATE_INVALID = -EINVAL,
52 } Template;
53
54 static const char *template_table[_TEMPLATE_MAX] = {
55 [TEMPLATE_SPARSE_FILE] = "sparse-file",
56 [TEMPLATE_ALLOCATED_FILE] = "allocated-file",
57 [TEMPLATE_DIRECTORY] = "directory",
58 [TEMPLATE_SUBVOLUME] = "subvolume",
59 };
60
61 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(template, Template);
62
63 static VolumeType volume_type_from_template(Template t) {
64 switch (t) {
65
66 case TEMPLATE_SPARSE_FILE:
67 case TEMPLATE_ALLOCATED_FILE:
68 return VOLUME_REG;
69
70 case TEMPLATE_DIRECTORY:
71 case TEMPLATE_SUBVOLUME:
72 return VOLUME_DIR;
73
74 default:
75 return _VOLUME_TYPE_INVALID;
76 }
77 }
78
79 static int open_storage_dir(void) {
80 int r;
81
82 _cleanup_free_ char *state_dir = NULL;
83 r = state_directory_generic(arg_runtime_scope, /* suffix= */ NULL, &state_dir);
84 if (r < 0)
85 return log_error_errno(r, "Failed to get state directory path: %m");
86
87 _cleanup_close_ int state_fd = chase_and_open(state_dir, /* root= */ NULL, CHASE_TRIGGER_AUTOFS|CHASE_MKDIR_0755|CHASE_MUST_BE_DIRECTORY, O_CLOEXEC|O_CREAT|O_DIRECTORY, /* ret_path= */ NULL);
88 if (state_fd < 0)
89 return log_error_errno(state_fd, "Failed to open '%s': %m", state_dir);
90
91 /* First we try to open the storage directory. If it exists this will work and we are happy. If we
92 * get ENOENT we'll try to create it. If that works, great. If we get EEXIST we'll try to reopen it
93 * again, to deal with other instances of ourselves racing with us. We only do this exactly once
94 * though, under the assumption that the dir is never removed, only created during runtime. */
95 _cleanup_close_ int storage_fd = chase_and_openat(XAT_FDROOT, state_fd, "storage", CHASE_TRIGGER_AUTOFS|CHASE_MUST_BE_DIRECTORY, O_CLOEXEC|O_DIRECTORY, /* ret_path= */ NULL);
96 if (storage_fd == -ENOENT) {
97 storage_fd = xopenat_full(state_fd, "storage", O_EXCL|O_CREAT|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW, XO_LABEL|XO_SUBVOLUME, 0700);
98 if (storage_fd == -EEXIST)
99 storage_fd = chase_and_openat(XAT_FDROOT, state_fd, "storage", CHASE_TRIGGER_AUTOFS|CHASE_MUST_BE_DIRECTORY, O_CLOEXEC|O_DIRECTORY, /* ret_path= */ NULL);
100 }
101 if (storage_fd < 0)
102 return log_error_errno(storage_fd, "Failed to open '%s/storage/': %m", state_dir);
103
104 return TAKE_FD(storage_fd);
105 }
106
107 static int vl_method_list_volumes(
108 sd_varlink *link,
109 sd_json_variant *parameters,
110 sd_varlink_method_flags_t flags,
111 void *userdata) {
112
113 int r;
114
115 assert(link);
116 assert(FLAGS_SET(flags, SD_VARLINK_METHOD_MORE));
117
118 struct {
119 const char *match_name;
120 } p = {};
121
122 static const sd_json_dispatch_field dispatch_table[] = {
123 { "matchName", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, voffsetof(p, match_name), 0 },
124 {}
125 };
126
127 r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
128 if (r != 0)
129 return r;
130
131 _cleanup_close_ int fd = open_storage_dir();
132 if (fd < 0)
133 return fd;
134
135 _cleanup_free_ DirectoryEntries *dentries = NULL;
136 r = readdir_all(fd, RECURSE_DIR_SORT, &dentries);
137 if (r < 0)
138 return r;
139
140 r = sd_varlink_set_sentinel(link, "io.systemd.StorageProvider.NoSuchVolume");
141 if (r < 0)
142 return r;
143
144 FOREACH_ARRAY(dp, dentries->entries, dentries->n_entries) {
145 struct dirent *d = *dp;
146
147 if (!IN_SET(d->d_type, DT_REG, DT_DIR, DT_LNK, DT_BLK, DT_UNKNOWN))
148 continue;
149
150 const char *e = endswith(d->d_name, ".volume");
151 if (!e)
152 continue;
153
154 _cleanup_free_ char *n = strndup(d->d_name, e - d->d_name);
155 if (!n)
156 return log_oom_debug();
157
158 if (!storage_volume_name_is_valid(n))
159 continue;
160
161 if (p.match_name && fnmatch(p.match_name, n, FNM_NOESCAPE) != 0)
162 continue;
163
164 _cleanup_close_ int pin_fd = -EBADF;
165 r = chaseat(XAT_FDROOT, fd, d->d_name, CHASE_TRIGGER_AUTOFS, /* ret_path= */ NULL, &pin_fd);
166 if (r < 0) {
167 log_debug_errno(r, "Failed to stat() '%s' in storage directory, ignoring: %m", d->d_name);
168 continue;
169 }
170
171 struct stat st;
172 if (fstat(pin_fd, &st) < 0)
173 return log_debug_errno(errno, "Failed to stat() '%s' in storage directory: %m", d->d_name);
174
175 uint64_t size = UINT64_MAX, used = UINT64_MAX;
176 bool ro = false;
177
178 switch (st.st_mode & S_IFMT) {
179 case S_IFREG:
180 ro = (st.st_mode & 0222) == 0;
181 size = st.st_size;
182 used = (uint64_t) st.st_blocks * UINT64_C(512);
183 break;
184
185 case S_IFDIR:
186 r = fd_is_read_only_fs(pin_fd);
187 if (r < 0)
188 log_debug_errno(r, "Failed to determine if '%s' is read-only, ignoring", d->d_name);
189 else
190 ro = r > 0;
191 break;
192
193 case S_IFBLK: {
194 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
195
196 r = sd_device_new_from_stat_rdev(&dev, &st);
197 if (r < 0)
198 log_debug_errno(r, "Failed to acquire device for '%s', ignoring: %m", d->d_name);
199 else {
200 r = device_get_sysattr_bool(dev, "ro");
201 if (r < 0)
202 log_device_debug_errno(dev, r, "Failed to get read/only state of '%s', ignoring: %m", d->d_name);
203 else
204 ro = r > 0;
205
206 r = device_get_sysattr_u64(dev, "size", &size);
207 if (r < 0)
208 log_device_debug_errno(dev, r, "Failed to acquire size of device '%s', ignoring: %m", d->d_name);
209 else
210 /* the 'size' sysattr is always in multiples of 512, even on 4K sector block devices! */
211 assert_se(MUL_ASSIGN_SAFE(&size, 512)); /* Overflow check for coverity */
212 }
213
214 break;
215 }
216
217 default:
218 log_debug("Volume of unexpected inode type, ignoring: %s", d->d_name);
219 continue;
220 }
221
222 r = sd_varlink_replybo(
223 link,
224 SD_JSON_BUILD_PAIR_STRING("name", n),
225 SD_JSON_BUILD_PAIR_STRING("type", inode_type_to_string(st.st_mode)),
226 SD_JSON_BUILD_PAIR_BOOLEAN("readOnly", ro),
227 SD_JSON_BUILD_PAIR_CONDITION(size != UINT64_MAX, "sizeBytes", SD_JSON_BUILD_UNSIGNED(size)),
228 SD_JSON_BUILD_PAIR_CONDITION(used != UINT64_MAX, "usedBytes", SD_JSON_BUILD_UNSIGNED(used)));
229 if (r < 0)
230 return r;
231 }
232
233 return 0;
234 }
235
236 static int vl_method_list_templates(
237 sd_varlink *link,
238 sd_json_variant *parameters,
239 sd_varlink_method_flags_t flags,
240 void *userdata) {
241
242 int r;
243
244 assert(link);
245 assert(FLAGS_SET(flags, SD_VARLINK_METHOD_MORE));
246
247 struct {
248 const char *match_name;
249 } p = {};
250
251 static const sd_json_dispatch_field dispatch_table[] = {
252 { "matchName", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, voffsetof(p, match_name), 0 },
253 {}
254 };
255
256 r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
257 if (r != 0)
258 return r;
259
260 r = sd_varlink_set_sentinel(link, "io.systemd.StorageProvider.NoSuchTemplate");
261 if (r < 0)
262 return r;
263
264 for (Template t = 0; t < _TEMPLATE_MAX; t++) {
265 const char *n = template_to_string(t);
266
267 if (p.match_name && fnmatch(p.match_name, n, FNM_NOESCAPE) != 0)
268 continue;
269
270 r = sd_varlink_replybo(
271 link,
272 SD_JSON_BUILD_PAIR_STRING("name", n),
273 SD_JSON_BUILD_PAIR_STRING("type", volume_type_to_string(volume_type_from_template(t))));
274 if (r < 0)
275 return r;
276 }
277
278 return 0;
279 }
280
281 static int create_volume_dir(
282 int storage_fd,
283 const char *filename,
284 Template t) {
285
286 int r;
287
288 assert(storage_fd >= 0);
289 assert(filename);
290
291 XOpenFlags xopen_flags;
292 switch (t) {
293
294 case TEMPLATE_DIRECTORY:
295 xopen_flags = 0;
296 break;
297
298 case TEMPLATE_SUBVOLUME:
299 xopen_flags = XO_SUBVOLUME;
300 break;
301
302 default:
303 return -ENOMEDIUM; /* Recognizable error for: template doesn't apply here */
304 }
305
306 _cleanup_free_ char *tf = NULL;
307 r = tempfn_random(filename, /* extra= */ NULL, &tf);
308 if (r < 0)
309 return r;
310
311 _cleanup_close_ int volume_fd = xopenat_full(storage_fd, tf, O_CREAT|O_EXCL|O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW, xopen_flags, 0700);
312 if (volume_fd < 0)
313 return volume_fd;
314
315 _cleanup_close_ int root_fd = xopenat_full(volume_fd, "root", O_CREAT|O_EXCL|O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW, xopen_flags, 0755);
316 if (root_fd < 0) {
317 r = root_fd;
318 goto fail;
319 }
320
321 r = RET_NERRNO(fchown(root_fd, FOREIGN_UID_MIN, FOREIGN_UID_MIN));
322 if (r < 0)
323 goto fail;
324
325 r = rename_noreplace(storage_fd, tf, storage_fd, filename);
326 if (r < 0)
327 goto fail;
328
329 return TAKE_FD(root_fd);
330
331 fail:
332 if (root_fd >= 0) {
333 assert(volume_fd >= 0);
334 root_fd = safe_close(root_fd);
335 (void) unlinkat(volume_fd, "root", AT_REMOVEDIR);
336 }
337
338 if (volume_fd >= 0) {
339 volume_fd = safe_close(volume_fd);
340 (void) unlinkat(storage_fd, tf, AT_REMOVEDIR);
341 }
342
343 return r;
344 }
345
346 static int create_volume_reg(
347 int storage_fd,
348 const char *filename,
349 Template t,
350 uint64_t create_size) {
351 int r;
352
353 assert(storage_fd >= 0);
354 assert(filename);
355
356 bool sparse;
357 switch (t) {
358
359 case TEMPLATE_SPARSE_FILE:
360 sparse = true;
361 break;
362
363 case TEMPLATE_ALLOCATED_FILE:
364 sparse = false;
365 break;
366
367 default:
368 return -ENOMEDIUM; /* Recognizable error for: template doesn't apply here */
369 }
370
371 _cleanup_free_ char *tf = NULL;
372 _cleanup_close_ int fd = open_tmpfile_linkable_at(storage_fd, filename, O_RDWR|O_CLOEXEC, &tf);
373 if (fd < 0)
374 return fd;
375
376 CLEANUP_TMPFILE_AT(storage_fd, tf);
377
378 r = chattr_fd(fd, FS_NOCOW_FL, FS_NOCOW_FL);
379 if (r < 0 && !ERRNO_IS_IOCTL_NOT_SUPPORTED(r))
380 return r;
381
382 if (create_size > 0) {
383 if (sparse)
384 r = RET_NERRNO(ftruncate(fd, create_size));
385 else
386 r = RET_NERRNO(fallocate(fd, /* mode= */ 0, /* offset= */ 0, create_size));
387 if (r < 0)
388 return r;
389 }
390
391 r = RET_NERRNO(fchmod(fd, 0600));
392 if (r < 0)
393 return r;
394
395 r = link_tmpfile_at(fd, storage_fd, tf, filename, /* flags= */ 0);
396 if (r < 0)
397 return r;
398
399 tf = mfree(tf); /* disarm clean-up */
400
401 return TAKE_FD(fd);
402 }
403
404 static int vl_method_acquire(
405 sd_varlink *link,
406 sd_json_variant *parameters,
407 sd_varlink_method_flags_t flags,
408 void *userdata) {
409
410 Hashmap **polkit_registry = ASSERT_PTR(userdata);
411 int r;
412
413 assert(link);
414
415 struct {
416 const char *name;
417 CreateMode create_mode;
418 const char *template;
419 int read_only;
420 VolumeType request_as;
421 uint64_t create_size;
422 } p = {
423 .create_mode = CREATE_ANY,
424 .read_only = -1,
425 .request_as = _VOLUME_TYPE_INVALID,
426 .create_size = UINT64_MAX,
427 };
428
429 static const sd_json_dispatch_field dispatch_table[] = {
430 { "name", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, voffsetof(p, name), SD_JSON_MANDATORY },
431 { "createMode", SD_JSON_VARIANT_STRING, json_dispatch_create_mode, voffsetof(p, create_mode), 0 },
432 { "template", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, voffsetof(p, template), 0 },
433 { "readOnly", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_tristate, voffsetof(p, read_only), 0 },
434 { "requestAs", SD_JSON_VARIANT_STRING, json_dispatch_volume_type, voffsetof(p, request_as), 0 },
435 { "createSizeBytes", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64, voffsetof(p, create_size), 0 },
436 VARLINK_DISPATCH_POLKIT_FIELD,
437 {}
438 };
439
440 r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
441 if (r != 0)
442 return r;
443
444 if (!storage_volume_name_is_valid(p.name))
445 return sd_varlink_error_invalid_parameter_name(link, "name");
446
447 if (!IN_SET(p.create_mode, CREATE_ANY, CREATE_OPEN, CREATE_NEW))
448 return sd_varlink_error(link, "io.systemd.StorageProvider.CreateNotSupported", NULL);
449
450 /* off_t is signed, hence refuse overly long requests */
451 if (p.create_size != UINT64_MAX && p.create_size > INT64_MAX)
452 return sd_varlink_error_invalid_parameter_name(link, "createSizeBytes");
453
454 Template t = _TEMPLATE_INVALID;
455 if (!isempty(p.template)) {
456 if (!storage_template_name_is_valid(p.template))
457 return sd_varlink_error_invalid_parameter_name(link, "template");
458
459 t = template_from_string(p.template);
460 if (t < 0)
461 return sd_varlink_error(link, "io.systemd.StorageProvider.NoSuchTemplate", NULL);
462 }
463
464 if (p.read_only > 0) {
465 if (p.create_mode == CREATE_NEW)
466 return sd_varlink_error_invalid_parameter_name(link, "readOnly");
467
468 p.create_mode = CREATE_OPEN;
469 }
470
471 /* Add a suffix so that we are never attempted to open a temporary file assuming it was a valid
472 * volume. */
473 _cleanup_free_ char *filename = strjoin(p.name, ".volume");
474 if (!filename)
475 return log_oom_debug();
476
477 if (!filename_is_valid(filename))
478 return sd_varlink_error_invalid_parameter_name(link, "name");
479
480 if (arg_runtime_scope != RUNTIME_SCOPE_USER) {
481 const char *details[] = {
482 "name", p.name,
483 NULL
484 };
485
486 r = varlink_verify_polkit_async(
487 link,
488 /* bus= */ NULL,
489 "io.systemd.storage.fs.acquire",
490 details,
491 polkit_registry);
492 if (r <= 0)
493 return r;
494 }
495
496 _cleanup_close_ int storage_fd = open_storage_dir();
497 if (storage_fd < 0)
498 return storage_fd;
499
500 _cleanup_close_ int pin_fd = -EBADF, real_fd = -EBADF;
501 r = chaseat(XAT_FDROOT, storage_fd, filename, CHASE_TRIGGER_AUTOFS, /* ret_path= */ NULL, &pin_fd);
502 if (r < 0) {
503 if (r != -ENOENT)
504 return r;
505 if (p.create_mode == CREATE_OPEN || p.read_only > 0)
506 return sd_varlink_error(link, "io.systemd.StorageProvider.NoSuchVolume", NULL);
507
508 /* Doesn't exist yet: create it now */
509
510 if (p.request_as < 0) /* Make a choice: pick default type */
511 p.request_as = t < 0 ? VOLUME_DIR : volume_type_from_template(t);
512
513 /* Try to create the volume */
514 switch (p.request_as) {
515
516 case VOLUME_DIR: {
517
518 if (t < 0) /* Make a choice: pick default template */
519 t = TEMPLATE_SUBVOLUME;
520
521 real_fd = create_volume_dir(storage_fd, filename, t);
522 break;
523 }
524
525 case VOLUME_REG: {
526 if (p.create_size == UINT64_MAX)
527 return sd_varlink_error(link, "io.systemd.StorageProvider.CreateSizeRequired", NULL);
528
529 if (t < 0) /* Make a choice: pick default template */
530 t = TEMPLATE_SPARSE_FILE;
531
532 real_fd = create_volume_reg(storage_fd, filename, t, p.create_size);
533 break;
534 }
535
536 case VOLUME_BLK:
537 /* We don't support creating block devices, we only support if they are symlinked
538 * into the storage directory. */
539 return sd_varlink_error(link, "io.systemd.StorageProvider.CreateNotSupported", NULL);
540
541 default:
542 assert_not_reached();
543 }
544
545 if (real_fd == -ENOMEDIUM)
546 return sd_varlink_error(link, "io.systemd.StorageProvider.BadTemplate", NULL);
547 if (real_fd == -EEXIST) {
548 if (p.create_mode == CREATE_NEW)
549 return sd_varlink_error(link, "io.systemd.StorageProvider.VolumeExists", NULL);
550
551 /* If we failed to open the volume and reached this point, then the volume already
552 * exists by now (i.e. we ran into a race). In that case, try to pin it a second time
553 * (but only once, let's never loop around this). */
554 r = chaseat(XAT_FDROOT, storage_fd, filename, CHASE_TRIGGER_AUTOFS, /* ret_path= */ NULL, &pin_fd);
555 if (r < 0)
556 return r;
557 } else if (real_fd < 0)
558 return real_fd;
559
560 } else if (p.create_mode == CREATE_NEW)
561 return sd_varlink_error(link, "io.systemd.StorageProvider.VolumeExists", NULL);
562
563 /* At this point, we either already opened the real fd, or we managed to pin it (but not both) */
564 assert((real_fd >= 0) != (pin_fd >= 0));
565
566 /* Let's first settle the volume type */
567 struct stat st;
568 if (fstat(real_fd >= 0 ? real_fd : pin_fd, &st) < 0)
569 return -errno;
570
571 if (p.request_as == VOLUME_REG) {
572 /* First, check for the other supported types and generate a nice error */
573 if (IN_SET(st.st_mode & S_IFMT, S_IFDIR, S_IFBLK))
574 return sd_varlink_error(link, "io.systemd.StorageProvider.WrongType", NULL);
575
576 /* Second verify cover all other types */
577 r = stat_verify_regular(&st);
578 if (r < 0)
579 return r;
580 } else if (p.request_as == VOLUME_DIR) {
581 if (IN_SET(st.st_mode & S_IFMT, S_IFREG, S_IFBLK))
582 return sd_varlink_error(link, "io.systemd.StorageProvider.WrongType", NULL);
583
584 r = stat_verify_directory(&st);
585 if (r < 0)
586 return r;
587 } else if (p.request_as == VOLUME_BLK) {
588 if (IN_SET(st.st_mode & S_IFMT, S_IFREG, S_IFDIR))
589 return sd_varlink_error(link, "io.systemd.StorageProvider.WrongType", NULL);
590
591 r = stat_verify_block(&st);
592 if (r < 0)
593 return r;
594
595 } else if (S_ISREG(st.st_mode))
596 p.request_as = VOLUME_REG;
597 else if (S_ISDIR(st.st_mode))
598 p.request_as = VOLUME_DIR;
599 else if (S_ISBLK(st.st_mode))
600 p.request_as = VOLUME_BLK;
601 else
602 return log_debug_errno(SYNTHETIC_ERRNO(EBADF), "Unexpected inode type, refusing.");
603
604 /* Let's now acquire a real fd for the pinned fd, if we still need to */
605 if (real_fd < 0) {
606 assert(pin_fd >= 0);
607
608 XOpenFlags xopen_flags =
609 (p.read_only < 0 && !S_ISDIR(st.st_mode) ? XO_AUTO_RW_RO : 0);
610 int open_flags =
611 (p.read_only < 0 ? 0 : (p.read_only > 0 || S_ISDIR(st.st_mode) ? O_RDONLY : O_RDWR));
612
613 const char *subdir = NULL;
614 if (p.request_as == VOLUME_DIR) {
615 /* We place the root of the directory tree one level down, to separate ownership of
616 * the inode: the upper inode is owned by the host, the lower one by the volume. This
617 * matters so that the host one can be owned by the host's root, and the volume one
618 * by the foreign UID range. */
619 subdir = "root";
620 open_flags |= O_DIRECTORY|O_NOFOLLOW;
621 }
622
623 real_fd = xopenat_full(pin_fd, subdir, open_flags|O_CLOEXEC, xopen_flags, /* mode= */ MODE_INVALID);
624 if (real_fd < 0)
625 return log_debug_errno(real_fd, "Failed to reopen volume fd for '%s': %m", filename);
626
627 /* In directory mode we might be looking at a different inode node, refresh the stat data */
628 if (p.request_as == VOLUME_DIR && fstat(real_fd, &st) < 0)
629 return -errno;
630 }
631
632 assert(real_fd >= 0);
633
634 bool ro;
635 switch (p.request_as) {
636
637 case VOLUME_REG:
638 case VOLUME_BLK: {
639 assert(IN_SET(st.st_mode & S_IFMT, S_IFREG, S_IFBLK));
640
641 int open_flags = fcntl(real_fd, F_GETFL, 0);
642 if (open_flags < 0)
643 return -errno;
644
645 ro = (open_flags & O_ACCMODE_STRICT) == O_RDONLY;
646 break;
647 }
648
649 case VOLUME_DIR: {
650 assert(S_ISDIR(st.st_mode));
651
652 if (!uid_is_foreign(st.st_uid) ||
653 !gid_is_foreign(st.st_gid))
654 return log_debug_errno(SYNTHETIC_ERRNO(EPERM), "Storage directory not owned by foreign UID/GID range.");
655
656 /* Let's now generate a new mount for the directory tree, where propagation is disabled, and the
657 * flags are all set to good defaults */
658 _cleanup_close_ int mount_fd = open_tree_attr_with_fallback(
659 real_fd,
660 /* path= */ NULL,
661 OPEN_TREE_CLONE|OPEN_TREE_CLOEXEC|AT_SYMLINK_NOFOLLOW,
662 &(struct mount_attr) {
663 .attr_set = (p.read_only > 0 ? MOUNT_ATTR_RDONLY : 0),
664 .attr_clr = MOUNT_ATTR_NOSUID|MOUNT_ATTR_NOEXEC|MOUNT_ATTR_NODEV,
665 .propagation = MS_PRIVATE,
666 });
667 if (mount_fd < 0)
668 return log_debug_errno(mount_fd, "Failed to generate per-volume mount: %m");
669
670 /* Let's turn on propagation again now that it is disconnected, simply because MS_SHARED is
671 * generally the default for everything we return. */
672
673 if (mount_setattr(mount_fd, "", AT_EMPTY_PATH|AT_SYMLINK_NOFOLLOW,
674 &(struct mount_attr) {
675 .propagation = MS_SHARED,
676 }, MOUNT_ATTR_SIZE_VER0) < 0)
677 return log_debug_errno(errno, "Failed to enable propagation on per-volume mount: %m");
678
679 close_and_replace(real_fd, mount_fd);
680
681 r = fd_is_read_only_fs(real_fd);
682 if (r < 0)
683 return r;
684
685 ro = r > 0;
686 break;
687 }
688
689 default:
690 assert_not_reached();
691 }
692
693 if (p.read_only == 0 && ro)
694 return sd_varlink_error(link, "io.systemd.StorageProvider.ReadOnlyVolume", NULL);
695
696 int idx = sd_varlink_push_fd(link, real_fd);
697 if (idx < 0)
698 return idx;
699
700 TAKE_FD(real_fd);
701
702 return sd_varlink_replybo(
703 link,
704 SD_JSON_BUILD_PAIR_INTEGER("fileDescriptorIndex", idx),
705 SD_JSON_BUILD_PAIR_STRING("type", inode_type_to_string(st.st_mode)),
706 SD_JSON_BUILD_PAIR_BOOLEAN("readOnly", ro),
707 SD_JSON_BUILD_PAIR_CONDITION(p.request_as == VOLUME_DIR, "baseUID", SD_JSON_BUILD_INTEGER(FOREIGN_UID_BASE)),
708 SD_JSON_BUILD_PAIR_CONDITION(p.request_as == VOLUME_DIR, "baseGID", SD_JSON_BUILD_INTEGER(FOREIGN_UID_BASE)));
709 }
710
711 static int vl_server(void) {
712 int r;
713
714 _cleanup_(hashmap_freep) Hashmap *polkit_registry = NULL;
715 _cleanup_(sd_varlink_server_unrefp) sd_varlink_server *varlink_server = NULL;
716 r = varlink_server_new(
717 &varlink_server,
718 SD_VARLINK_SERVER_HANDLE_SIGINT|
719 SD_VARLINK_SERVER_HANDLE_SIGTERM|
720 SD_VARLINK_SERVER_ALLOW_FD_PASSING_OUTPUT|
721 SD_VARLINK_SERVER_INHERIT_USERDATA,
722 &polkit_registry);
723 if (r < 0)
724 return log_error_errno(r, "Failed to allocate Varlink server: %m");
725
726 r = sd_varlink_server_add_interface(varlink_server, &vl_interface_io_systemd_StorageProvider);
727 if (r < 0)
728 return log_error_errno(r, "Failed to add Varlink interface: %m");
729
730 r = sd_varlink_server_bind_method_many(
731 varlink_server,
732 "io.systemd.StorageProvider.Acquire", vl_method_acquire,
733 "io.systemd.StorageProvider.ListVolumes", vl_method_list_volumes,
734 "io.systemd.StorageProvider.ListTemplates", vl_method_list_templates);
735 if (r < 0)
736 return log_error_errno(r, "Failed to bind Varlink methods: %m");
737
738 r = sd_varlink_server_loop_auto(varlink_server);
739 if (r < 0)
740 return log_error_errno(r, "Failed to run Varlink event loop: %m");
741
742 return 0;
743 }
744
745 static int help(void) {
746 int r;
747
748 help_cmdline("[OPTIONS...]");
749 help_abstract("Simple file system backed storage provider");
750
751 _cleanup_(table_unrefp) Table *options = NULL;
752 r = option_parser_get_help_table(&options);
753 if (r < 0)
754 return r;
755
756 help_section("Options");
757
758 r = table_print_or_warn(options);
759 if (r < 0)
760 return r;
761
762 help_man_page_reference("systemd-storage-fs", "8");
763 return 0;
764 }
765
766 static int parse_argv(int argc, char *argv[]) {
767 assert(argc >= 0);
768 assert(argv);
769
770 OptionParser opts = { argc, argv };
771 FOREACH_OPTION_OR_RETURN(c, &opts)
772 switch (c) {
773
774 OPTION_COMMON_HELP:
775 return help();
776
777 OPTION_COMMON_VERSION:
778 return version();
779
780 OPTION_COMMON_SYSTEM:
781 arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
782 break;
783
784 OPTION_COMMON_USER:
785 arg_runtime_scope = RUNTIME_SCOPE_USER;
786 break;
787 }
788
789 if (option_parser_get_n_args(&opts) > 0)
790 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program takes no arguments.");
791
792 return 1;
793 }
794
795 static int run(int argc, char* argv[]) {
796 int r;
797
798 log_setup();
799
800 r = parse_argv(argc, argv);
801 if (r <= 0)
802 return r;
803
804 return vl_server();
805 }
806
807 DEFINE_MAIN_FUNCTION(run);