Repository navigation
Expand file tree
/
Copy pathrootfs.rs
More file actions
1891 lines (1697 loc) · 68.7 KB
/
Copy pathrootfs.rs
File metadata and controls
1891 lines (1697 loc) · 68.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
use flate2::read::MultiGzDecoder;
use sha2::{Digest, Sha256};
use std::fs;
use std::fs::File;
#[cfg(test)]
use std::io::BufWriter;
use std::io::{BufRead, BufReader, Cursor, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU64, Ordering};
use crate::driver::{DEFAULT_SANDBOX_UID, PREPARED_IMAGE_ROOTFS_DIR};
const SANDBOX: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/openshell-sandbox.zst"));
const SUPERVISOR: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/openshell-supervisor.zst"));
const VM_INIT: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/openshell-vm-init.zst"));
const UMOCI: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/umoci.zst"));
const ROOTFS_VARIANT_MARKER: &str = ".openshell-rootfs-variant";
/// Leading bytes of a gzip stream, used to recognize `.tar.gz`/`.tgz` input
/// without trusting the file name.
pub const GZIP_MAGIC: [u8; 2] = [0x1f, 0x8b];
const SANDBOX_GUEST_INIT_PATH: &str = "/srv/openshell-vm-sandbox-init.sh";
const SANDBOX_SUPERVISOR_PATH: &str = openshell_core::driver_utils::SUPERVISOR_CONTAINER_BINARY;
const SANDBOX_UMOCI_PATH: &str = openshell_core::container_paths::VM_UMOCI_PATH;
const SANDBOX_VM_INIT_PATH: &str = "/opt/openshell/bin/openshell-vm-init";
const ROOTFS_IMAGE_MIN_SIZE_BYTES: u64 = 512 * 1024 * 1024;
const ROOTFS_IMAGE_MIN_HEADROOM_BYTES: u64 = 256 * 1024 * 1024;
const EXT4_IMAGE_MIN_HEADROOM_BYTES: u64 = 16 * 1024 * 1024;
static INJECTION_COUNTER: AtomicU64 = AtomicU64::new(0);
pub const fn sandbox_guest_init_path() -> &'static str {
SANDBOX_GUEST_INIT_PATH
}
/// Identity of every embedded artifact materialized into a bootstrap rootfs.
///
/// Including this in the image-cache key makes local, uncommitted guest-sandbox
/// changes invalidate the cache even when the `OpenShell` version is unchanged.
pub fn sandbox_guest_runtime_identity() -> String {
let mut hasher = Sha256::new();
hasher.update(SANDBOX);
hasher.update(VM_INIT);
hasher.update(UMOCI);
hasher.update(include_bytes!("../scripts/openshell-vm-sandbox-init.sh"));
format!("{:x}", hasher.finalize())
}
/// Materialize the supervisor embedded in the VM driver for host-side use.
pub fn extract_host_supervisor(path: &Path) -> Result<(), String> {
if SUPERVISOR.is_empty() {
return Err(
"host supervisor is not embedded; run `mise run vm:supervisor` and rebuild openshell-driver-vm"
.to_string(),
);
}
let supervisor = embedded_host_supervisor()?;
install_host_supervisor_atomically(path, &supervisor)?;
validate_host_supervisor(path)
}
pub fn validate_host_supervisor(path: &Path) -> Result<(), String> {
validate_host_supervisor_digest(path, embedded_host_supervisor_digest()?)
}
fn validate_host_supervisor_digest(path: &Path, expected: [u8; 32]) -> Result<(), String> {
let metadata = fs::symlink_metadata(path)
.map_err(|error| format!("inspect cached host supervisor {}: {error}", path.display()))?;
if !metadata.file_type().is_file() {
return Err(format!(
"cached host supervisor is not a regular file: {}",
path.display()
));
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
if metadata.permissions().mode() & 0o111 == 0 {
return Err(format!(
"cached host supervisor is not executable: {}",
path.display()
));
}
}
let actual = sha256_reader(
File::open(path)
.map_err(|error| format!("open cached host supervisor {}: {error}", path.display()))?,
)
.map_err(|error| format!("hash cached host supervisor {}: {error}", path.display()))?;
if actual != expected {
return Err(format!(
"cached host supervisor content does not match embedded runtime: {}",
path.display()
));
}
Ok(())
}
fn embedded_host_supervisor() -> Result<Vec<u8>, String> {
zstd::decode_all(Cursor::new(SUPERVISOR))
.map_err(|error| format!("decompress host supervisor: {error}"))
}
fn embedded_host_supervisor_digest() -> Result<[u8; 32], String> {
static DIGEST: OnceLock<Result<[u8; 32], String>> = OnceLock::new();
DIGEST
.get_or_init(|| embedded_host_supervisor().map(|bytes| sha256_bytes(&bytes)))
.clone()
}
fn sha256_bytes(bytes: &[u8]) -> [u8; 32] {
Sha256::digest(bytes).into()
}
fn sha256_reader(mut reader: impl Read) -> std::io::Result<[u8; 32]> {
let mut hasher = Sha256::new();
let mut buffer = [0_u8; 16 * 1024];
loop {
let read = reader.read(&mut buffer)?;
if read == 0 {
break;
}
hasher.update(&buffer[..read]);
}
Ok(hasher.finalize().into())
}
fn install_host_supervisor_atomically(path: &Path, bytes: &[u8]) -> Result<(), String> {
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.ok_or_else(|| format!("host supervisor path has no parent: {}", path.display()))?;
fs::create_dir_all(parent).map_err(|error| format!("create {}: {error}", parent.display()))?;
let temporary = parent.join(format!(
".openshell-sandbox.tmp-{}-{}",
std::process::id(),
INJECTION_COUNTER.fetch_add(1, Ordering::Relaxed)
));
let result = (|| {
let mut options = fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt as _;
options.mode(0o755);
}
let mut file = options
.open(&temporary)
.map_err(|error| format!("create {}: {error}", temporary.display()))?;
file.write_all(bytes)
.map_err(|error| format!("write {}: {error}", temporary.display()))?;
file.sync_all()
.map_err(|error| format!("sync {}: {error}", temporary.display()))?;
fs::rename(&temporary, path).map_err(|error| {
format!(
"commit cached host supervisor {} to {}: {error}",
temporary.display(),
path.display()
)
})?;
File::open(parent)
.and_then(|directory| directory.sync_all())
.map_err(|error| format!("sync host supervisor cache {}: {error}", parent.display()))
})();
if result.is_err() {
let _ = fs::remove_file(&temporary);
}
result
}
#[allow(clippy::similar_names)]
pub fn prepare_sandbox_rootfs_from_image_root(
rootfs: &Path,
image_identity: &str,
sandbox_uid: Option<u32>,
sandbox_gid: Option<u32>,
) -> Result<(), String> {
prepare_sandbox_rootfs(rootfs, sandbox_uid, sandbox_gid)?;
validate_sandbox_rootfs(rootfs)?;
fs::write(
rootfs.join(ROOTFS_VARIANT_MARKER),
format!("{}:image:{image_identity}\n", env!("CARGO_PKG_VERSION")),
)
.map_err(|e| format!("write rootfs variant marker: {e}"))?;
Ok(())
}
/// Extract a rootfs tarball, transparently decompressing gzip archives.
///
/// Compression is detected from the magic bytes rather than the file name:
/// `--from` accepts `.tar.gz` and `.tgz`, but nothing guarantees a caller's
/// extension matches the bytes, and the archives this crate stages internally
/// carry no extension at all.
pub fn extract_rootfs_archive_to(archive_path: &Path, dest: &Path) -> Result<(), String> {
if dest.exists() {
fs::remove_dir_all(dest)
.map_err(|e| format!("remove old rootfs {}: {e}", dest.display()))?;
}
fs::create_dir_all(dest).map_err(|e| format!("create rootfs dir {}: {e}", dest.display()))?;
let file =
File::open(archive_path).map_err(|e| format!("open {}: {e}", archive_path.display()))?;
let mut reader = BufReader::new(file);
let compressed = reader
.fill_buf()
.map_err(|e| format!("read {}: {e}", archive_path.display()))?
.starts_with(&GZIP_MAGIC);
if compressed {
unpack_tar_reader(MultiGzDecoder::new(reader), dest)
} else {
unpack_tar_reader(reader, dest)
}
}
fn unpack_tar_reader(reader: impl Read, dest: &Path) -> Result<(), String> {
tar::Archive::new(reader)
.unpack(dest)
.map_err(|e| format!("extract rootfs tarball into {}: {e}", dest.display()))
}
#[cfg(test)]
pub fn create_rootfs_archive_from_dir(source: &Path, archive_path: &Path) -> Result<(), String> {
if let Some(parent) = archive_path.parent() {
fs::create_dir_all(parent).map_err(|e| format!("create {}: {e}", parent.display()))?;
}
let file = File::create(archive_path)
.map_err(|e| format!("create {}: {e}", archive_path.display()))?;
let writer = BufWriter::new(file);
let mut builder = tar::Builder::new(writer);
append_rootfs_tree_to_archive(&mut builder, source, Path::new("")).map_err(|e| {
format!(
"archive {} into {}: {e}",
source.display(),
archive_path.display()
)
})?;
builder
.finish()
.map_err(|e| format!("finalize {}: {e}", archive_path.display()))
}
pub fn create_rootfs_image_from_dir(source: &Path, image_path: &Path) -> Result<(), String> {
let image_size = rootfs_image_size_bytes(source)?;
create_ext4_image_from_dir_with_size(source, image_path, image_size)?;
if let Err(err) = normalize_sandbox_owner_in_rootfs_image(source, image_path) {
let _ = fs::remove_file(image_path);
return Err(err);
}
Ok(())
}
pub fn create_ext4_image_from_dir_with_size(
source: &Path,
image_path: &Path,
image_size: u64,
) -> Result<(), String> {
if let Some(parent) = image_path.parent() {
fs::create_dir_all(parent).map_err(|e| format!("create {}: {e}", parent.display()))?;
}
if image_path.exists() {
fs::remove_file(image_path)
.map_err(|e| format!("remove old rootfs image {}: {e}", image_path.display()))?;
}
let required_size = ext4_image_min_size_bytes(source)?;
if image_size < required_size {
return Err(format!(
"ext4 image size {} bytes is too small for {} (requires at least {} bytes)",
image_size,
source.display(),
required_size
));
}
let image = File::create(image_path)
.map_err(|e| format!("create rootfs image {}: {e}", image_path.display()))?;
image
.set_len(image_size)
.map_err(|e| format!("size rootfs image {}: {e}", image_path.display()))?;
drop(image);
if let Err(err) = format_ext4_image_from_dir(source, image_path) {
let _ = fs::remove_file(image_path);
return Err(err);
}
Ok(())
}
pub fn clone_or_copy_sparse_file(source: &Path, dest: &Path) -> Result<(), String> {
if let Some(parent) = dest.parent() {
fs::create_dir_all(parent).map_err(|e| format!("create {}: {e}", parent.display()))?;
}
if dest.exists() {
fs::remove_file(dest).map_err(|e| format!("remove old file {}: {e}", dest.display()))?;
}
let clone_error = match try_clone_file(source, dest) {
Ok(()) => return Ok(()),
Err(err) => {
let _ = fs::remove_file(dest);
err
}
};
copy_sparse_file(source, dest).map_err(|copy_error| {
format!(
"clone {} to {} failed ({clone_error}); sparse copy failed: {copy_error}",
source.display(),
dest.display()
)
})
}
pub fn write_rootfs_image_file(
image_path: &Path,
guest_path: &str,
contents: &[u8],
) -> Result<(), String> {
ensure_rootfs_image_parent_dirs(image_path, guest_path);
let tmp_path = temporary_injection_path(image_path);
fs::write(&tmp_path, contents).map_err(|e| format!("write {}: {e}", tmp_path.display()))?;
let Some(quoted_guest_path) = debugfs_quote_absolute_path(guest_path) else {
let _ = fs::remove_file(&tmp_path);
return Err(format!("invalid debugfs guest path '{guest_path}'"));
};
let Some(quoted_tmp_path) = debugfs_quote_argument(&tmp_path.to_string_lossy()) else {
let _ = fs::remove_file(&tmp_path);
return Err(format!(
"invalid debugfs injection path '{}'",
tmp_path.display()
));
};
let _ = run_debugfs(image_path, &format!("rm {quoted_guest_path}"));
let result = run_debugfs(
image_path,
&format!("write {quoted_tmp_path} {quoted_guest_path}"),
);
let _ = fs::remove_file(&tmp_path);
result
}
pub fn remove_rootfs_image_file(image_path: &Path, guest_path: &str) -> Result<(), String> {
let Some(quoted_guest_path) = debugfs_quote_absolute_path(guest_path) else {
return Err(format!("invalid debugfs guest path '{guest_path}'"));
};
run_debugfs(image_path, &format!("rm {quoted_guest_path}"))
}
pub fn set_rootfs_image_file_mode(
image_path: &Path,
guest_path: &str,
mode: u32,
) -> Result<(), String> {
let regular_file_mode = 0o100_000 | (mode & 0o7777);
let Some(quoted_guest_path) = debugfs_quote_absolute_path(guest_path) else {
return Err(format!("invalid debugfs guest path '{guest_path}'"));
};
run_debugfs(
image_path,
&format!("set_inode_field {quoted_guest_path} mode 0{regular_file_mode:o}"),
)
}
/// Replay the ext4 journal and repair automatically correctable filesystem
/// state before the driver mutates a preserved guest disk offline.
pub fn recover_rootfs_image(image_path: &Path) -> Result<(), String> {
let mut command = e2fs_command("e2fsck")?;
let path = PathBuf::from(command.get_program());
let output = command.arg("-p").arg("-f").arg(image_path).output();
match output {
Ok(output) if matches!(output.status.code(), Some(0..=2)) => Ok(()),
Ok(output) => Err(format!(
"{} failed with status {}\nstdout: {}\nstderr: {}",
path.display(),
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
)),
Err(error) => Err(format!("run {}: {error}", path.display())),
}
}
#[cfg(target_os = "macos")]
fn try_clone_file(source: &Path, dest: &Path) -> Result<(), String> {
let output = Command::new("cp")
.arg("-c")
.arg(source)
.arg(dest)
.output()
.map_err(|e| format!("run cp -c: {e}"))?;
if output.status.success() {
return Ok(());
}
Err(format!(
"cp -c failed with status {}\nstdout: {}\nstderr: {}",
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
))
}
#[cfg(target_os = "linux")]
fn try_clone_file(source: &Path, dest: &Path) -> Result<(), String> {
let output = Command::new("cp")
.arg("--reflink=auto")
.arg("--sparse=always")
.arg(source)
.arg(dest)
.output()
.map_err(|e| format!("run cp --reflink=auto: {e}"))?;
if output.status.success() {
return Ok(());
}
Err(format!(
"cp --reflink=auto --sparse=always failed with status {}\nstdout: {}\nstderr: {}",
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
))
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
fn try_clone_file(_source: &Path, _dest: &Path) -> Result<(), String> {
Err("no platform clone command available".to_string())
}
fn copy_sparse_file(source: &Path, dest: &Path) -> Result<(), String> {
const BUFFER_SIZE: usize = 1024 * 1024;
let mut source_file =
File::open(source).map_err(|e| format!("open {}: {e}", source.display()))?;
let mut dest_file =
File::create(dest).map_err(|e| format!("create {}: {e}", dest.display()))?;
let mut buffer = vec![0_u8; BUFFER_SIZE];
let mut size = 0_u64;
loop {
let read = source_file
.read(&mut buffer)
.map_err(|e| format!("read {}: {e}", source.display()))?;
if read == 0 {
break;
}
if buffer[..read].iter().all(|byte| *byte == 0) {
let skip =
i64::try_from(read).map_err(|_| format!("sparse copy chunk too large: {read}"))?;
dest_file
.seek(SeekFrom::Current(skip))
.map_err(|e| format!("seek {}: {e}", dest.display()))?;
} else {
dest_file
.write_all(&buffer[..read])
.map_err(|e| format!("write {}: {e}", dest.display()))?;
}
size += read as u64;
}
dest_file
.set_len(size)
.map_err(|e| format!("size {}: {e}", dest.display()))
}
#[cfg(test)]
fn append_rootfs_tree_to_archive(
builder: &mut tar::Builder<BufWriter<File>>,
source: &Path,
archive_prefix: &Path,
) -> Result<(), String> {
let mut entries = fs::read_dir(source)
.map_err(|e| format!("read {}: {e}", source.display()))?
.collect::<Result<Vec<_>, _>>()
.map_err(|e| format!("read {}: {e}", source.display()))?;
entries.sort_by_key(fs::DirEntry::file_name);
for entry in entries {
let entry_name = entry.file_name();
let source_path = entry.path();
let archive_path = if archive_prefix.as_os_str().is_empty() {
entry_name.into()
} else {
archive_prefix.join(entry_name)
};
let metadata = fs::symlink_metadata(&source_path)
.map_err(|e| format!("stat {}: {e}", source_path.display()))?;
let file_type = metadata.file_type();
if file_type.is_dir() {
builder
.append_dir(&archive_path, &source_path)
.map_err(|e| format!("append dir {}: {e}", source_path.display()))?;
append_rootfs_tree_to_archive(builder, &source_path, &archive_path)?;
continue;
}
if file_type.is_file() {
let mut file = File::open(&source_path)
.map_err(|e| format!("open {}: {e}", source_path.display()))?;
builder
.append_file(&archive_path, &mut file)
.map_err(|e| format!("append file {}: {e}", source_path.display()))?;
continue;
}
if file_type.is_symlink() {
append_symlink_to_archive(builder, &source_path, &archive_path, &metadata)?;
continue;
}
return Err(format!(
"unsupported rootfs entry type at {}",
source_path.display()
));
}
Ok(())
}
#[cfg(test)]
fn append_symlink_to_archive(
builder: &mut tar::Builder<BufWriter<File>>,
source_path: &Path,
archive_path: &Path,
metadata: &fs::Metadata,
) -> Result<(), String> {
let target = fs::read_link(source_path)
.map_err(|e| format!("readlink {}: {e}", source_path.display()))?;
let mut header = tar::Header::new_gnu();
header.set_metadata(metadata);
header.set_size(0);
header.set_cksum();
builder
.append_link(&mut header, archive_path, target)
.map_err(|e| format!("append symlink {}: {e}", source_path.display()))
}
#[allow(clippy::similar_names)]
fn prepare_sandbox_rootfs(
rootfs: &Path,
sandbox_uid: Option<u32>,
sandbox_gid: Option<u32>,
) -> Result<(), String> {
for relative in ["opt/openshell/.initialized", "opt/openshell/.rootfs-type"] {
remove_rootfs_path(rootfs, relative)?;
}
let init_path = rootfs.join("srv/openshell-vm-sandbox-init.sh");
if let Some(parent) = init_path.parent() {
create_guest_dir_all(parent)?;
}
fs::write(
&init_path,
include_str!("../scripts/openshell-vm-sandbox-init.sh"),
)
.map_err(|e| format!("write {}: {e}", init_path.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
fs::set_permissions(&init_path, fs::Permissions::from_mode(0o755))
.map_err(|e| format!("chmod {}: {e}", init_path.display()))?;
}
ensure_supervisor_binary(rootfs)?;
ensure_vm_init_binary(rootfs)?;
ensure_umoci_binary(rootfs)?;
let opt_dir = rootfs.join("opt/openshell");
create_guest_dir_all(&opt_dir)?;
fs::write(opt_dir.join(".rootfs-type"), "sandbox\n")
.map_err(|e| format!("write sandbox rootfs marker: {e}"))?;
ensure_sandbox_guest_user(rootfs, sandbox_uid, sandbox_gid)?;
create_sandbox_mountpoint(&rootfs.join("sandbox"))?;
create_sandbox_mountpoint(&rootfs.join("image-cache"))?;
create_sandbox_mountpoint(&rootfs.join("lower"))?;
create_sandbox_mountpoint(&rootfs.join("overlay"))?;
create_sandbox_mountpoint(&rootfs.join("newroot"))?;
Ok(())
}
pub fn validate_sandbox_rootfs(rootfs: &Path) -> Result<(), String> {
require_rootfs_path(rootfs, SANDBOX_GUEST_INIT_PATH)?;
require_rootfs_path(rootfs, SANDBOX_SUPERVISOR_PATH)?;
require_rootfs_path(rootfs, SANDBOX_VM_INIT_PATH)?;
require_rootfs_path(rootfs, SANDBOX_UMOCI_PATH)?;
require_any_rootfs_path(rootfs, &["/bin/bash"])?;
require_any_rootfs_path(rootfs, &["/bin/mount", "/usr/bin/mount"])?;
require_any_rootfs_path(
rootfs,
&[
"/usr/sbin/chroot",
"/usr/bin/chroot",
"/sbin/chroot",
"/bin/chroot",
],
)?;
require_any_rootfs_path(rootfs, &["/bin/sed", "/usr/bin/sed"])?;
Ok(())
}
fn create_sandbox_mountpoint(path: &Path) -> Result<(), String> {
create_guest_dir_all(path)?;
chmod_guest_dir(path)
}
/// Like `create_dir_all`, but each directory it makes is 0755 whatever the
/// umask. The sandbox user must be able to traverse the guest rootfs.
fn create_guest_dir_all(path: &Path) -> Result<(), String> {
if path.is_dir() {
return Ok(());
}
if let Some(parent) = path.parent() {
create_guest_dir_all(parent)?;
}
fs::create_dir(path).map_err(|e| format!("create {}: {e}", path.display()))?;
chmod_guest_dir(path)
}
fn chmod_guest_dir(path: &Path) -> Result<(), String> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
fs::set_permissions(path, fs::Permissions::from_mode(0o755))
.map_err(|e| format!("chmod {}: {e}", path.display()))?;
}
#[cfg(not(unix))]
let _ = path;
Ok(())
}
fn rootfs_image_size_bytes(source: &Path) -> Result<u64, String> {
let used = directory_size_bytes(source)?;
let headroom = (used / 4).max(ROOTFS_IMAGE_MIN_HEADROOM_BYTES);
let size = (used + headroom).max(ROOTFS_IMAGE_MIN_SIZE_BYTES);
Ok(round_up_to_mib(size))
}
fn ext4_image_min_size_bytes(source: &Path) -> Result<u64, String> {
let used = directory_size_bytes(source)?;
Ok(round_up_to_mib(used + EXT4_IMAGE_MIN_HEADROOM_BYTES))
}
fn directory_size_bytes(path: &Path) -> Result<u64, String> {
let metadata =
fs::symlink_metadata(path).map_err(|e| format!("stat {}: {e}", path.display()))?;
if metadata.file_type().is_file() || metadata.file_type().is_symlink() {
return Ok(metadata.len());
}
if !metadata.file_type().is_dir() {
return Ok(0);
}
let mut size = 4096;
for entry in fs::read_dir(path).map_err(|e| format!("read {}: {e}", path.display()))? {
let entry = entry.map_err(|e| format!("read {}: {e}", path.display()))?;
size += directory_size_bytes(&entry.path())?;
}
Ok(size)
}
fn round_up_to_mib(bytes: u64) -> u64 {
const MIB: u64 = 1024 * 1024;
bytes.div_ceil(MIB) * MIB
}
fn format_ext4_image_from_dir(source: &Path, image_path: &Path) -> Result<(), String> {
let path = openshell_core::e2fsprogs::resolve(&["mke2fs", "mkfs.ext4"])?;
let output = Command::new(&path)
.arg("-q")
.arg("-F")
.arg("-t")
.arg("ext4")
.arg("-E")
.arg("root_owner=0:0")
.arg("-d")
.arg(source)
.arg(image_path)
.output()
.map_err(|error| format!("run {}: {error}", path.display()))?;
if output.status.success() {
return Ok(());
}
// A selected formatter failure must retain its diagnostics. Retrying with
// another installation can overwrite a partial image and hide the cause.
Err(format!(
"failed to create ext4 rootfs image from {}: {} failed with status {}\nstdout: {}\nstderr: {}",
source.display(),
path.display(),
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
))
}
fn ensure_rootfs_image_parent_dirs(image_path: &Path, guest_path: &str) {
let Some(parent) = Path::new(guest_path).parent() else {
return;
};
let mut current = String::new();
for component in parent.components() {
let part = component.as_os_str().to_string_lossy();
if part == "/" || part.is_empty() {
continue;
}
current.push('/');
current.push_str(&part);
let _ = run_debugfs(image_path, &format!("mkdir {current}"));
}
}
fn normalize_sandbox_owner_in_rootfs_image(source: &Path, image_path: &Path) -> Result<(), String> {
let sandbox_dir = source.join("sandbox");
if !sandbox_dir.exists() {
return Ok(());
}
let Some((uid, gid)) = sandbox_guest_user_ids(source)? else {
return Ok(());
};
let mut commands = Vec::new();
if !collect_sandbox_owner_commands(&sandbox_dir, "/sandbox", uid, gid, &mut commands)? {
return Ok(());
}
if commands.is_empty() {
return Ok(());
}
run_debugfs_batch(image_path, &commands)
}
fn collect_sandbox_owner_commands(
source_path: &Path,
guest_path: &str,
uid: u32,
gid: u32,
commands: &mut Vec<String>,
) -> Result<bool, String> {
let metadata = fs::symlink_metadata(source_path).map_err(|e| {
format!(
"stat {} for rootfs ownership normalization: {e}",
source_path.display()
)
})?;
if metadata.file_type().is_symlink() {
return Ok(true);
}
let Some(quoted_guest_path) = debugfs_quote_absolute_path(guest_path) else {
return Ok(false);
};
commands.push(format!("set_inode_field {quoted_guest_path} uid {uid}"));
commands.push(format!("set_inode_field {quoted_guest_path} gid {gid}"));
if !metadata.is_dir() {
return Ok(true);
}
let mut entries = fs::read_dir(source_path)
.map_err(|e| {
format!(
"read {} for rootfs ownership normalization: {e}",
source_path.display()
)
})?
.collect::<Result<Vec<_>, _>>()
.map_err(|e| {
format!(
"read {} entry for rootfs ownership normalization: {e}",
source_path.display()
)
})?;
entries.sort_by_key(fs::DirEntry::file_name);
for entry in entries {
let file_name = entry.file_name();
let Some(file_name) = file_name.to_str() else {
return Ok(false);
};
let child_guest_path = format!("{guest_path}/{file_name}");
if !collect_sandbox_owner_commands(&entry.path(), &child_guest_path, uid, gid, commands)? {
return Ok(false);
}
}
Ok(true)
}
fn debugfs_quote_absolute_path(path: &str) -> Option<String> {
if path.is_empty() || !path.starts_with('/') {
return None;
}
debugfs_quote_argument(path)
}
fn debugfs_quote_argument(argument: &str) -> Option<String> {
if argument.is_empty() {
return None;
}
let mut quoted = String::with_capacity(argument.len() + 2);
quoted.push('"');
for ch in argument.chars() {
match ch {
'\0' | '\n' | '\r' => return None,
'\\' => quoted.push_str("\\\\"),
'"' => quoted.push_str("\\\""),
_ => quoted.push(ch),
}
}
quoted.push('"');
Some(quoted)
}
/// Read the sandbox account identity directly from an ext4 rootfs image.
///
/// Persisted VM overlays may outlive the prepared-image cache layout that
/// created them. Reading the matching old lower disk lets the driver preserve
/// that overlay's real ownership contract during an upgrade.
pub fn sandbox_guest_user_ids_from_image(image_path: &Path) -> Result<Option<(u32, u32)>, String> {
if ext4_image_has_directory(image_path, PREPARED_IMAGE_ROOTFS_DIR)? {
let passwd = format!("{PREPARED_IMAGE_ROOTFS_DIR}/etc/passwd");
return sandbox_guest_user_ids_from_image_path(image_path, &passwd);
}
sandbox_guest_user_ids_from_image_path(image_path, "/etc/passwd")
}
/// Read a sandbox account copied into an overlay upper layer.
///
/// An upper-layer passwd file is the most direct evidence of the identity an
/// existing overlay observed, so migration consults it before any lower image.
pub fn sandbox_guest_user_ids_from_overlay_image(
image_path: &Path,
) -> Result<Option<(u32, u32)>, String> {
sandbox_guest_user_ids_from_image_path(image_path, "/upper/etc/passwd")
}
/// Check, without mounting, whether an ext4 image has a directory at
/// `guest_path`. Symlinks are not followed.
pub fn ext4_image_has_directory(image_path: &Path, guest_path: &str) -> Result<bool, String> {
let quoted_path = debugfs_quote_absolute_path(guest_path)
.ok_or_else(|| format!("invalid debugfs guest path '{guest_path}'"))?;
let command = format!("stat {quoted_path}");
let output = e2fs_command("debugfs")?
.arg("-R")
.arg(&command)
.arg(image_path)
.output();
match output {
Ok(output) if output.status.success() => {
// debugfs exits 0 whether or not the path exists; the answer
// is only in its output.
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
if stdout.contains("Type: directory") {
return Ok(true);
}
if stdout.contains("Type: ") || stderr.contains("File not found") {
return Ok(false);
}
Err(format!(
"debugfs command '{command}' produced unrecognized output for {}\nstdout: {stdout}\nstderr: {stderr}",
image_path.display()
))
}
Ok(output) => Err(format!(
"debugfs command '{command}' failed for {}: debugfs failed with status {}\nstdout: {}\nstderr: {}. Install e2fsprogs (debugfs) and retry",
image_path.display(),
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
)),
Err(error) => Err(format!(
"debugfs command '{command}' failed for {}: {error}. Install e2fsprogs (debugfs) and retry",
image_path.display()
)),
}
}
fn sandbox_guest_user_ids_from_image_path(
image_path: &Path,
guest_path: &str,
) -> Result<Option<(u32, u32)>, String> {
let metadata = fs::metadata(image_path)
.map_err(|error| format!("stat rootfs image {}: {error}", image_path.display()))?;
if !metadata.is_file() {
return Err(format!(
"rootfs image {} is not a regular file",
image_path.display()
));
}
let quoted_path = debugfs_quote_absolute_path(guest_path)
.expect("the static passwd path is a valid debugfs path");
let command = format!("cat {quoted_path}");
let output = e2fs_command("debugfs")?
.arg("-R")
.arg(&command)
.arg(image_path)
.output();
match output {
Ok(output) if output.status.success() => {
let passwd = String::from_utf8(output.stdout).map_err(|error| {
format!(
"read {guest_path} from {} as UTF-8: {error}",
image_path.display()
)
})?;
parse_sandbox_guest_user_ids(&passwd, &image_path.display().to_string())
}
Ok(output) => Err(format!(
"debugfs command '{command}' failed for {}: debugfs failed with status {}\nstdout: {}\nstderr: {}. Install e2fsprogs (debugfs) and retry",
image_path.display(),
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
)),
Err(error) => Err(format!(
"debugfs command '{command}' failed for {}: {error}. Install e2fsprogs (debugfs) and retry",
image_path.display()
)),
}
}
fn sandbox_guest_user_ids(rootfs: &Path) -> Result<Option<(u32, u32)>, String> {
let passwd_path = rootfs.join("etc/passwd");
if !passwd_path.exists() {
return Ok(None);
}
let passwd = fs::read_to_string(&passwd_path)
.map_err(|e| format!("read {}: {e}", passwd_path.display()))?;
parse_sandbox_guest_user_ids(&passwd, &passwd_path.display().to_string())
}
fn parse_sandbox_guest_user_ids(passwd: &str, source: &str) -> Result<Option<(u32, u32)>, String> {
for line in passwd.lines() {
let mut parts = line.split(':');
if parts.next() != Some("sandbox") {
continue;
}
let _password = parts.next();
let uid = parts
.next()
.ok_or_else(|| format!("sandbox entry in {source} is missing uid"))?
.parse::<u32>()
.map_err(|e| format!("sandbox uid in {source} is invalid: {e}"))?;
let gid = parts
.next()
.ok_or_else(|| format!("sandbox entry in {source} is missing gid"))?
.parse::<u32>()
.map_err(|e| format!("sandbox gid in {source} is invalid: {e}"))?;
return Ok(Some((uid, gid)));
}
Ok(None)
}
fn run_debugfs_batch(image_path: &Path, commands: &[String]) -> Result<(), String> {
let command_path = temporary_injection_path(image_path);
let mut contents = commands.join("\n");
contents.push('\n');
fs::write(&command_path, contents)
.map_err(|e| format!("write {}: {e}", command_path.display()))?;
let result = run_debugfs_batch_file(image_path, &command_path);
let _ = fs::remove_file(&command_path);
result
}
fn run_debugfs_batch_file(image_path: &Path, command_path: &Path) -> Result<(), String> {
let output = e2fs_command("debugfs")?
.arg("-w")
.arg("-f")
.arg(command_path)
.arg(image_path)
.output();
match output {
Ok(output) if output.status.success() => Ok(()),
Ok(output) => Err(format!(
"debugfs batch {} failed for {}: debugfs failed with status {}\nstdout: {}\nstderr: {}. Install e2fsprogs (debugfs) and retry",
command_path.display(),
image_path.display(),
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
)),
Err(error) => Err(format!(
"debugfs batch {} failed for {}: {error}. Install e2fsprogs (debugfs) and retry",
command_path.display(),
image_path.display()