-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathmain.rs
562 lines (508 loc) · 18.2 KB
/
main.rs
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
extern crate clap;
extern crate distinst;
extern crate failure;
#[macro_use]
extern crate failure_derive;
extern crate libc;
extern crate pbr;
mod configure;
mod errors;
use clap::{App, Arg, ArgMatches, Values};
use configure::*;
use distinst::{timezones::Timezones, *};
use errors::DistinstError;
use pbr::ProgressBar;
use std::{
cell::RefCell,
io,
path::{Path, PathBuf},
process::exit,
rc::Rc,
sync::atomic::Ordering,
};
fn main() {
let matches = App::new("distinst")
.arg(
Arg::with_name("username")
.long("username")
.requires("profile_icon")
.help("specifies a default user account to create")
.takes_value(true),
)
.arg(
Arg::with_name("password")
.long("password")
.help("set the password for the username")
.requires("username")
.takes_value(true),
)
.arg(
Arg::with_name("realname")
.long("realname")
.help("the full name of user to create")
.requires("username")
.takes_value(true),
)
.arg(
Arg::with_name("profile_icon")
.long("profile_icon")
.help("path to icon for user profile")
.takes_value(true),
)
.arg(
Arg::with_name("timezone")
.long("tz")
.help("the timezone to set for the new install")
.value_delimiter("/")
.min_values(2)
.max_values(2),
)
.arg(
Arg::with_name("squashfs")
.short("s")
.long("squashfs")
.help("define the squashfs image which will be installed")
.takes_value(true)
.required(true),
)
.arg(
Arg::with_name("hostname")
.short("h")
.long("hostname")
.help("define the hostname that the new system will have")
.takes_value(true)
.required(true),
)
.arg(
Arg::with_name("keyboard")
.short("k")
.long("keyboard")
.help("define the keyboard configuration to use")
.takes_value(true)
.min_values(1)
.max_values(3)
.default_value("us"),
)
.arg(
Arg::with_name("lang")
.short("l")
.long("lang")
.help("define the locale that the new system will use")
.takes_value(true)
.default_value("en_US.UTF-8"),
)
.arg(
Arg::with_name("remove")
.short("r")
.long("remove")
.help("defines the manifest file that contains the packages to remove post-install")
.takes_value(true)
.required(true),
)
.arg(
Arg::with_name("disk")
.short("b")
.long("block")
.help("defines a disk that will be manipulated in the installation process")
.takes_value(true)
.multiple(true)
.required(true),
)
.arg(
Arg::with_name("table")
.short("t")
.long("new-table")
.help(
"defines a new partition table to apply to the disk, clobbering it in the \
process",
)
.multiple(true)
.takes_value(true),
)
.arg(
Arg::with_name("new")
.short("n")
.long("new")
.help("defines a new partition that will be created on the disk")
.multiple(true)
.takes_value(true),
)
.arg(
Arg::with_name("use")
.short("u")
.long("use")
.help("defines to reuse an existing partition on the disk")
.takes_value(true)
.multiple(true),
)
.arg(
Arg::with_name("test")
.long("test")
.help("simply test whether the provided arguments pass the partitioning stage"),
)
.arg(
Arg::with_name("hardware-support")
.long("hardware-support")
.help("install hardware support packages based on detected hardware"),
)
.arg(
Arg::with_name("modify-boot")
.long("modify-boot")
.help("modify the boot order after installing"),
)
.arg(
Arg::with_name("force-bios")
.long("force-bios")
.help("performs a BIOS installation even if the running system is EFI"),
)
.arg(
Arg::with_name("force-efi")
.long("force-efi")
.help("performs an EFI installation even if the running system is BIOS"),
)
.arg(
Arg::with_name("no-efi-vars")
.long("no-efi-vars")
.help("disables mounting of the efivars directory"),
)
.arg(
Arg::with_name("delete")
.short("d")
.long("delete")
.help("defines to delete the specified partitions")
.takes_value(true)
.multiple(true),
)
.arg(
Arg::with_name("move")
.short("m")
.long("move")
.help("defines to move and/or resize an existing partition")
.takes_value(true)
.multiple(true),
)
.arg(
Arg::with_name("logical")
.long("logical")
.help("creates a partition on a LVM volume group")
.takes_value(true)
.multiple(true),
)
.arg(
Arg::with_name("logical-modify")
.long("logical-modify")
.help("modifies an existing LVM volume group")
.takes_value(true)
.multiple(true),
)
.arg(
Arg::with_name("logical-remove")
.long("logical-remove")
.help("removes an existing LVM logical volume")
.takes_value(true)
.multiple(true),
)
.arg(
Arg::with_name("logical-remove-all")
.long("logical-remove-all")
.help("TODO")
.takes_value(true),
)
.arg(
Arg::with_name("decrypt")
.long("decrypt")
.help("decrypts an existing LUKS partition")
.takes_value(true)
.multiple(true),
)
.arg(Arg::with_name("run-ubuntu-drivers").long("run-ubuntu-drivers").help(
"use ubuntu-drivers to find drivers then install in the chroot, some may have \
proprietary licenses",
))
.get_matches();
if let Err(err) = distinst::log(|_level, _message| {}) {
eprintln!("Failed to initialize logging: {}", err);
}
let squashfs = matches.value_of("squashfs").unwrap();
let hostname = matches.value_of("hostname").unwrap();
let mut keyboard = matches.values_of("keyboard").unwrap();
let lang = matches.value_of("lang").unwrap();
let remove = matches.value_of("remove").unwrap();
let tzs_;
let timezone = match matches.values_of("timezone") {
Some(mut tz) => {
let (zone, region) = (tz.next().unwrap(), tz.next().unwrap());
tzs_ = Timezones::new().expect("failed to get timzones");
let zone = tzs_
.zones()
.into_iter()
.find(|z| z.name() == zone)
.expect(&format!("failed to find zone: {}", zone));
let region = zone
.regions()
.into_iter()
.find(|r| r.name() == region)
.expect(&format!("failed to find region: {}", region));
Some(region.clone())
}
None => None,
};
let user_account = matches.value_of("username").map(|username| {
let username = username.to_owned();
let profile_icon = matches.value_of("profile_icon").map(String::from);
let realname = matches.value_of("realname").map(String::from);
let password = matches.value_of("password").map(String::from).or_else(|| {
if unsafe { libc::isatty(0) } == 0 {
let mut pass = String::new();
io::stdin().read_line(&mut pass).unwrap();
pass.pop();
Some(pass)
} else {
None
}
});
UserAccountCreate { realname, username, password, profile_icon }
});
let pb_opt: Rc<RefCell<Option<ProgressBar<io::Stdout>>>> = Rc::new(RefCell::new(None));
let res = {
let mut installer = Installer::default();
{
let pb_opt = pb_opt.clone();
installer.on_error(move |error| {
if let Some(mut pb) = pb_opt.borrow_mut().take() {
pb.finish_println("");
}
eprintln!("Error: {:?}", error);
});
}
{
let pb_opt = pb_opt.clone();
let mut step_opt = None;
installer.on_status(move |status| {
if step_opt != Some(status.step) {
if let Some(mut pb) = pb_opt.borrow_mut().take() {
pb.finish_println("");
}
step_opt = Some(status.step);
let mut pb = ProgressBar::new(100);
pb.show_speed = false;
pb.show_counter = false;
pb.message(match status.step {
Step::Backup => "Backing up files",
Step::Init => "Initializing",
Step::Partition => "Partitioning disk ",
Step::Extract => "Extracting filesystem ",
Step::Configure => "Configuring installation",
Step::Bootloader => "Installing bootloader ",
});
*pb_opt.borrow_mut() = Some(pb);
}
if let Some(ref mut pb) = *pb_opt.borrow_mut() {
pb.set(status.percent as u64);
}
});
}
if let Some(timezone) = timezone {
installer.set_timezone_callback(move || timezone.clone());
}
if let Some(user_account) = user_account {
installer.set_user_callback(move || user_account.clone());
}
let disks = match configure_disks(&matches) {
Ok(disks) => disks,
Err(why) => {
eprintln!("distinst: {}", why);
exit(1);
}
};
configure_signal_handling();
if matches.is_present("test") {
PARTITIONING_TEST.store(true, Ordering::Relaxed);
}
if matches.is_present("force-bios") {
FORCE_BOOTLOADER.store(1, Ordering::Relaxed);
} else if matches.is_present("force-efi") {
FORCE_BOOTLOADER.store(2, Ordering::Relaxed);
}
if matches.is_present("no-efi-vars") {
NO_EFI_VARIABLES.store(true, Ordering::Relaxed);
}
fn take_optional_string(argument: Option<&str>) -> Option<String> {
argument.map(String::from).and_then(|x| if x.is_empty() { None } else { Some(x) })
}
// The lock is an `OwnedFd`, which on drop will close / unlock the inhibitor.
let _inhibit_suspend = match distinst::dbus_interfaces::LoginManager::new() {
Ok(manager) => match manager.connect().inhibit_suspend(
"Distinst Installer",
"prevent suspension while installing a distribution",
) {
Ok(lock) => Some(lock),
Err(why) => {
eprintln!("distinst: failed to inhibit suspend: {}", why);
None
}
},
Err(why) => {
eprintln!("distinst: failed to get logind dbus connection: {}", why);
None
}
};
installer.install(
disks,
&Config {
flags: install_flags(&matches),
hostname: hostname.into(),
keyboard_layout: keyboard.next().map(String::from).unwrap(),
keyboard_model: take_optional_string(keyboard.next()),
keyboard_variant: take_optional_string(keyboard.next()),
old_root: None,
lang: lang.into(),
remove: remove.into(),
squashfs: squashfs.into(),
},
)
};
if let Some(mut pb) = pb_opt.borrow_mut().take() {
pb.finish_println("");
}
let status = match res {
Ok(()) => {
println!("install was successful");
0
}
Err(err) => {
println!("install failed: {}", err);
1
}
};
exit(status);
}
fn install_flags(matches: &ArgMatches) -> u8 {
let mut flags = 0;
flags +=
if matches.occurrences_of("modify-boot") != 0 { distinst::MODIFY_BOOT_ORDER } else { 0 };
flags += if matches.occurrences_of("hardware-support") != 0 {
distinst::INSTALL_HARDWARE_SUPPORT
} else {
0
};
flags += if matches.occurrences_of("run-ubuntu-drivers") != 0 {
distinst::RUN_UBUNTU_DRIVERS
} else {
0
};
flags
}
fn configure_signal_handling() {
extern "C" fn handler(signal: i32) {
match signal {
libc::SIGINT => KILL_SWITCH.store(true, Ordering::SeqCst),
_ => unreachable!(),
}
}
if unsafe { libc::signal(libc::SIGINT, handler as libc::sighandler_t) == libc::SIG_ERR } {
eprintln!("distinst: signal handling error: {}", io::Error::last_os_error());
exit(1);
}
}
enum PartType {
/// A normal partition with a standard file system
Fs(Option<FileSystem>),
/// A partition that is formatted with LVM, optionally with encryption.
Lvm(String, Option<LvmEncryption>),
}
fn parse_key(
key: &str,
pass: &mut Option<String>,
keydata: &mut Option<String>,
) -> Result<(), DistinstError> {
if key.starts_with("pass=") {
let passval = &key[5..];
if passval.is_empty() {
return Err(DistinstError::EmptyPassword);
}
*pass = Some(passval.into());
} else if key.starts_with("keyfile=") {
let keyval = &key[8..];
if keyval.is_empty() {
return Err(DistinstError::EmptyKeyValue);
}
*keydata = Some(keyval.into());
} else {
return Err(DistinstError::InvalidField { field: key.into() });
}
Ok(())
}
fn parse_fs(fs: &str) -> Result<PartType, DistinstError> {
if fs.starts_with("enc=") {
let (mut pass, mut keydata) = (None, None);
let mut fields = fs[4..].split(',');
let physical_volume =
fields.next().map(|pv| pv.into()).ok_or(DistinstError::NoPhysicalVolume)?;
let volume_group = fields.next().map(|vg| vg.into()).ok_or(DistinstError::NoVolumeGroup)?;
for field in fields {
parse_key(field, &mut pass, &mut keydata)?;
}
Ok(PartType::Lvm(
volume_group,
if pass.is_none() && keydata.is_none() {
None
} else {
Some(LvmEncryption::new(physical_volume, pass, keydata))
},
))
} else if fs.starts_with("lvm=") {
let mut fields = fs[4..].split(',');
Ok(PartType::Lvm(
fields.next().map(|vg| vg.into()).ok_or(DistinstError::NoVolumeGroup)?,
None,
))
} else {
Ok(PartType::Fs(fs.parse::<FileSystem>().ok()))
}
}
fn parse_sector(sector: &str) -> Result<Sector, DistinstError> {
let result = if sector.ends_with("MiB") {
sector[..sector.len() - 3].parse::<i64>().ok().and_then(|mebibytes| {
format!("{}M", (mebibytes * 1_048_576) / 1_000_000).parse::<Sector>().ok()
})
} else {
sector.parse::<Sector>().ok()
};
result.ok_or_else(|| DistinstError::InvalidSectorValue { value: sector.into() })
}
fn parse_flags(flags: &str) -> Vec<PartitionFlag> {
// TODO: implement FromStr for PartitionFlag
flags
.split(',')
.filter_map(|flag| match flag {
"esp" => Some(PartitionFlag::PED_PARTITION_ESP),
"boot" => Some(PartitionFlag::PED_PARTITION_BOOT),
"root" => Some(PartitionFlag::PED_PARTITION_ROOT),
"swap" => Some(PartitionFlag::PED_PARTITION_SWAP),
"hidden" => Some(PartitionFlag::PED_PARTITION_HIDDEN),
"raid" => Some(PartitionFlag::PED_PARTITION_RAID),
"lvm" => Some(PartitionFlag::PED_PARTITION_LVM),
"lba" => Some(PartitionFlag::PED_PARTITION_LBA),
"hpservice" => Some(PartitionFlag::PED_PARTITION_HPSERVICE),
"palo" => Some(PartitionFlag::PED_PARTITION_PALO),
"prep" => Some(PartitionFlag::PED_PARTITION_PREP),
"msft_reserved" => Some(PartitionFlag::PED_PARTITION_MSFT_RESERVED),
"apple_tv_recovery" => Some(PartitionFlag::PED_PARTITION_APPLE_TV_RECOVERY),
"diag" => Some(PartitionFlag::PED_PARTITION_DIAG),
"legacy_boot" => Some(PartitionFlag::PED_PARTITION_LEGACY_BOOT),
"msft_data" => Some(PartitionFlag::PED_PARTITION_MSFT_DATA),
"irst" => Some(PartitionFlag::PED_PARTITION_IRST),
_ => None,
})
.collect::<Vec<_>>()
}
fn find_disk_mut<'a>(disks: &'a mut Disks, block: &str) -> Result<&'a mut Disk, DistinstError> {
disks.find_disk_mut(block).ok_or_else(|| DistinstError::DiskNotFound { disk: block.into() })
}
fn find_partition_mut(
disk: &mut Disk,
partition: i32,
) -> Result<&mut PartitionInfo, DistinstError> {
disk.get_partition_mut(partition).ok_or_else(|| DistinstError::PartitionNotFound { partition })
}