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
|
use anyhow::bail;
use cargo::core::compiler::{BuildConfig, CompileMode};
use cargo::core::SourceId;
use cargo::ops::{CompileFilter, CompileOptions};
use cargo::util::config::Config as CargoConfig;
use cargo::util::interning::InternedString;
use clap::Parser;
use fatfs::{FatType, FormatVolumeOptions};
use fscommon::StreamSlice;
use reqwest::Url;
use squashfs_ng::write::{
Source as SqsSource, SourceData as SqsSourceData, SourceFile as SqsSourceFile,
TreeProcessor as SqsTreeProcessor,
};
use std::collections::{BTreeMap, HashMap};
use std::ffi::{OsStr, OsString};
use std::fs::{File, OpenOptions};
use std::io::{self, prelude::*};
use std::os::unix::fs::PermissionsExt;
use std::os::unix::io::AsRawFd;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
const MODE_DEVICE: u32 = 1 << 14;
#[allow(non_upper_case_globals)]
const KiB: u32 = 1024;
#[allow(non_upper_case_globals)]
const MiB: u32 = 1024 * KiB;
const KERNEL_BASE: &str = "https://github.com/rustkrazy/kernel/raw/master/";
const FIRMWARE_BASE: &str = "https://github.com/rustkrazy/firmware/raw/master/";
#[derive(Debug, Parser)]
#[command(author = "The Rustkrazy Authors", version = "v0.1.0", about = "Generate a rustkrazy image.", long_about = None)]
struct Args {
/// Output location of a full image.
#[arg(short = 'o', long = "overwrite")]
overwrite: String,
/// Size of image file in bytes. Used if --overwrite is a file.
#[arg(short = 'n', long = "size")]
size: Option<u64>,
/// Architecture of the device running the image. Supported: x86_64 rpi.
#[arg(short = 'a', long = "architecture")]
arch: String,
/// Crates to install into the image.
#[arg(short = 'c', long = "crates")]
crates: Vec<String>,
/// Crates to install from git.
#[arg(short = 'g', long = "git")]
git: Vec<String>,
/// Init crate. rustkrazy_init is a reasonable default for most applications.
#[arg(short = 'i', long = "init")]
init: String,
}
#[cfg(target_os = "linux")]
fn device_size(file: &File, path: String) -> anyhow::Result<u64> {
use nix::ioctl_read;
const BLKGETSIZE64_CODE: u8 = 0x12;
const BLKGETSIZE64_SEQ: u8 = 114;
ioctl_read!(ioctl_blkgetsize64, BLKGETSIZE64_CODE, BLKGETSIZE64_SEQ, u64);
let fd = file.as_raw_fd();
let mut dev_size = 0;
let dev_size_ptr = &mut dev_size as *mut u64;
unsafe {
match ioctl_blkgetsize64(fd, dev_size_ptr) {
Ok(_) => {}
Err(_) => bail!("{} does not seem to be a device", path),
}
}
Ok(dev_size)
}
fn write_mbr_partition_table(file: &mut File, dev_size: u64) -> anyhow::Result<()> {
const INACTIVE: &[u8] = &[0x00];
const ACTIVE: &[u8] = &[0x80];
const INVALID_CHS: &[u8] = &[0xFF, 0xFF, 0xFE]; // Causes sector values to be used
const FAT: &[u8] = &[0xc];
const LINUX: &[u8] = &[0x83];
const SQUASHFS: &[u8] = LINUX;
const SIGNATURE: &[u8] = &[0x55, 0xAA];
file.write_all(&[0; 446])?; // Boot code
// Partition 1: boot
file.write_all(ACTIVE)?;
file.write_all(INVALID_CHS)?;
file.write_all(FAT)?;
file.write_all(INVALID_CHS)?;
file.write_all(&2048_u32.to_le_bytes())?; // Start at sector 2048
file.write_all(&(256 * MiB / 512).to_le_bytes())?; // 256 MiB in size
// Partition 2: rootfs A
file.write_all(INACTIVE)?;
file.write_all(INVALID_CHS)?;
file.write_all(SQUASHFS)?;
file.write_all(INVALID_CHS)?;
file.write_all(&(2048 + 256 * MiB / 512).to_le_bytes())?;
file.write_all(&(256 * MiB / 512).to_le_bytes())?;
// Partition 3: rootfs B
file.write_all(INACTIVE)?;
file.write_all(INVALID_CHS)?;
file.write_all(SQUASHFS)?;
file.write_all(INVALID_CHS)?;
file.write_all(&(2048 + 2 * (256 * MiB / 512)).to_le_bytes())?;
file.write_all(&(256 * MiB / 512).to_le_bytes())?;
// Partition 4: data
file.write_all(INACTIVE)?;
file.write_all(INVALID_CHS)?;
file.write_all(LINUX)?;
file.write_all(INVALID_CHS)?;
file.write_all(&(2048 + 3 * (256 * MiB / 512)).to_le_bytes())?;
file.write_all(&(dev_size as u32 / 512 - 2048 - 3 * (256 * MiB / 512)).to_le_bytes())?;
file.write_all(SIGNATURE)?;
println!("Partition table written successfully");
Ok(())
}
fn partition(
file: &mut File,
dev_size: u64,
arch: String,
crates: Vec<String>,
git: Vec<String>,
init: String,
) -> anyhow::Result<()> {
const ROOT_A_START: u64 = (2048 * 512 + 256 * MiB) as u64;
let root_a_end = ROOT_A_START + (256 * MiB) as u64;
let root_b_end = root_a_end + (256 * MiB) as u64;
let data_end = root_b_end + (dev_size / 512 - 2048 - 3 * (256 * MiB / 512) as u64);
write_mbr_partition_table(file, dev_size)?;
let mut boot_partition = StreamSlice::new(file.try_clone()?, 2048 * 512, ROOT_A_START - 1)?;
let mut root_partition_a = StreamSlice::new(file.try_clone()?, ROOT_A_START, root_a_end - 1)?;
let mut root_partition_b = StreamSlice::new(file.try_clone()?, root_a_end, root_b_end - 1)?;
let mut data_partition = StreamSlice::new(file.try_clone()?, root_b_end, data_end - 1)?;
let buf = write_boot(&mut boot_partition, &arch)?;
write_mbr(file, &buf["kernel.img"], &buf["cmdline.txt"])?;
write_root(&mut root_partition_a, &arch, &crates, &git, &init)?;
write_empty_root(&mut root_partition_b)?;
format_ext4(&mut data_partition)?;
Ok(())
}
fn partition_device(
file: &mut File,
overwrite: String,
arch: String,
crates: Vec<String>,
git: Vec<String>,
init: String,
) -> anyhow::Result<()> {
let dev_size = device_size(file, overwrite)?;
println!("Destination holds {} bytes", dev_size);
partition(file, dev_size, arch, crates, git, init)?;
Ok(())
}
fn write_boot(
partition: &mut StreamSlice<File>,
arch: &str,
) -> anyhow::Result<BTreeMap<String, Vec<u8>>> {
match arch {
"x86_64" => {}
"rpi" => {}
_ => bail!("invalid architecture (supported: x86_64 rpi)"),
}
let format_opts = FormatVolumeOptions::new().fat_type(FatType::Fat32);
fatfs::format_volume(&mut *partition, format_opts)?;
let fs = fatfs::FileSystem::new(partition, fatfs::FsOptions::new())?;
let root_dir = fs.root_dir();
println!("Installing kernel...");
let mut buf = BTreeMap::new();
let mut copy = BTreeMap::new();
copy.insert("kernel.img", format!("vmlinuz-{}", arch));
copy.insert("cmdline.txt", String::from("cmdline.txt"));
for (dst, src) in copy {
let mut file = root_dir.create_file(dst)?;
let mut resp = reqwest::blocking::get(KERNEL_BASE.to_owned() + &src)?.error_for_status()?;
buf.insert(dst.to_owned(), Vec::new());
resp.copy_to(buf.get_mut(dst).unwrap())?;
io::copy(&mut buf.get(dst).unwrap().as_slice(), &mut file)?;
}
// We don't need the firmware to boot on other supported architectures.
if arch == "rpi" {
println!("Installing RPi firmware...");
let fwcopy = [
"bootcode.bin",
"fixup.dat",
"fixup4.dat",
"fixup4cd.dat",
"fixup4db.dat",
"fixup4x.dat",
"fixup_cd.dat",
"fixup_db.dat",
"fixup_x.dat",
"start.elf",
"start4.elf",
"start4cd.elf",
"start4db.elf",
"start4x.elf",
"start_cd.elf",
"start_db.elf",
"start_x.elf",
];
for fw in fwcopy {
println!("Installing RPi firmware: {}", fw);
let mut file = root_dir.create_file(fw)?;
let mut resp =
reqwest::blocking::get(FIRMWARE_BASE.to_owned() + fw)?.error_for_status()?;
let mut data = Vec::new();
resp.copy_to(&mut data)?;
io::copy(&mut data.as_slice(), &mut file)?;
}
}
println!("Boot filesystem created successfully");
Ok(buf)
}
fn write_mbr(file: &mut File, kernel_buf: &[u8], cmdline_buf: &[u8]) -> anyhow::Result<()> {
let mut buf = Vec::new();
file.read_to_end(&mut buf)?;
let kernel_offset: u32 = (buf
.windows(kernel_buf.len())
.position(|window| window == kernel_buf)
.expect("can't find kernel (/kernel.img) on boot partition")
/ 512
+ 1)
.try_into()?;
let cmdline_offset: u32 = (buf
.windows(cmdline_buf.len())
.position(|window| window == cmdline_buf)
.expect("can't find cmdline (/cmdline.txt) on boot partition")
/ 512
+ 1)
.try_into()?;
let kernel_lba = kernel_offset + 2048;
let cmdline_lba = cmdline_offset + 2048;
let mut bootloader_params = Vec::new();
bootloader_params.extend_from_slice(&kernel_lba.to_le_bytes());
bootloader_params.extend_from_slice(&cmdline_lba.to_le_bytes());
let mut bootloader_file = File::open("boot.bin")?;
let mut bootloader_buf = Vec::new();
bootloader_file.read_to_end(&mut bootloader_buf)?;
bootloader_buf.resize(432, 0);
file.rewind()?;
file.write_all(&bootloader_buf[..432])?;
file.write_all(&bootloader_params)?;
println!("MBR written successfully");
println!("MBR summary:");
println!(
" LBA: kernel.img={}, cmdline.txt={}",
kernel_lba, cmdline_lba
);
Ok(())
}
fn write_root(
partition: &mut StreamSlice<File>,
arch: &str,
crates: &Vec<String>,
git: &Vec<String>,
init: &str,
) -> anyhow::Result<()> {
let target = match arch {
"x86_64" => "x86_64",
"rpi" => "aarch64",
_ => bail!("invalid architecture (supported: x86_64 rpi)"),
};
let target_triple = format!("{}-unknown-linux-musl", target);
println!("Installing crates: {:?}", crates);
println!("Installing git: {:?}", git);
let tmp_dir = tempfile::tempdir()?;
let mut cargo_opts = CargoConfig::default()?;
let mut compile_opts = CompileOptions::new(&CargoConfig::default()?, CompileMode::Build)?;
cargo_opts.configure(0, false, None, false, false, false, &None, &[], &[])?;
compile_opts.build_config = BuildConfig::new(
&CargoConfig::default()?,
None,
false,
&[target_triple],
CompileMode::Build,
)?;
compile_opts.build_config.requested_profile = InternedString::new("release");
if arch == "rpi" {
let rustc_args = vec![
String::from("-C"),
String::from("linker=aarch64-linux-gnu-ld"),
];
compile_opts.target_rustc_args = Some(rustc_args);
}
for crate_name in crates {
compile_opts.filter = CompileFilter::single_bin(crate_name.to_owned());
cargo::ops::install(
&cargo_opts,
Some(tmp_dir.path().to_str().unwrap()), // root (output dir)
vec![(crate_name, None)],
SourceId::crates_io(&CargoConfig::default()?)?,
false, // from_cwd
&compile_opts,
false, // force
true, // no_track
)?;
}
for location in git {
let mut split = location.split('%');
let url = Url::parse(split.next().unwrap())?;
let pkg = split.next().unwrap_or(
url.path_segments()
.unwrap()
.next_back()
.unwrap()
.trim_end_matches(".git"),
);
compile_opts.filter = CompileFilter::single_bin(pkg.to_owned());
cargo::ops::install(
&cargo_opts,
Some(tmp_dir.path().to_str().unwrap()), // root (output dir)
vec![(pkg, None)],
SourceId::from_url(&("git+".to_owned() + url.as_str()))?,
false, // from_cwd
&compile_opts,
false, // force
true, // no_track
)?;
}
let mut tmp_file = tempfile::NamedTempFile::new()?;
io::copy(partition, &mut tmp_file)?;
let tree = SqsTreeProcessor::new(tmp_file.path())?;
let mut crate_inodes = Vec::new();
for pkg in crates {
let crate_path = tmp_dir.path().join("bin/".to_owned() + pkg);
let crate_file = File::open(crate_path)?;
crate_inodes.push(tree.add(SqsSourceFile {
path: Path::new("/bin").join(if pkg == init { "init" } else { pkg }),
content: SqsSource {
data: SqsSourceData::File(Box::new(crate_file)),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?);
}
for location in git {
let mut split = location.split('%');
let url = Url::parse(split.next().unwrap())?;
let pkg = split.next().unwrap_or(
url.path_segments()
.unwrap()
.next_back()
.unwrap()
.trim_end_matches(".git"),
);
let crate_path = tmp_dir.path().join("bin/".to_owned() + pkg);
let crate_file = File::open(crate_path)?;
crate_inodes.push(tree.add(SqsSourceFile {
path: Path::new("/bin").join(if pkg == init { "init" } else { pkg }),
content: SqsSource {
data: SqsSourceData::File(Box::new(crate_file)),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?);
}
let init2 = String::from(init);
let bin_inode = tree.add(SqsSourceFile {
path: PathBuf::from("/bin"),
content: SqsSource {
data: SqsSourceData::Dir(Box::new(
crates
.clone()
.into_iter()
.map(move |pkg| {
if pkg == init2 {
String::from("init")
} else {
pkg
}
})
.map(OsString::from)
.zip(crate_inodes.into_iter()),
)),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?;
let dev_inode = tree.add(SqsSourceFile {
path: PathBuf::from("/dev"),
content: SqsSource {
data: SqsSourceData::Dir(Box::new(Vec::new().into_iter())),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?;
let boot_inode = tree.add(SqsSourceFile {
path: PathBuf::from("/boot"),
content: SqsSource {
data: SqsSourceData::Dir(Box::new(Vec::new().into_iter())),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?;
let data_inode = tree.add(SqsSourceFile {
path: PathBuf::from("/data"),
content: SqsSource {
data: SqsSourceData::Dir(Box::new(Vec::new().into_iter())),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?;
let proc_inode = tree.add(SqsSourceFile {
path: PathBuf::from("/proc"),
content: SqsSource {
data: SqsSourceData::Dir(Box::new(Vec::new().into_iter())),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?;
let tmp_inode = tree.add(SqsSourceFile {
path: PathBuf::from("/tmp"),
content: SqsSource {
data: SqsSourceData::Dir(Box::new(Vec::new().into_iter())),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?;
let run_inode = tree.add(SqsSourceFile {
path: PathBuf::from("/run"),
content: SqsSource {
data: SqsSourceData::Dir(Box::new(Vec::new().into_iter())),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?;
tree.add(SqsSourceFile {
path: PathBuf::from("/"),
content: SqsSource {
data: SqsSourceData::Dir(Box::new(
vec![
(OsString::from("bin"), bin_inode),
(OsString::from("dev"), dev_inode),
(OsString::from("boot"), boot_inode),
(OsString::from("data"), data_inode),
(OsString::from("proc"), proc_inode),
(OsString::from("tmp"), tmp_inode),
(OsString::from("run"), run_inode),
]
.into_iter(),
)),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?;
tree.finish()?;
tmp_file.rewind()?;
partition.rewind()?;
io::copy(&mut tmp_file, partition)?;
println!("Root filesystem A created successfully");
Ok(())
}
fn write_empty_root(partition: &mut StreamSlice<File>) -> anyhow::Result<()> {
let mut tmp_file = tempfile::NamedTempFile::new()?;
io::copy(partition, &mut tmp_file)?;
let tree = SqsTreeProcessor::new(tmp_file.path())?;
let bin_inode = tree.add(SqsSourceFile {
path: PathBuf::from("/bin"),
content: SqsSource {
data: SqsSourceData::Dir(Box::new(Vec::new().into_iter())),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?;
let dev_inode = tree.add(SqsSourceFile {
path: PathBuf::from("/dev"),
content: SqsSource {
data: SqsSourceData::Dir(Box::new(Vec::new().into_iter())),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?;
let boot_inode = tree.add(SqsSourceFile {
path: PathBuf::from("/boot"),
content: SqsSource {
data: SqsSourceData::Dir(Box::new(Vec::new().into_iter())),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?;
let data_inode = tree.add(SqsSourceFile {
path: PathBuf::from("/data"),
content: SqsSource {
data: SqsSourceData::Dir(Box::new(Vec::new().into_iter())),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?;
let proc_inode = tree.add(SqsSourceFile {
path: PathBuf::from("/proc"),
content: SqsSource {
data: SqsSourceData::Dir(Box::new(Vec::new().into_iter())),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?;
let tmp_inode = tree.add(SqsSourceFile {
path: PathBuf::from("/tmp"),
content: SqsSource {
data: SqsSourceData::Dir(Box::new(Vec::new().into_iter())),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?;
let run_inode = tree.add(SqsSourceFile {
path: PathBuf::from("/run"),
content: SqsSource {
data: SqsSourceData::Dir(Box::new(Vec::new().into_iter())),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?;
tree.add(SqsSourceFile {
path: PathBuf::from("/"),
content: SqsSource {
data: SqsSourceData::Dir(Box::new(
vec![
(OsString::from("bin"), bin_inode),
(OsString::from("dev"), dev_inode),
(OsString::from("boot"), boot_inode),
(OsString::from("data"), data_inode),
(OsString::from("proc"), proc_inode),
(OsString::from("tmp"), tmp_inode),
(OsString::from("run"), run_inode),
]
.into_iter(),
)),
uid: 0,
gid: 0,
mode: 0o755,
modified: 0,
xattrs: HashMap::new(),
flags: 0,
},
})?;
tree.finish()?;
tmp_file.rewind()?;
partition.rewind()?;
io::copy(&mut tmp_file, partition)?;
println!("Root filesystem B created successfully");
Ok(())
}
fn format_ext4(partition: &mut StreamSlice<File>) -> anyhow::Result<()> {
let mut tmp_file = tempfile::NamedTempFile::new()?;
io::copy(partition, &mut tmp_file)?;
let mut mkfs = no_stdin("mkfs.ext4");
mkfs.arg(tmp_file.path());
if !mkfs.spawn()?.wait()?.success() {
bail!("mkfs.ext4 failed");
}
tmp_file.rewind()?;
partition.rewind()?;
io::copy(&mut tmp_file, partition)?;
println!("Data filesystem created successfully");
Ok(())
}
fn overwrite_device(
file: &mut File,
overwrite: String,
arch: String,
crates: Vec<String>,
git: Vec<String>,
init: String,
) -> anyhow::Result<()> {
partition_device(file, overwrite, arch, crates, git, init)?;
Ok(())
}
fn overwrite_file(
file: &mut File,
file_size: u64,
arch: String,
crates: Vec<String>,
git: Vec<String>,
init: String,
) -> anyhow::Result<()> {
partition(file, file_size, arch, crates, git, init)?;
Ok(())
}
fn main() -> anyhow::Result<()> {
let args = Args::parse();
match args.arch.as_str() {
"x86_64" => {}
"rpi" => {}
_ => bail!("invalid architecture (supported: x86_64 rpi)"),
}
let init_in_crates = args.crates.iter().any(|pkg| *pkg == args.init);
let init_in_git = args.git.iter().any(|location| {
let mut split = location.split('%');
let url = match Url::parse(split.next().unwrap()) {
Ok(url) => url,
Err(e) => {
println!("Invalid git crate {}: {}", location, e);
return false;
}
};
let pkg = split.next().unwrap_or(
url.path_segments()
.unwrap()
.next_back()
.unwrap()
.trim_end_matches(".git"),
);
pkg == args.init
});
if !init_in_crates && !init_in_git {
bail!("Init must be listed in crates to install");
}
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(args.overwrite.clone())?;
if file.metadata()?.permissions().mode() & MODE_DEVICE != 0 {
overwrite_device(
&mut file,
args.overwrite,
args.arch,
args.crates,
args.git,
args.init,
)
} else {
match args.size {
Some(v) => overwrite_file(&mut file, v, args.arch, args.crates, args.git, args.init),
None => bail!("Files require --size to be specified"),
}
}
}
fn no_stdin<S: AsRef<OsStr>>(program: S) -> Command {
let mut cmd = Command::new(program);
cmd.stdin(Stdio::null());
cmd
}
|