Debian Codegraph @

pkg/storaged/block/format-dialog.jsx

raw
1 /*
2 * Copyright (C) 2016 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import cockpit from "cockpit";
7 import client from "../client.js";
8
9 import {
10 edit_crypto_config, parse_options, unparse_options, extract_option,
11 get_parent_blocks, is_netdev,
12 decode_filename, encode_filename, block_name,
13 get_active_usage, reload_systemd, teardown_active_usage,
14 validate_fsys_label,
15 } from "../utils.js";
16
17 import {
18 dialog_open,
19 TextInput, PassInput, CheckBoxes, SelectOne, SizeSlider,
20 BlockingMessage, TeardownMessage,
21 init_teardown_usage
22 } from "../dialog.jsx";
23
24 import { get_fstab_config, is_valid_mount_point } from "../filesystem/utils.jsx";
25 import { init_existing_passphrase, unlock_with_type } from "../crypto/keyslots.jsx";
26 import { job_progress_wrapper } from "../jobs-panel.jsx";
27 import { at_boot_input, update_at_boot_input, mount_options } from "../filesystem/mounting-dialog.jsx";
28 import { remember_passphrase } from "../anaconda.jsx";
29
30 const _ = cockpit.gettext;
31
32 export function initial_tab_options(client, block, for_fstab) {
33 const options = { };
34
35 // "nofail" is the default for new filesystems with Cockpit so
36 // that a failure to mount one of them will not prevent
37 // Cockpit from starting. This allows people to debug and fix
38 // these failures with Cockpit itself.
39 //
40 // In Anaconda mode however, we don't make "nofail" the
41 // default since people will be creating the core filesystems
42 // like "/", "/var", etc.
43
44 if (!client.in_anaconda_mode())
45 options.nofail = true;
46
47 get_parent_blocks(client, block.path).forEach(p => {
48 if (is_netdev(client, p)) {
49 options._netdev = true;
50 }
51 // HACK - https://bugzilla.redhat.com/show_bug.cgi?id=1589541
52 if (client.legacy_vdo_overlay.find_by_block(client.blocks[p])) {
53 options._netdev = true;
54 options["x-systemd.device-timeout=0"] = true;
55 if (for_fstab)
56 options["x-systemd.requires=vdo.service"] = true;
57 }
58 });
59
60 return Object.keys(options).join(",");
61 }
62
63 export function initial_crypto_options(client, block) {
64 return initial_tab_options(client, block, false);
65 }
66
67 export function initial_mount_options(client, block) {
68 return initial_tab_options(client, block, true);
69 }
70
71 export function format_dialog(client, path, start, size, enable_dos_extended) {
72 const block = client.blocks[path];
73 if (block.IdUsage == "crypto") {
74 cockpit.spawn(["cryptsetup", "luksDump", decode_filename(block.Device)], { superuser: "require" })
75 .then(output => {
76 if (output.indexOf("Keyslots:") >= 0) // This is what luksmeta-monitor-hack looks for
77 return 2;
78 else
79 return 1;
80 })
81 .catch(() => {
82 return false;
83 })
84 .then(version => {
85 return format_dialog_internal(client, path, start, size, enable_dos_extended, version);
86 });
87 } else {
88 return format_dialog_internal(client, path, start, size, enable_dos_extended);
89 }
90 }
91
92 function find_root_fsys_block() {
93 const root = client.anaconda?.mount_point_prefix || "/";
94 for (const p in client.blocks) {
95 if (client.blocks_fsys[p] && client.blocks_fsys[p].MountPoints.map(decode_filename).indexOf(root) >= 0)
96 return client.blocks[p];
97 if (client.blocks[p].Configuration.find(c => c[0] == "fstab" && decode_filename(c[1].dir.v) == root))
98 return client.blocks[p];
99 }
100 return null;
101 }
102
103 function format_dialog_internal(client, path, start, size, enable_dos_extended, old_luks_version) {
104 const block = client.blocks[path];
105 const block_part = client.blocks_part[path];
106 const block_ptable = client.blocks_ptable[path] || client.blocks_ptable[block_part?.Table];
107 const content_block = block.IdUsage == "crypto" ? client.blocks_cleartext[path] : block;
108
109 const offer_keep_keys = block.IdUsage == "crypto";
110 const unlock_before_format = offer_keep_keys && (!content_block || content_block.ReadOnly);
111
112 const create_partition = (start !== undefined);
113
114 let title;
115 if (create_partition)
116 title = cockpit.format(_("Create partition on $0"), block_name(block));
117 else
118 title = cockpit.format(_("Format $0"), block_name(block));
119
120 function is_filesystem(vals) {
121 return vals.type != "empty" && vals.type != "dos-extended" && vals.type != "biosboot" && vals.type != "swap";
122 }
123
124 function add_fsys(storaged_name, entry) {
125 if (storaged_name === true ||
126 (client.fsys_info && client.fsys_info[storaged_name] && client.fsys_info[storaged_name].can_format)) {
127 filesystem_options.push(entry);
128 }
129 }
130
131 const filesystem_options = [];
132 add_fsys("xfs", { value: "xfs", title: "XFS" });
133 add_fsys("ext4", { value: "ext4", title: "EXT4" });
134 if (client.features.btrfs)
135 add_fsys("btrfs", { value: "btrfs", title: "BTRFS" });
136 add_fsys("vfat", { value: "vfat", title: "VFAT" });
137 add_fsys("ntfs", { value: "ntfs", title: "NTFS" });
138 add_fsys("swap", { value: "swap", title: "Swap" });
139 if (client.in_anaconda_mode()) {
140 if (block_ptable && block_ptable.Type == "gpt" && !client.anaconda.efi)
141 add_fsys(true, { value: "biosboot", title: "BIOS boot partition" });
142 if (block_ptable && client.anaconda.efi)
143 add_fsys(true, { value: "efi", title: "EFI system partition" });
144 }
145 add_fsys(true, { value: "empty", title: _("No filesystem") });
146 if (create_partition && enable_dos_extended)
147 add_fsys(true, { value: "dos-extended", title: _("Extended partition") });
148
149 function is_supported(type) {
150 return filesystem_options.find(o => o.value == type);
151 }
152
153 let default_type = null;
154 if (content_block?.IdUsage == "filesystem" && is_supported(content_block.IdType))
155 default_type = content_block.IdType;
156 else {
157 const root_block = find_root_fsys_block();
158 if (root_block && is_supported(root_block.IdType)) {
159 default_type = root_block.IdType;
160 } else if (client.anaconda?.default_fsys_type && is_supported(client.anaconda.default_fsys_type)) {
161 default_type = client.anaconda.default_fsys_type;
162 } else {
163 default_type = "ext4";
164 }
165 }
166
167 function is_encrypted(vals) {
168 return vals.crypto && vals.crypto !== "none";
169 }
170
171 function add_crypto_type(value, title, recommended) {
172 if ((client.manager.SupportedEncryptionTypes && client.manager.SupportedEncryptionTypes.indexOf(value) != -1) ||
173 value == "luks1") {
174 crypto_types.push({
175 value,
176 title: title + (recommended ? " " + _("(recommended)") : "")
177 });
178 }
179 }
180
181 const crypto_types = [{ value: "none", title: _("No encryption") }];
182 if (offer_keep_keys) {
183 if (old_luks_version)
184 crypto_types.push({
185 value: " keep",
186 title: cockpit.format(_("Reuse existing encryption ($0)"), "LUKS" + old_luks_version)
187 });
188 else
189 crypto_types.push({ value: " keep", title: _("Reuse existing encryption") });
190 }
191 add_crypto_type("luks1", "LUKS1", false);
192 add_crypto_type("luks2", "LUKS2", true);
193
194 const usage = get_active_usage(client, create_partition ? null : path, _("format"), _("delete"));
195
196 if (usage.Blocking) {
197 dialog_open({
198 Title: cockpit.format(_("$0 is in use"), block_name(block)),
199 Body: BlockingMessage(usage)
200 });
201 return;
202 }
203
204 const crypto_config = block.Configuration.find(c => c[0] == "crypttab");
205 let crypto_options;
206 if (crypto_config) {
207 crypto_options = (decode_filename(crypto_config[1].options.v)
208 .split(",")
209 .filter(function (s) { return s.indexOf("x-parent") !== 0 })
210 .join(","));
211 } else {
212 crypto_options = initial_crypto_options(client, block);
213 }
214
215 const crypto_split_options = parse_options(crypto_options);
216 extract_option(crypto_split_options, "noauto");
217 extract_option(crypto_split_options, "nofail");
218 extract_option(crypto_split_options, "_netdev");
219 extract_option(crypto_split_options, "readonly");
220 extract_option(crypto_split_options, "read-only");
221 const crypto_extra_options = unparse_options(crypto_split_options);
222
223 let [, old_dir, old_opts] = get_fstab_config(block, true,
224 content_block?.IdType == "btrfs"
225 ? { pathname: "/", id: 5 }
226 : undefined);
227 if (old_opts == undefined)
228 old_opts = initial_mount_options(client, block);
229
230 old_dir = client.strip_mount_point_prefix(old_dir);
231 if (old_dir === false)
232 return Promise.reject(_("This device can not be used for the installation target."));
233
234 // Strip out btrfs subvolume mount options
235 const split_options = parse_options(old_opts).filter(opt => !(opt.startsWith('subvol=') || opt.startsWith('subvolid=')));
236 extract_option(split_options, "noauto");
237 const opt_ro = extract_option(split_options, "ro");
238 const opt_never_auto = extract_option(split_options, "x-cockpit-never-auto");
239 const opt_nofail = extract_option(split_options, "nofail");
240 const opt_netdev = extract_option(split_options, "_netdev");
241 const extra_options = unparse_options(split_options);
242
243 let existing_passphrase_type = null;
244
245 let at_boot;
246 if (opt_never_auto)
247 at_boot = "never";
248 else if (opt_netdev)
249 at_boot = "netdev";
250 else if (opt_nofail)
251 at_boot = "nofail";
252 else
253 at_boot = "local";
254
255 let action_variants = [
256 { tag: null, Title: create_partition ? _("Create and mount") : _("Format and mount") },
257 { tag: "nomount", Title: create_partition ? _("Create only") : _("Format only") }
258 ];
259
260 const action_variants_for_empty = [
261 { tag: "nomount", Title: create_partition ? _("Create") : _("Format") }
262 ];
263
264 let action_variants_for_swap = [
265 { tag: null, Title: create_partition ? _("Create and start") : _("Format and start") },
266 { tag: "nomount", Title: create_partition ? _("Create only") : _("Format only") }
267 ];
268
269 if (client.in_anaconda_mode()) {
270 action_variants = action_variants_for_swap = [
271 { tag: "nomount", Title: create_partition ? _("Create") : _("Format") }
272 ];
273 }
274
275 const dlg = dialog_open({
276 Title: title,
277 Teardown: TeardownMessage(usage),
278 Fields: [
279 TextInput("name", _("Name"),
280 {
281 value: content_block?.IdLabel,
282 validate: (name, vals) => validate_fsys_label(name, vals.type),
283 visible: is_filesystem
284 }),
285 TextInput("mount_point", _("Mount point"),
286 {
287 visible: is_filesystem,
288 value: old_dir || "",
289 validate: (val, values, variant) => {
290 return is_valid_mount_point(client,
291 block,
292 client.add_mount_point_prefix(val),
293 variant == "nomount");
294 }
295 }),
296 SelectOne("type", _("Type"),
297 {
298 value: default_type,
299 choices: filesystem_options
300 }),
301 SizeSlider("size", _("Size"),
302 {
303 value: size,
304 max: size,
305 round: 1024 * 1024,
306 visible: function () {
307 return create_partition;
308 }
309 }),
310 CheckBoxes("erase", _("Overwrite"),
311 {
312 fields: [
313 { tag: "on", title: _("Overwrite existing data with zeros (slower)") }
314 ],
315 }),
316 SelectOne("crypto", _("Encryption"),
317 {
318 choices: crypto_types,
319 value: offer_keep_keys ? " keep" : "none",
320 visible: vals => vals.type != "dos-extended" && vals.type != "biosboot" && vals.type != "efi",
321 nested_fields: [
322 PassInput("passphrase", _("Passphrase"),
323 {
324 validate: function (phrase, vals) {
325 if (vals.crypto != " keep" && phrase === "")
326 return _("Passphrase cannot be empty");
327 },
328 visible: vals => is_encrypted(vals) && vals.crypto != " keep",
329 new_password: true
330 }),
331 PassInput("passphrase2", _("Confirm"),
332 {
333 validate: function (phrase2, vals) {
334 if (vals.crypto != " keep" && phrase2 != vals.passphrase)
335 return _("Passphrases do not match");
336 },
337 visible: vals => is_encrypted(vals) && vals.crypto != " keep",
338 new_password: true
339 }),
340 CheckBoxes("store_passphrase", "",
341 {
342 visible: vals => is_encrypted(vals) && vals.crypto != " keep",
343 value: {
344 on: false,
345 },
346 fields: [
347 { title: _("Store passphrase"), tag: "on" }
348 ]
349 }),
350 PassInput("old_passphrase", _("Passphrase"),
351 {
352 validate: function (phrase) {
353 if (phrase === "")
354 return _("Passphrase cannot be empty");
355 },
356 visible: vals => vals.crypto == " keep" && vals.needs_explicit_passphrase,
357 explanation: _("The disk needs to be unlocked before formatting. Please provide an existing passphrase.")
358 }),
359 TextInput("crypto_options", _("Encryption options"),
360 {
361 visible: is_encrypted,
362 value: crypto_extra_options
363 })
364 ]
365 }),
366 at_boot_input(at_boot, is_filesystem),
367 mount_options(opt_ro, extra_options, is_filesystem),
368 ],
369 update: function (dlg, vals, trigger) {
370 update_at_boot_input(dlg, vals, trigger);
371 if (trigger == "type") {
372 if (dlg.get_value("type") == "empty") {
373 dlg.update_actions({ Variants: action_variants_for_empty });
374 } else if (dlg.get_value("type") == "swap") {
375 dlg.update_actions({ Variants: action_variants_for_swap });
376 } else {
377 dlg.update_actions({ Variants: action_variants });
378 }
379 if (vals.type == "efi" && !vals.mount_point)
380 dlg.set_values({ mount_point: "/boot/efi" });
381 } else if (trigger == "crypto") {
382 if (vals.crypto != "none" && vals.crypto != " keep")
383 dlg.show_field("crypto_options");
384 }
385 },
386 Action: {
387 Variants: action_variants,
388 Danger: (create_partition ? null : _("Formatting erases all data on a storage device.")),
389 wrapper: job_progress_wrapper(client, block.path, client.blocks_cleartext[block.path]?.path),
390 disable_on_error: usage.Teardown,
391 action: function (vals) {
392 const mount_now = vals.variant != "nomount";
393 let type = vals.type;
394 let partition_type = "";
395
396 if (type == "efi") {
397 type = "vfat";
398 partition_type = block_ptable.Type == "dos" ? "0xEF" : "c12a7328-f81f-11d2-ba4b-00a0c93ec93b";
399 }
400
401 if (type == "biosboot") {
402 type = "empty";
403 partition_type = "21686148-6449-6e6f-744e-656564454649";
404 }
405
406 if (type == "swap") {
407 partition_type = (block_ptable && block_ptable.Type == "dos"
408 ? "0x82"
409 : "0657fd6d-a4ab-43c4-84e5-0933c84b4f4f");
410 }
411
412 const options = {
413 'tear-down': { t: 'b', v: true }
414 };
415 if (vals.erase.on)
416 options.erase = { t: 's', v: "zero" };
417 if (vals.name)
418 options.label = { t: 's', v: vals.name };
419
420 // HACK - https://bugzilla.redhat.com/show_bug.cgi?id=1516041
421 if (client.legacy_vdo_overlay.find_by_block(block)) {
422 options['no-discard'] = { t: 'b', v: true };
423 }
424
425 const keep_keys = is_encrypted(vals) && offer_keep_keys && vals.crypto == " keep";
426
427 const config_items = [];
428 let new_crypto_options;
429 if (is_encrypted(vals)) {
430 let opts = [];
431 if (is_filesystem(vals)) {
432 if (vals.mount_options?.ro)
433 opts.push("readonly");
434 if (!mount_now || vals.at_boot == "never")
435 opts.push("noauto");
436 if (vals.at_boot == "nofail")
437 opts.push("nofail");
438 if (vals.at_boot == "netdev")
439 opts.push("_netdev");
440 }
441
442 opts = opts.concat(parse_options(vals.crypto_options));
443 new_crypto_options = { t: 'ay', v: encode_filename(unparse_options(opts)) };
444 const item = {
445 options: new_crypto_options,
446 "track-parents": { t: 'b', v: true }
447 };
448
449 if (!keep_keys) {
450 if (vals.store_passphrase.on) {
451 item["passphrase-contents"] = { t: 'ay', v: encode_filename(vals.passphrase) };
452 } else {
453 item["passphrase-contents"] = { t: 'ay', v: encode_filename("") };
454 }
455 config_items.push(["crypttab", item]);
456 options["encrypt.passphrase"] = { t: 's', v: vals.passphrase };
457 options["encrypt.type"] = { t: 's', v: vals.crypto };
458 }
459 }
460
461 let mount_point;
462
463 if (is_filesystem(vals)) {
464 const mount_options = [];
465 if (!mount_now || vals.at_boot == "never") {
466 mount_options.push("noauto");
467 }
468 if (vals.mount_options?.ro)
469 mount_options.push("ro");
470 if (vals.at_boot == "never")
471 mount_options.push("x-cockpit-never-auto");
472 if (vals.at_boot == "nofail")
473 mount_options.push("nofail");
474 if (vals.at_boot == "netdev")
475 mount_options.push("_netdev");
476 if (vals.mount_options?.extra)
477 mount_options.push(vals.mount_options.extra);
478 if (type == "btrfs")
479 mount_options.push("subvol=/");
480
481 mount_point = vals.mount_point;
482 if (mount_point != "") {
483 if (mount_point[0] != "/")
484 mount_point = "/" + mount_point;
485 mount_point = client.add_mount_point_prefix(mount_point);
486
487 config_items.push(["fstab", {
488 dir: { t: 'ay', v: encode_filename(mount_point) },
489 type: { t: 'ay', v: encode_filename("auto") },
490 opts: { t: 'ay', v: encode_filename(mount_options.join(",") || "defaults") },
491 freq: { t: 'i', v: 0 },
492 passno: { t: 'i', v: 0 },
493 "track-parents": { t: 'b', v: true }
494 }]);
495 }
496 }
497
498 if (type == "swap") {
499 config_items.push(["fstab", {
500 dir: { t: 'ay', v: encode_filename("none") },
501 type: { t: 'ay', v: encode_filename("swap") },
502 opts: { t: 'ay', v: encode_filename(mount_now ? "defaults" : "noauto") },
503 freq: { t: 'i', v: 0 },
504 passno: { t: 'i', v: 0 },
505 "track-parents": { t: 'b', v: true }
506 }]);
507 }
508
509 if (config_items.length > 0)
510 options["config-items"] = { t: 'a(sa{sv})', v: config_items };
511
512 async function maybe_unlock() {
513 const content_block = client.blocks_cleartext[path];
514 if (content_block) {
515 if (content_block.ReadOnly) {
516 const block_crypto = client.blocks_crypto[path];
517 await block_crypto.Lock({});
518 await unlock_with_type(client, block, vals.old_passphrase, existing_passphrase_type, false);
519 }
520 return content_block;
521 }
522
523 try {
524 await unlock_with_type(client, block, vals.old_passphrase, existing_passphrase_type, false);
525 return client.blocks_cleartext[path];
526 } catch (error) {
527 dlg.set_values({ needs_explicit_passphrase: true });
528 throw error;
529 }
530 }
531
532 function format() {
533 if (create_partition) {
534 if (type == "dos-extended")
535 return block_ptable.CreatePartition(start, vals.size, "0x05", "", { });
536 else
537 return block_ptable.CreatePartitionAndFormat(start, vals.size, partition_type, "", { },
538 type, options);
539 } else if (keep_keys) {
540 return (edit_crypto_config(block,
541 (config, commit) => {
542 config.options = new_crypto_options;
543 return commit();
544 })
545 .then(() => maybe_unlock())
546 .then(content_block => {
547 return content_block.Format(type, options);
548 }));
549 } else {
550 return block.Format(type, options)
551 .then(() => {
552 if (partition_type != "" && block_part)
553 return block_part.SetType(partition_type, {});
554 });
555 }
556 }
557
558 function block_fsys_for_block(path) {
559 if (keep_keys) {
560 const content_block = client.blocks_cleartext[path];
561 return client.blocks_fsys[content_block.path];
562 } else if (is_encrypted(vals))
563 return (client.blocks_cleartext[path] &&
564 client.blocks_fsys[client.blocks_cleartext[path].path]);
565 else
566 return client.blocks_fsys[path];
567 }
568
569 function block_swap_for_block(path) {
570 if (keep_keys) {
571 const content_block = client.blocks_cleartext[path];
572 return client.blocks_swap[content_block.path];
573 } else if (is_encrypted(vals))
574 return (client.blocks_cleartext[path] &&
575 client.blocks_swap[client.blocks_cleartext[path].path]);
576 else
577 return client.blocks_swap[path];
578 }
579
580 function block_crypto_for_block(path) {
581 return client.blocks_crypto[path];
582 }
583
584 async function maybe_mount(new_path) {
585 const path = new_path || block.path;
586 const new_block = await client.wait_for(() => client.blocks[path]);
587
588 if (is_encrypted(vals) && vals.passphrase)
589 remember_passphrase(new_block, vals.passphrase);
590
591 if (is_encrypted(vals) && is_filesystem(vals) && vals.mount_options?.ro) {
592 const block_crypto = await client.wait_for(() => block_crypto_for_block(path));
593 await block_crypto.Lock({});
594 if (vals.passphrase)
595 await block_crypto.Unlock(vals.passphrase, { "read-only": { t: "b", v: true } });
596 else
597 await unlock_with_type(client, block, vals.old_passphrase, existing_passphrase_type, true);
598 }
599
600 if (is_filesystem(vals) && mount_now) {
601 const block_fsys = await client.wait_for(() => block_fsys_for_block(path));
602 await client.mount_at(client.blocks[block_fsys.path], mount_point);
603 }
604 if (type == "swap" && mount_now) {
605 const block_swap = await client.wait_for(() => block_swap_for_block(path));
606 await block_swap.Start({});
607 }
608 if (is_encrypted(vals) && vals.type != "empty" && !mount_now && !client.in_anaconda_mode()) {
609 const block_crypto = await client.wait_for(() => block_crypto_for_block(path));
610 await block_crypto.Lock({ });
611 }
612 }
613
614 return teardown_active_usage(client, usage)
615 .then(reload_systemd)
616 .then(format)
617 .then(new_path => reload_systemd().then(() => new_path))
618 .then(maybe_mount);
619 }
620 },
621 Inits: [
622 init_teardown_usage(client, usage),
623 unlock_before_format
624 ? init_existing_passphrase(block, true, type => { existing_passphrase_type = type })
625 : null
626 ]
627 });
628 }