Debian Codegraph @

src/storage/storagectl.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "sd-varlink.h"
4
5 #include <sys/mount.h>
6 #include <sys/stat.h>
7 #include <unistd.h>
8
9 #include "alloc-util.h"
10 #include "ansi-color.h"
11 #include "argv-util.h"
12 #include "build.h"
13 #include "bus-util.h"
14 #include "errno-list.h"
15 #include "escape.h"
16 #include "extract-word.h"
17 #include "fd-util.h"
18 #include "format-table.h"
19 #include "format-util.h"
20 #include "help-util.h"
21 #include "machine-util.h"
22 #include "main-func.h"
23 #include "mount-util.h"
24 #include "namespace-util.h"
25 #include "options.h"
26 #include "parse-argument.h"
27 #include "parse-util.h"
28 #include "path-lookup.h"
29 #include "path-util.h"
30 #include "polkit-agent.h"
31 #include "recurse-dir.h"
32 #include "runtime-scope.h"
33 #include "socket-util.h"
34 #include "stat-util.h"
35 #include "stdio-util.h"
36 #include "storage-util.h"
37 #include "string-util.h"
38 #include "strv.h"
39 #include "user-util.h"
40 #include "varlink-util.h"
41 #include "verbs.h"
42
43 static sd_json_format_flags_t arg_json_format_flags = SD_JSON_FORMAT_OFF;
44 static PagerFlags arg_pager_flags = 0;
45 static bool arg_legend = true;
46 static bool arg_ask_password = true;
47 static RuntimeScope arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
48
49 static int help(void) {
50 int r;
51
52 help_cmdline("[OPTIONS...] COMMAND");
53 help_abstract("Enumerate storage volumes and providers.");
54
55 _cleanup_(table_unrefp) Table *verbs = NULL;
56 r = verbs_get_help_table(&verbs);
57 if (r < 0)
58 return r;
59
60 _cleanup_(table_unrefp) Table *options = NULL;
61 r = option_parser_get_help_table_ns("storagectl", &options);
62 if (r < 0)
63 return r;
64
65 (void) table_sync_column_widths(0, verbs, options);
66
67 help_section("Commands");
68
69 r = table_print_or_warn(verbs);
70 if (r < 0)
71 return r;
72
73 help_section("Options");
74
75 r = table_print_or_warn(options);
76 if (r < 0)
77 return r;
78
79 help_man_page_reference("storagectl", "1");
80 return 0;
81 }
82
83 VERB_COMMON_HELP_HIDDEN(help);
84
85 static const char *ro_color(int ro) {
86 if (ro > 0)
87 return ansi_highlight_red();
88 if (ro == 0)
89 return ansi_highlight_green();
90
91 return NULL;
92 }
93
94 static int on_list_reply(
95 sd_varlink *link,
96 sd_json_variant *parameters,
97 const char *error_id,
98 sd_varlink_reply_flags_t flags,
99 void* userdata) {
100
101 Table *t = ASSERT_PTR(userdata);
102 int r;
103
104 assert(link);
105
106 const char *d = ASSERT_PTR(sd_varlink_get_description(link));
107
108 if (error_id) {
109 log_debug("%s: Received error '%s', ignoring.", d, error_id);
110 return 0;
111 }
112
113 _cleanup_free_ char *provider = NULL;
114 r = path_extract_filename(d, &provider);
115 if (r < 0)
116 return log_error_errno(r, "Failed to extract provider name from socket path: %m");
117
118 struct {
119 const char *name;
120 const char *type;
121 int read_only;
122 uint64_t size_bytes;
123 uint64_t used_bytes;
124 } p = {
125 .read_only = -1,
126 .size_bytes = UINT64_MAX,
127 .used_bytes = UINT64_MAX,
128 };
129
130 static const sd_json_dispatch_field dispatch_table[] = {
131 { "name", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, voffsetof(p, name), 0 },
132 { "type", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, voffsetof(p, type), 0 },
133 { "readOnly", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_tristate, voffsetof(p, read_only), 0 },
134 { "sizeBytes", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64, voffsetof(p, size_bytes), 0 },
135 { "usedBytes", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64, voffsetof(p, used_bytes), 0 },
136 {}
137 };
138
139 r = sd_json_dispatch(parameters, dispatch_table, SD_JSON_ALLOW_EXTENSIONS, &p);
140 if (r < 0)
141 return log_error_errno(r, "Failed to decode List() reply: %m");
142
143 r = table_add_many(
144 t,
145 TABLE_STRING, provider,
146 TABLE_STRING, p.name,
147 TABLE_STRING, p.type,
148 TABLE_TRISTATE, p.read_only,
149 TABLE_SET_COLOR, ro_color(p.read_only));
150 if (r < 0)
151 return table_log_add_error(r);
152
153 if (p.size_bytes == UINT64_MAX)
154 r = table_add_many(t, TABLE_EMPTY, TABLE_SET_ALIGN_PERCENT, 100);
155 else
156 r = table_add_many(t, TABLE_SIZE, p.size_bytes, TABLE_SET_ALIGN_PERCENT, 100);
157 if (r < 0)
158 return table_log_add_error(r);
159
160 if (p.used_bytes == UINT64_MAX)
161 r = table_add_many(t, TABLE_EMPTY, TABLE_SET_ALIGN_PERCENT, 100);
162 else
163 r = table_add_many(t, TABLE_SIZE, p.used_bytes, TABLE_SET_ALIGN_PERCENT, 100);
164 if (r < 0)
165 return table_log_add_error(r);
166
167 return 0;
168 }
169
170 VERB(verb_list_volumes, "volumes", "GLOB", /* min_args= */ VERB_ANY, /* max_args= */ 2, VERB_DEFAULT, "List storage volumes");
171 static int verb_list_volumes(int argc, char *argv[], uintptr_t data, void *userdata) {
172 int r;
173
174 assert(argc <= 2);
175
176 _cleanup_free_ char *socket_path = NULL;
177 r = runtime_directory_generic(arg_runtime_scope, "systemd/io.systemd.StorageProvider", &socket_path);
178 if (r < 0)
179 return log_error_errno(r, "Failed to determine socket directory: %m");
180
181 _cleanup_(table_unrefp) Table *t = table_new("provider", "name", "type", "ro", "size", "used");
182 if (!t)
183 return log_oom();
184
185 (void) table_set_sort(t, (size_t) 0, (size_t) 1);
186 table_set_ersatz_string(t, TABLE_ERSATZ_DASH);
187
188 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
189 if (argc >= 2) {
190 r = sd_json_buildo(
191 &v,
192 SD_JSON_BUILD_PAIR_STRING("matchName", argv[1]));
193 if (r < 0)
194 return log_oom();
195 }
196
197 ssize_t n = varlink_execute_directory(
198 socket_path,
199 "io.systemd.StorageProvider.ListVolumes",
200 v,
201 /* more= */ true,
202 /* timeout_usec= */ 0, /* 0 means default */
203 on_list_reply,
204 t);
205 if (n < 0 && n != -ENOENT)
206 return log_error_errno(n, "Failed to enumerate storage volumes: %m");
207
208 if (!table_isempty(t)) {
209 r = table_print_with_pager(t, arg_json_format_flags, arg_pager_flags, arg_legend);
210 if (r < 0)
211 return r;
212 }
213
214 if (arg_legend && FLAGS_SET(arg_json_format_flags, SD_JSON_FORMAT_OFF)) {
215 if (table_isempty(t))
216 printf("No storage volumes.\n");
217 else
218 printf("\n%zu storage volumes listed.\n", table_get_rows(t) - 1);
219 }
220
221 return 0;
222 }
223
224 static int on_list_templates_reply(
225 sd_varlink *link,
226 sd_json_variant *parameters,
227 const char *error_id,
228 sd_varlink_reply_flags_t flags,
229 void* userdata) {
230
231 Table *t = ASSERT_PTR(userdata);
232 int r;
233
234 assert(link);
235
236 const char *d = ASSERT_PTR(sd_varlink_get_description(link));
237
238 if (error_id) {
239 log_debug("%s: Received error '%s', ignoring.", d, error_id);
240 return 0;
241 }
242
243 _cleanup_free_ char *provider = NULL;
244 r = path_extract_filename(d, &provider);
245 if (r < 0)
246 return log_error_errno(r, "Failed to extract provider name from socket path: %m");
247
248 struct {
249 const char *name;
250 const char *type;
251 } p = {
252 };
253
254 static const sd_json_dispatch_field dispatch_table[] = {
255 { "name", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, voffsetof(p, name), 0 },
256 { "type", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, voffsetof(p, type), 0 },
257 {}
258 };
259
260 r = sd_json_dispatch(parameters, dispatch_table, SD_JSON_ALLOW_EXTENSIONS, &p);
261 if (r < 0)
262 return log_error_errno(r, "Failed to decode ListTemplates() reply: %m");
263
264 r = table_add_many(
265 t,
266 TABLE_STRING, provider,
267 TABLE_STRING, p.name,
268 TABLE_STRING, p.type);
269 if (r < 0)
270 return table_log_add_error(r);
271
272 return 0;
273 }
274
275 VERB(verb_templates, "templates", "GLOB", /* min_args= */ VERB_ANY, /* max_args= */ 2, /* flags= */ 0, "List storage volume templates");
276 static int verb_templates(int argc, char *argv[], uintptr_t data, void *userdata) {
277 int r;
278
279 assert(argc <= 2);
280
281 _cleanup_free_ char *socket_path = NULL;
282 r = runtime_directory_generic(arg_runtime_scope, "systemd/io.systemd.StorageProvider", &socket_path);
283 if (r < 0)
284 return log_error_errno(r, "Failed to determine socket directory: %m");
285
286 _cleanup_(table_unrefp) Table *t = table_new("provider", "name", "type");
287 if (!t)
288 return log_oom();
289
290 (void) table_set_sort(t, (size_t) 0, (size_t) 1);
291 table_set_ersatz_string(t, TABLE_ERSATZ_DASH);
292
293 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
294 if (argc >= 2) {
295 r = sd_json_buildo(
296 &v,
297 SD_JSON_BUILD_PAIR_STRING("matchName", argv[1]));
298 if (r < 0)
299 return log_oom();
300 }
301
302 ssize_t n = varlink_execute_directory(
303 socket_path,
304 "io.systemd.StorageProvider.ListTemplates",
305 v,
306 /* more= */ true,
307 /* timeout_usec= */ 0, /* 0 means default */
308 on_list_templates_reply,
309 t);
310 if (n < 0 && n != -ENOENT)
311 return log_error_errno(n, "Failed to enumerate storage volume templates: %m");
312
313 if (!table_isempty(t)) {
314 r = table_print_with_pager(t, arg_json_format_flags, arg_pager_flags, arg_legend);
315 if (r < 0)
316 return r;
317 }
318
319 if (arg_legend && FLAGS_SET(arg_json_format_flags, SD_JSON_FORMAT_OFF)) {
320 if (table_isempty(t))
321 printf("No templates.\n");
322 else
323 printf("\n%zu templates listed.\n", table_get_rows(t) - 1);
324 }
325
326 return 0;
327 }
328
329 VERB_NOARG(verb_providers, "providers", "List storage providers");
330 static int verb_providers(int argc, char *argv[], uintptr_t data, void *userdata) {
331 int r;
332
333 _cleanup_free_ char *socket_path = NULL;
334 r = runtime_directory_generic(arg_runtime_scope, "systemd/io.systemd.StorageProvider", &socket_path);
335 if (r < 0)
336 return log_error_errno(r, "Failed to determine socket directory: %m");
337
338 _cleanup_(table_unrefp) Table *t = table_new("provider", "listening");
339 if (!t)
340 return log_oom();
341
342 (void) table_set_sort(t, (size_t) 0);
343 table_set_ersatz_string(t, TABLE_ERSATZ_DASH);
344
345 _cleanup_close_ int fd = open(socket_path, O_RDONLY|O_CLOEXEC|O_DIRECTORY);
346 if (fd < 0) {
347 if (errno != ENOENT)
348 return log_error_errno(errno, "Failed to open '%s': %m", socket_path);
349 } else {
350 _cleanup_free_ DirectoryEntries *dentries = NULL;
351 r = readdir_all(fd, RECURSE_DIR_SORT|RECURSE_DIR_IGNORE_DOT|RECURSE_DIR_ENSURE_TYPE, &dentries);
352 if (r < 0)
353 return log_error_errno(r, "Failed to enumerate '%s': %m", socket_path);
354
355 FOREACH_ARRAY(dp, dentries->entries, dentries->n_entries) {
356 struct dirent *de = *dp;
357
358 if (de->d_type != DT_SOCK)
359 continue;
360
361 if (!storage_provider_name_is_valid(de->d_name))
362 continue;
363
364 _cleanup_close_ int socket_fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
365 if (socket_fd < 0)
366 return log_error_errno(errno, "Failed to allocate AF_UNIX/SOCK_STREAM socket: %m");
367
368 _cleanup_free_ char *no = NULL;
369 r = connect_unix_path(socket_fd, fd, de->d_name);
370 if (r < 0) {
371 no = strjoin("no (", ERRNO_NAME(r), ")");
372 if (!no)
373 return log_oom();
374 }
375
376 r = table_add_many(t,
377 TABLE_STRING, de->d_name,
378 TABLE_STRING, no ?: "yes",
379 TABLE_SET_COLOR, ansi_highlight_green_red(!no));
380 if (r < 0)
381 return table_log_add_error(r);
382 }
383 }
384
385 if (!table_isempty(t)) {
386 r = table_print_with_pager(t, arg_json_format_flags, arg_pager_flags, arg_legend);
387 if (r < 0)
388 return r;
389 }
390
391 if (arg_legend && FLAGS_SET(arg_json_format_flags, SD_JSON_FORMAT_OFF)) {
392 if (table_isempty(t))
393 printf("No providers.\n");
394 else
395 printf("\n%zu providers listed.\n", table_get_rows(t) - 1);
396 }
397
398 return 0;
399 }
400
401 static int parse_argv(int argc, char *argv[], char ***remaining_args) {
402 int r;
403
404 assert(argc >= 0);
405 assert(argv);
406 assert(remaining_args);
407
408 OptionParser opts = { argc, argv, .namespace = "storagectl" };
409 FOREACH_OPTION_OR_RETURN(c, &opts)
410 switch (c) {
411
412 OPTION_NAMESPACE("storagectl"): {}
413
414 OPTION_COMMON_HELP:
415 return help();
416
417 OPTION_COMMON_VERSION:
418 return version();
419
420 OPTION_COMMON_NO_PAGER:
421 arg_pager_flags |= PAGER_DISABLE;
422 break;
423
424 OPTION_COMMON_NO_LEGEND:
425 arg_legend = false;
426 break;
427
428 OPTION_COMMON_JSON:
429 r = parse_json_argument(opts.arg, &arg_json_format_flags);
430 if (r <= 0)
431 return r;
432 break;
433
434 OPTION_COMMON_NO_ASK_PASSWORD:
435 arg_ask_password = false;
436 break;
437
438 OPTION_COMMON_SYSTEM:
439 arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
440 break;
441
442 OPTION_COMMON_USER:
443 arg_runtime_scope = RUNTIME_SCOPE_USER;
444 break;
445 }
446
447 *remaining_args = option_parser_get_args(&opts);
448 return 1;
449 }
450
451 static int run_as_mount_helper(int argc, char *argv[]) {
452 int r;
453
454 /* Implements util-linux "external helper" command line interface, as per mount(8) man page.
455 *
456 * Usage:
457 *
458 * mount -t storage fs:mydirvolume /some/place # Directory volumes
459 * mount -t storage.ext4 fs:myblkvolume /some/place # Block volumes
460 */
461
462 const char *fstype = NULL, *options = NULL;
463 bool fake = false;
464
465 OptionParser opts = { argc, argv, .namespace = "mount.storage" };
466 FOREACH_OPTION_OR_RETURN(c, &opts)
467 switch (c) {
468
469 OPTION_NAMESPACE("mount.storage"): {}
470
471 OPTION_SHORT('f', NULL, /* help= */ NULL):
472 fake = true;
473 break;
474
475 OPTION_SHORT('o', "OPTIONS", /* help= */ NULL):
476 options = opts.arg;
477 break;
478
479 OPTION_SHORT('t', "FSTYPE", /* help= */ NULL):
480 fstype = startswith(opts.arg, "storage.");
481 if (fstype) {
482 /* Paranoia: don't allow "storage.storage.storage.…" chains... */
483 if (startswith(fstype, "storage.") || streq(fstype, "storage"))
484 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Refusing nested storage volumes.");
485 } else if (!streq(opts.arg, "storage"))
486 log_warning("Unexpected file system type '%s', ignoring.", opts.arg);
487
488 break;
489
490 OPTION_SHORT('s', NULL, /* help= */ NULL): {} /* sloppy mount options */
491 OPTION_SHORT('n', NULL, /* help= */ NULL): {} /* aka --no-mtab */
492 OPTION_SHORT('v', NULL, /* help= */ NULL): /* aka --verbose */
493 log_debug("Ignoring option -%c, not implemented.", opts.opt->short_code);
494 break;
495
496 OPTION_SHORT('N', "NS", /* help= */ NULL): /* aka --namespace= */
497 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
498 "Option -%c is not implemented, refusing.",
499 opts.opt->short_code);
500 }
501
502 char **args = option_parser_get_args(&opts);
503 size_t n_args = option_parser_get_n_args(&opts);
504
505 if (n_args != 2)
506 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
507 "Expected a storage volume specification and target directory as only arguments.");
508
509 const char *colon = strchr(args[0], ':');
510 if (!colon)
511 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid storage volume specification, refusing: %s", args[0]);
512
513 _cleanup_free_ char *provider = strndup(args[0], colon - args[0]);
514 if (!provider)
515 return log_oom();
516 if (!storage_provider_name_is_valid(provider))
517 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid storage provider name: %s", provider);
518
519 _cleanup_free_ char *name = strdup(colon + 1);
520 if (!name)
521 return log_oom();
522 if (!storage_volume_name_is_valid(name))
523 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid storage volume name: %s", name);
524
525 _cleanup_free_ char *path = NULL;
526 r = parse_path_argument(args[1], /* suppress_root= */ false, &path);
527 if (r < 0)
528 return r;
529
530 _cleanup_free_ char *filtered = NULL, *template = NULL;
531 CreateMode create_mode = _CREATE_MODE_INVALID;
532 uint64_t create_size = UINT64_MAX;
533 ReadOnlyMode read_only = _READ_ONLY_INVALID;
534 for (const char *p = options;;) {
535 _cleanup_free_ char *word = NULL;
536
537 r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE|EXTRACT_UNESCAPE_SEPARATORS);
538 if (r < 0)
539 return log_error_errno(r, "Failed to extract mount option: %m");
540 if (r == 0)
541 break;
542
543 const char *t = startswith(word, "storage.");
544 if (t) {
545 const char *v;
546 if ((v = startswith(t, "create="))) {
547 create_mode = create_mode_from_string(v);
548 if (create_mode < 0)
549 return log_error_errno(create_mode, "Failed to parse storage.create= parameter: %s", v);
550 } else if ((v = startswith(t, "create-size="))) {
551 r = parse_size(v, /* base= */ 1024, &create_size);
552 if (r < 0)
553 return log_error_errno(r, "Failed to parse storage.create-size= parameter: %s", v);
554 } else if ((v = startswith(t, "template="))) {
555 if (!storage_template_name_is_valid(v))
556 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid template name, refusing: %s", v);
557
558 r = free_and_strdup(&template, v);
559 if (r < 0)
560 return log_oom();
561 } else
562 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown mount option '%s', refusing.", word);
563 } else if (streq(word, "ro"))
564 read_only = READ_ONLY_YES;
565 else if (streq(word, "rw"))
566 read_only = READ_ONLY_NO;
567 else if (!strextend_with_separator(&filtered, ",", word))
568 return log_oom();
569 }
570
571 if (fake)
572 return 0;
573
574 (void) polkit_agent_open_if_enabled(BUS_TRANSPORT_LOCAL, arg_ask_password);
575
576 VolumeType requested_type = fstype ? VOLUME_REG : VOLUME_DIR;
577
578 BindVolume bv = BIND_VOLUME_INIT;
579 bv.provider = provider;
580 bv.volume = name;
581 bv.create_mode = create_mode;
582 bv.template = template;
583 bv.read_only = read_only;
584 bv.request_as = requested_type;
585 bv.create_size_bytes = create_size;
586
587 _cleanup_(storage_acquire_reply_done) StorageAcquireReply reply = STORAGE_ACQUIRE_REPLY_INIT;
588 _cleanup_free_ char *acquire_error_id = NULL;
589 r = storage_acquire_volume(arg_runtime_scope, &bv, arg_ask_password, &acquire_error_id, &reply);
590 if (r < 0 && fstype &&
591 STR_IN_SET(strna(acquire_error_id),
592 "io.systemd.StorageProvider.TypeNotSupported",
593 "io.systemd.StorageProvider.WrongType")) {
594 _cleanup_(storage_acquire_reply_done) StorageAcquireReply retry = STORAGE_ACQUIRE_REPLY_INIT;
595 assert(bv.request_as == VOLUME_REG);
596 bv.request_as = VOLUME_BLK;
597 int k = storage_acquire_volume(arg_runtime_scope, &bv, arg_ask_password, /* reterr_error_id= */ NULL, &retry);
598 if (k >= 0) {
599 storage_acquire_reply_done(&reply);
600 reply = retry;
601 retry = STORAGE_ACQUIRE_REPLY_INIT;
602 acquire_error_id = mfree(acquire_error_id);
603 requested_type = VOLUME_BLK;
604 r = 0;
605 }
606 }
607
608 if (r < 0) {
609 const char *eid = acquire_error_id;
610
611 if (streq_ptr(eid, "io.systemd.StorageProvider.NoSuchVolume"))
612 return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "Volume '%s' not known.", name);
613 if (streq_ptr(eid, "io.systemd.StorageProvider.NoSuchTemplate"))
614 return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "Template '%s' not known.", template);
615 if (streq_ptr(eid, "io.systemd.StorageProvider.VolumeExists"))
616 return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "Volume '%s' exists already.", name);
617 if (streq_ptr(eid, "io.systemd.StorageProvider.TypeNotSupported"))
618 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Storage provider does not support the specified volume type '%s'.", volume_type_to_string(requested_type));
619 if (streq_ptr(eid, "io.systemd.StorageProvider.WrongType"))
620 return log_error_errno(SYNTHETIC_ERRNO(EADDRNOTAVAIL), "Volume '%s' is not of type '%s'.", name, volume_type_to_string(requested_type));
621 if (streq_ptr(eid, "io.systemd.StorageProvider.CreateNotSupported"))
622 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Storage provider does not support creating volumes.");
623 if (streq_ptr(eid, "io.systemd.StorageProvider.CreateSizeRequired"))
624 return log_error_errno(SYNTHETIC_ERRNO(ENODATA), "Storage provider requires a create size to be provided when creating volumes on-the-fly. Use 'storage.create-size=' mount option.");
625 if (streq_ptr(eid, "io.systemd.StorageProvider.ReadOnlyVolume"))
626 return log_error_errno(SYNTHETIC_ERRNO(EROFS), "Volume '%s' is read-only.", name);
627 if (streq_ptr(eid, "io.systemd.StorageProvider.BadTemplate"))
628 return log_error_errno(SYNTHETIC_ERRNO(EADDRNOTAVAIL), "Template does not apply to this volume type.");
629
630 if (eid)
631 return log_error_errno(r, "Failed to issue io.systemd.StorageProvider.Acquire() varlink call (%s): %m", eid);
632 return log_error_errno(r, "Failed to issue io.systemd.StorageProvider.Acquire() varlink call: %m");
633 }
634
635 struct stat st;
636 if (fstat(reply.fd, &st) < 0)
637 return log_error_errno(errno, "Failed to stat returned file descriptor: %m");
638
639 _cleanup_strv_free_ char **cmdline = strv_new("mount", "-c");
640 if (!cmdline)
641 return log_oom();
642
643 if (fstype) {
644 if (!IN_SET(reply.type, VOLUME_REG, VOLUME_BLK))
645 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Mounting as file system type '%s' requested, but volume is not a block device or regular file.", fstype);
646
647 r = stat_verify_regular_or_block(&st);
648 if (r < 0)
649 return log_error_errno(r, "File descriptor for block/regular volume is not a block or regular inode: %m");
650
651 if (strv_extend_strv(&cmdline, STRV_MAKE("-t", fstype), /* filter_duplicates= */ false) < 0)
652 return log_oom();
653 } else {
654 if (reply.type != VOLUME_DIR)
655 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Mount as directory requested, but volume is not a directory.");
656
657 if (!uid_is_valid(reply.base_uid) || !gid_is_valid(reply.base_gid))
658 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Provider did not report base UID/GID, cannot mount.");
659
660 if (reply.base_uid > UINT32_MAX - USERNS_RANGE_SIZE ||
661 reply.base_gid > UINT32_MAX - USERNS_RANGE_SIZE)
662 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Returned base UID/GID out of range.");
663
664 r = stat_verify_directory(&st);
665 if (r < 0)
666 return log_error_errno(r, "File descriptor for directory volume is not a directory inode: %m");
667
668 if (st.st_uid < reply.base_uid || st.st_uid >= reply.base_uid + USERNS_RANGE_SIZE ||
669 st.st_gid < reply.base_gid || st.st_gid >= reply.base_gid + USERNS_RANGE_SIZE)
670 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "File descriptor for directory volume is not owned by base UID/GID range, refusing.");
671
672 /* Now move the mount into our own UID/GID range */
673 _cleanup_free_ char *uid_line = asprintf_safe(
674 UID_FMT " " UID_FMT " " UID_FMT "\n",
675 reply.base_uid, (uid_t) 0, USERNS_RANGE_SIZE);
676 _cleanup_free_ char *gid_line = asprintf_safe(
677 GID_FMT " " GID_FMT " " GID_FMT "\n",
678 reply.base_gid, (gid_t) 0, USERNS_RANGE_SIZE);
679 if (!uid_line || !gid_line)
680 return log_oom();
681
682 _cleanup_close_ int userns_fd = userns_acquire(uid_line, gid_line, /* setgroups_deny= */ true);
683 if (userns_fd < 0)
684 return log_error_errno(userns_fd, "Failed to acquire new user namespace: %m");
685
686 _cleanup_close_ int remapped_fd = open_tree_attr_with_fallback(
687 reply.fd,
688 /* path= */ NULL,
689 OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC,
690 &(struct mount_attr) {
691 .attr_set = MOUNT_ATTR_IDMAP,
692 .userns_fd = userns_fd,
693 });
694 if (remapped_fd < 0)
695 return log_error_errno(remapped_fd, "Failed to set ID mapping on returned mount: %m");
696
697 close_and_replace(reply.fd, remapped_fd);
698
699 if (strv_extend(&cmdline, "--bind") < 0)
700 return log_oom();
701 }
702
703 if (reply.read_only > 0)
704 read_only = READ_ONLY_YES;
705
706 if (!strextend_with_separator(&filtered, ",", read_only == READ_ONLY_YES ? "ro" : "rw"))
707 return log_oom();
708
709 if (strv_extend_strv(&cmdline, STRV_MAKE("-o", filtered), /* filter_duplicates= */ false) < 0)
710 return log_oom();
711
712 if (strv_extend_strv(&cmdline, STRV_MAKE(FORMAT_PROC_FD_PATH(reply.fd), path), /* filter_duplicates= */ false) < 0)
713 return log_oom();
714
715 r = fd_cloexec(reply.fd, false);
716 if (r < 0)
717 return log_error_errno(r, "Failed to disable O_CLOEXEC for mount fd: %m");
718
719 if (DEBUG_LOGGING) {
720 _cleanup_free_ char *q = quote_command_line(cmdline, SHELL_ESCAPE_EMPTY);
721 log_debug("Chain-loading: %s", strna(q));
722 }
723
724 /* NB: we do not honour $PATH here, since as plugin to /bin/mount we might be called in a setuid()
725 * context, and hence don't want to chain to programs potentially under user control. */
726 execv("/bin/mount", cmdline);
727 return log_error_errno(errno, "Failed to execute mount tool: %m");
728 }
729
730 static int run(int argc, char *argv[]) {
731 int r;
732
733 log_setup();
734
735 if (invoked_as(argv, "mount.storage"))
736 return run_as_mount_helper(argc, argv);
737
738 char **args = NULL;
739 r = parse_argv(argc, argv, &args);
740 if (r <= 0)
741 return r;
742
743 return dispatch_verb(args, /* userdata= */ NULL);
744 }
745
746 DEFINE_MAIN_FUNCTION(run);