-
Notifications
You must be signed in to change notification settings - Fork 198
/
Copy pathcomposepost.rs
1556 lines (1405 loc) · 55.8 KB
/
composepost.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
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
//! Logic for post-processing a filesystem tree, server-side.
//!
//! This code runs server side to "postprocess" a filesystem tree (usually
//! containing mostly RPMs) in order to prepare it as an OSTree commit.
// SPDX-License-Identifier: Apache-2.0 OR MIT
use crate::bwrap;
use crate::bwrap::Bubblewrap;
use crate::capstdext::dirbuilder_from_mode;
use crate::cmdutils::CommandRunExt;
use crate::cxxrsutil::*;
use crate::ffi::BubblewrapMutability;
use crate::ffiutil::ffi_dirfd;
use crate::normalization;
use crate::treefile::{OptUsrLocal, Treefile};
use anyhow::{anyhow, bail, Context, Result};
use camino::{Utf8Path, Utf8PathBuf};
use cap_std::fs::Dir;
use cap_std::fs_utf8::Dir as Utf8Dir;
use cap_std::io_lifetimes::AsFilelike;
use cap_std_ext::cap_std;
use cap_std_ext::cap_std::fs::{DirBuilderExt, MetadataExt, Permissions, PermissionsExt};
use cap_std_ext::dirext::CapStdExtDirExt;
use fn_error_context::context;
use gio::prelude::*;
use ostree_ext::{gio, glib};
use rayon::prelude::*;
use std::borrow::Cow;
use std::fmt::Write as FmtWrite;
use std::io::{BufRead, BufReader, Seek, Write};
use std::os::unix::io::AsRawFd;
use std::os::unix::prelude::IntoRawFd;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::process::Stdio;
/// Directories that are moved out and symlinked from their `/var/lib/<entry>`
/// location to `/usr/lib/<entry>`.
pub(crate) static COMPAT_VARLIB_SYMLINKS: &[&str] = &["alternatives", "vagrant"];
const DEFAULT_DIRMODE: u32 = 0o755;
/// Symlinks to ensure home directories persist by default.
const OSTREE_HOME_SYMLINKS: &[(&str, &str)] = &[("var/roothome", "root"), ("var/home", "home")];
/* See rpmostree-core.h */
const RPMOSTREE_BASE_RPMDB: &str = "usr/lib/sysimage/rpm-ostree-base-db";
pub(crate) const RPMOSTREE_RPMDB_LOCATION: &str = "usr/share/rpm";
const RPMOSTREE_SYSIMAGE_RPMDB: &str = "usr/lib/sysimage/rpm";
pub(crate) const TRADITIONAL_RPMDB_LOCATION: &str = "var/lib/rpm";
const SD_LOCAL_FS_TARGET_REQUIRES: &str = "usr/lib/systemd/system/local-fs.target.requires";
#[context("Moving {}", name)]
fn dir_move_if_exists(src: &cap_std::fs::Dir, dest: &cap_std::fs::Dir, name: &str) -> Result<()> {
if src.symlink_metadata(name).is_ok() {
src.rename(name, dest, name)?;
}
Ok(())
}
/// Initialize an ostree-oriented root filesystem.
///
/// Now unfortunately today, we're not generating toplevel filesystem entries
/// because the `filesystem` package does it from Lua code, which we don't run.
/// (See rpmostree-core.cxx)
#[context("Initializing rootfs (base)")]
fn compose_init_rootfs_base(rootfs_dfd: &cap_std::fs::Dir, tmp_is_dir: bool) -> Result<()> {
const TOPLEVEL_DIRS: &[&str] = &["dev", "proc", "run", "sys", "var", "sysroot"];
let default_dirbuilder = &dirbuilder_from_mode(DEFAULT_DIRMODE);
let default_dirmode = cap_std::fs::Permissions::from_mode(DEFAULT_DIRMODE);
rootfs_dfd
.set_permissions(".", default_dirmode)
.context("Setting rootdir permissions")?;
TOPLEVEL_DIRS.par_iter().try_for_each(|&d| {
rootfs_dfd
.ensure_dir_with(d, default_dirbuilder)
.with_context(|| format!("Creating {d}"))
.map(|_: bool| ())
})?;
if tmp_is_dir {
let tmp_mode = 0o1777;
rootfs_dfd
.ensure_dir_with("tmp", &dirbuilder_from_mode(tmp_mode))
.context("tmp")?;
rootfs_dfd
.set_permissions("tmp", cap_std::fs::Permissions::from_mode(tmp_mode))
.context("Setting permissions for tmp")?;
} else {
rootfs_dfd.symlink("sysroot/tmp", "tmp")?;
}
OSTREE_HOME_SYMLINKS
.par_iter()
.try_for_each(|&(dest, src)| {
rootfs_dfd
.symlink(dest, src)
.with_context(|| format!("Creating {src}"))
})?;
rootfs_dfd
.symlink("sysroot/ostree", "ostree")
.context("Symlinking ostree -> sysroot/ostree")?;
Ok(())
}
/// Initialize a root filesystem set up for use with ostree's `root.transient` mode.
#[context("Initializing rootfs (base)")]
fn compose_init_rootfs_transient(rootfs_dfd: &cap_std::fs::Dir) -> Result<()> {
// Enforce tmp-is-dir in this, because there's really no reason not to.
compose_init_rootfs_base(rootfs_dfd, true)?;
// Again we need to make these directories here because we don't run
// the `filesystem` package's lua script.
const EXTRA_TOPLEVEL_DIRS: &[&str] = &["opt", "media", "mnt", "usr/local"];
let mut db = dirbuilder_from_mode(DEFAULT_DIRMODE);
db.recursive(true);
EXTRA_TOPLEVEL_DIRS.par_iter().try_for_each(|&d| {
// We need to handle the case where these may have been created as a symlink
// by tmpfiles.d snippets for example.
if let Some(meta) = rootfs_dfd.symlink_metadata_optional(d)? {
if !meta.is_dir() {
rootfs_dfd.remove_file(d)?;
}
}
rootfs_dfd
.ensure_dir_with(d, &db)
.with_context(|| format!("Creating {d}"))
.map(|_: bool| ())
})?;
Ok(())
}
/// Initialize an ostree-oriented root filesystem.
///
/// This is hardcoded; in the future we may make more things configurable,
/// but the goal is for all state to be in `/etc` and `/var`.
#[context("Initializing rootfs")]
fn compose_init_rootfs_strict(
rootfs_dfd: &cap_std::fs::Dir,
tmp_is_dir: bool,
opt_usrlocal: OptUsrLocal,
) -> Result<()> {
println!("Initializing rootfs");
compose_init_rootfs_base(rootfs_dfd, tmp_is_dir)?;
let opt_symlink = match opt_usrlocal {
OptUsrLocal::Var => Some("var/opt"),
OptUsrLocal::Root => {
rootfs_dfd.create_dir_all("opt")?;
None
}
OptUsrLocal::StateOverlay => Some("usr/lib/opt"),
};
// This is used in the case where we don't have a transient rootfs; redirect
// these toplevel directories underneath /var.
let ostree_strict_mode_symlinks = [
("var/srv", "srv"),
("var/mnt", "mnt"),
("run/media", "media"),
];
ostree_strict_mode_symlinks
.into_iter()
.chain(opt_symlink.map(|link| (link, "opt")))
.try_for_each(|(dest, src)| {
rootfs_dfd
.symlink(dest, src)
.with_context(|| format!("Creating {src}"))
})?;
Ok(())
}
/// Prepare rootfs for commit.
///
/// In the default mode, we initialize a basic root filesystem in @target_root_dfd, then walk over the
/// root filesystem in @src_rootfs_fd and take the basic content (/usr, /boot, /var)
/// and cherry pick only specific bits of the rest of the toplevel like compatibility
/// symlinks (e.g. /lib64 -> /usr/lib64) if they exist.
///
/// However, if the rootfs is setup as transient, then we just copy everything.
#[context("Preparing rootfs for commit")]
pub fn compose_prepare_rootfs(
src_rootfs_dfd: i32,
target_rootfs_dfd: i32,
treefile: &mut Treefile,
) -> CxxResult<()> {
let src_rootfs_dfd = unsafe { &ffi_dirfd(src_rootfs_dfd)? };
let target_rootfs_dfd = unsafe { &ffi_dirfd(target_rootfs_dfd)? };
let tmp_is_dir = treefile.parsed.base.tmp_is_dir.unwrap_or_default();
if crate::ostree_prepareroot::transient_root_enabled(src_rootfs_dfd)? {
println!("Target has transient root enabled");
// While sadly tmp-is-dir: false by default, we want to encourage
// people to switch, so just error out if they're somehow configured
// things for the newer transient root model but forgot to set `tmp-is-dir`.
if !tmp_is_dir {
return Err("Transient root conflicts with tmp-is-dir: false"
.to_string()
.into());
}
// We grab all the content from the source root by default on general principle,
// but note this won't be very much right now because
// we're not executing the `filesystem` package's lua script.
for entry in src_rootfs_dfd.entries()? {
let entry = entry?;
let name = entry.file_name();
src_rootfs_dfd
.rename(&name, target_rootfs_dfd, &name)
.with_context(|| format!("Moving {name:?}"))?;
}
compose_init_rootfs_transient(target_rootfs_dfd)?;
return Ok(());
}
compose_init_rootfs_strict(
target_rootfs_dfd,
tmp_is_dir,
treefile.parsed.base.opt_usrlocal.unwrap_or_default(),
)?;
println!("Moving /usr to target");
src_rootfs_dfd.rename("usr", target_rootfs_dfd, "usr")?;
/* The kernel may be in the source rootfs /boot; to handle that, we always
* rename the source /boot to the target, and will handle everything after
* that in the target root.
*/
dir_move_if_exists(src_rootfs_dfd, target_rootfs_dfd, "boot")?;
/* And grab /var - we'll convert to tmpfiles.d later */
dir_move_if_exists(src_rootfs_dfd, target_rootfs_dfd, "var")?;
const TOPLEVEL_LINKS: &[&str] = &["lib", "lib64", "lib32", "bin", "sbin"];
println!("Copying toplevel compat symlinks");
TOPLEVEL_LINKS
.par_iter()
.try_for_each(|&l| dir_move_if_exists(src_rootfs_dfd, target_rootfs_dfd, l))?;
Ok(())
}
// rpm-ostree uses /home → /var/home by default as generated by our
// rootfs; we don't expect people to change this. Let's be nice
// and also fixup the $HOME entries generated by `useradd` so
// that `~` shows up as expected in shells, etc.
//
// https://github.com/coreos/fedora-coreos-config/pull/18
// https://pagure.io/workstation-ostree-config/pull-request/121
// https://discussion.fedoraproject.org/t/adapting-user-home-in-etc-passwd/487/6
// https://github.com/justjanne/powerline-go/issues/94
#[context("Postprocessing useradd")]
fn postprocess_useradd(rootfs_dfd: &cap_std::fs::Dir) -> Result<()> {
let path = Utf8Path::new("usr/etc/default/useradd");
let perms = cap_std::fs::Permissions::from_mode(0o644);
if let Some(f) = rootfs_dfd.open_optional(path).context("opening")? {
rootfs_dfd
.atomic_replace_with(path, |bufw| -> Result<_> {
bufw.get_mut().as_file_mut().set_permissions(perms)?;
let f = BufReader::new(&f);
for line in f.lines() {
let line = line?;
if !line.starts_with("HOME=") {
bufw.write_all(line.as_bytes())?;
} else {
bufw.write_all(b"HOME=/var/home")?;
}
bufw.write_all(b"\n")?;
}
Ok(())
})
.with_context(|| format!("Replacing {}", path))?;
}
Ok(())
}
fn is_overlay_whiteout(meta: &cap_std::fs::Metadata) -> bool {
(meta.mode() & libc::S_IFMT) == libc::S_IFCHR && meta.rdev() == 0
}
/// Automatically "quote" embeded overlayfs whiteouts as regular files, and
/// if configured error out on devices or ignore them.
/// For more on overlayfs, see https://github.com/ostreedev/ostree/pull/2722/commits/0085494e350c72599fc5c0e00422885d80b3c660
#[context("Postprocessing devices")]
fn postprocess_devices(root: &Dir, treefile: &Treefile) -> Result<()> {
const OSTREE_WHITEOUT_PREFIX: &str = ".ostree-wh.";
let mut n_overlay = 0u64;
let mut n_devices = 0u64;
fn recurse(
root: &Dir,
path: &Utf8Path,
ignore_devices: bool,
n_overlay: &mut u64,
n_devices: &mut u64,
) -> Result<()> {
for entry in root.read_dir(path)? {
let entry = entry?;
let meta = entry.metadata()?;
let name = PathBuf::from(entry.file_name());
let name: Utf8PathBuf = name.try_into()?;
if meta.is_dir() {
recurse(root, &path.join(name), ignore_devices, n_overlay, n_devices)?;
continue;
}
let is_device = matches!(meta.mode() & libc::S_IFMT, libc::S_IFCHR | libc::S_IFBLK);
if !is_device {
continue;
}
let srcpath = path.join(&name);
if is_overlay_whiteout(&meta) {
let targetname = format!("{OSTREE_WHITEOUT_PREFIX}{name}");
let destpath = path.join(&targetname);
root.remove_file(srcpath)?;
root.atomic_write_with_perms(destpath, "", meta.permissions())?;
*n_overlay += 1;
continue;
}
if ignore_devices {
root.remove_file(srcpath)?;
*n_devices += 1;
} else {
anyhow::bail!("Unsupported device file: {srcpath}")
}
}
Ok(())
}
recurse(
root,
".".into(),
treefile.get_ignore_devices(),
&mut n_overlay,
&mut n_devices,
)?;
if n_overlay > 0 {
println!("Processed {n_overlay} embedded whiteouts");
} else {
println!("No embedded whiteouts found");
}
if n_devices > 0 {
println!("Ignored {n_devices} device files");
} else {
println!("No device files found");
}
Ok(())
}
/// Write an RPM macro file to ensure the rpmdb path is set on the client side.
pub fn compose_postprocess_rpm_macro(rootfs_dfd: i32) -> CxxResult<()> {
let rootfs = unsafe { &crate::ffiutil::ffi_dirfd(rootfs_dfd)? };
postprocess_rpm_macro(rootfs)?;
Ok(())
}
/// Ensure our own `_dbpath` macro exists in the tree.
#[context("Writing _dbpath RPM macro")]
fn postprocess_rpm_macro(rootfs_dfd: &Dir) -> Result<()> {
static RPM_MACROS_DIR: &str = "usr/lib/rpm/macros.d";
static MACRO_FILENAME: &str = "macros.rpm-ostree";
let mut db = cap_std::fs::DirBuilder::new();
db.recursive(true);
db.mode(0o755);
rootfs_dfd.create_dir_with(RPM_MACROS_DIR, &db)?;
let rpm_macros_dfd = rootfs_dfd.open_dir(RPM_MACROS_DIR)?;
let perms = cap_std::fs::Permissions::from_mode(0o644);
rpm_macros_dfd.atomic_replace_with(MACRO_FILENAME, |w| -> Result<()> {
w.get_mut().as_file_mut().set_permissions(perms)?;
w.write_all(b"%_dbpath /")?;
w.write_all(RPMOSTREE_RPMDB_LOCATION.as_bytes())?;
w.write_all(b"\n")?;
Ok(())
})?;
Ok(())
}
// This function does two things: (1) make sure there is a /home --> /var/home substitution rule,
// and (2) make sure there *isn't* a /var/home -> /home substition rule. The latter check won't
// technically be needed once downstreams have:
// https://src.fedoraproject.org/rpms/selinux-policy/pull-request/14
#[context("Postprocessing subs_dist")]
fn postprocess_subs_dist(rootfs_dfd: &Dir) -> Result<()> {
let path = Path::new("usr/etc/selinux/targeted/contexts/files/file_contexts.subs_dist");
if let Some(f) = rootfs_dfd.open_optional(path)? {
let perms = cap_std::fs::Permissions::from_mode(0o644);
rootfs_dfd.atomic_replace_with(path, |w| -> Result<()> {
w.get_mut().as_file_mut().set_permissions(perms)?;
let f = BufReader::new(&f);
for line in f.lines() {
let line = line?;
if line.starts_with("/var/home ") {
writeln!(w, "# https://github.com/projectatomic/rpm-ostree/pull/1754")?;
write!(w, "# ")?;
}
writeln!(w, "{}", line)?;
}
writeln!(w, "# https://github.com/projectatomic/rpm-ostree/pull/1754")?;
writeln!(w, "/home /var/home")?;
writeln!(w, "# https://github.com/coreos/rpm-ostree/pull/4640")?;
writeln!(w, "/usr/etc /etc")?;
writeln!(w, "# https://github.com/coreos/rpm-ostree/pull/1795")?;
writeln!(w, "/usr/lib/opt /opt")?;
Ok(())
})?;
}
Ok(())
}
#[context("Cleaning up rpmdb leftovers")]
fn postprocess_cleanup_rpmdb_impl(rootfs_dfd: &Dir) -> Result<()> {
let d = if let Some(d) = rootfs_dfd.open_dir_optional(RPMOSTREE_RPMDB_LOCATION)? {
Utf8Dir::from_cap_std(d)
} else {
return Ok(());
};
for ent in d.entries()? {
let ent = ent?;
let name = ent.file_name()?;
let name = name.as_str();
if matches!(name, ".dbenv.lock" | ".rpm.lock") || name.starts_with("__db.") {
d.remove_file(name)?;
}
}
Ok(())
}
pub(crate) fn postprocess_cleanup_rpmdb(rootfs_dfd: i32) -> CxxResult<()> {
postprocess_cleanup_rpmdb_impl(unsafe { &ffi_dirfd(rootfs_dfd)? }).map_err(Into::into)
}
/// Final processing steps.
///
/// This function is called from rpmostree_postprocess_final(); think of
/// it as the bits of that function that we've chosen to implement in Rust.
/// It takes care of all things that are really required to use rpm-ostree
/// on the target host.
pub fn compose_postprocess_final_pre(rootfs_dfd: i32, treefile: &Treefile) -> CxxResult<()> {
let rootfs_dfd = unsafe { &crate::ffiutil::ffi_dirfd(rootfs_dfd)? };
// These tasks can safely run in parallel, so just for fun we do so via rayon.
let tasks = [
postprocess_useradd,
postprocess_subs_dist,
postprocess_rpm_macro,
];
tasks.par_iter().try_for_each(|f| f(rootfs_dfd))?;
// This task recursively traverses the filesystem and hence should be serial.
postprocess_devices(rootfs_dfd, treefile)?;
Ok(())
}
#[context("Handling treefile 'units'")]
fn compose_postprocess_units(rootfs_dfd: &Dir, treefile: &mut Treefile) -> Result<()> {
let mut db = cap_std::fs::DirBuilder::new();
db.recursive(true);
db.mode(0o755);
let units = if let Some(u) = treefile.parsed.base.units.as_ref() {
u
} else {
return Ok(());
};
let multiuser_wants = Path::new("usr/etc/systemd/system/multi-user.target.wants");
// Sanity check
if !rootfs_dfd.try_exists("usr/etc")? {
return Err(anyhow!("Missing usr/etc in rootfs"));
}
rootfs_dfd.ensure_dir_with(multiuser_wants, &db)?;
for unit in units {
let dest = multiuser_wants.join(unit);
if rootfs_dfd
.symlink_metadata_optional(&dest)
.with_context(|| format!("Querying {unit}"))?
.is_some()
{
continue;
}
println!("Adding {} to multi-user.target.wants", unit);
let target = format!("/usr/lib/systemd/system/{unit}");
cap_primitives::fs::symlink_contents(target, &rootfs_dfd.as_filelike_view(), dest)
.with_context(|| format!("Linking {unit}"))?;
}
Ok(())
}
#[context("Handling treefile 'default-target'")]
fn compose_postprocess_default_target(rootfs: &Dir, target: &str) -> Result<()> {
/* This used to be in /etc, but doing it in /usr makes more sense, as it's
* part of the OS defaults. This was changed in particular to work with
* ConditionFirstBoot= which runs `systemctl preset-all`:
* https://github.com/projectatomic/rpm-ostree/pull/1425
*/
let default_target_path = "usr/lib/systemd/system/default.target";
rootfs.remove_file_optional(default_target_path)?;
rootfs.symlink(target, default_target_path)?;
Ok(())
}
/// The treefile format has two kinds of postprocessing scripts;
/// there's a single `postprocess-script` as well as inline (anonymous)
/// scripts. This function executes both kinds in bwrap containers.
fn compose_postprocess_scripts(
rootfs_dfd: &Dir,
treefile: &mut Treefile,
unified_core: bool,
) -> Result<()> {
// Execute the anonymous (inline) scripts.
for (i, script) in treefile
.parsed
.base
.postprocess
.iter()
.flatten()
.enumerate()
{
let binpath = format!("/usr/bin/rpmostree-postprocess-inline-{}", i);
let target_binpath = &binpath[1..];
rootfs_dfd.atomic_write_with_perms(
target_binpath,
script,
Permissions::from_mode(0o755),
)?;
println!("Executing `postprocess` inline script '{}'", i);
let child_argv = vec![binpath.to_string()];
let _ = bwrap::bubblewrap_run_sync(
rootfs_dfd.as_raw_fd(),
&child_argv,
false,
BubblewrapMutability::for_unified_core(unified_core),
)?;
rootfs_dfd.remove_file(target_binpath)?;
}
// And the single postprocess script.
if let Some(postprocess_script) = treefile.get_postprocess_script() {
let binpath = "/usr/bin/rpmostree-treefile-postprocess-script";
let target_binpath = &binpath[1..];
postprocess_script.seek(std::io::SeekFrom::Start(0))?;
let mut reader = std::io::BufReader::new(postprocess_script);
rootfs_dfd.atomic_replace_with(target_binpath, |w| {
std::io::copy(&mut reader, w)?;
w.get_mut()
.as_file_mut()
.set_permissions(Permissions::from_mode(0o755))?;
Ok::<_, anyhow::Error>(())
})?;
println!("Executing postprocessing script");
let child_argv = &vec![binpath.to_string()];
let _ = crate::bwrap::bubblewrap_run_sync(
rootfs_dfd.as_raw_fd(),
child_argv,
false,
BubblewrapMutability::for_unified_core(unified_core),
)
.context("Executing postprocessing script")?;
rootfs_dfd.remove_file(target_binpath)?;
println!("Finished postprocessing script");
}
Ok(())
}
/// Logic for handling treefile `remove-files`.
#[context("Handling `remove-files`")]
pub fn compose_postprocess_remove_files(
rootfs_dfd: &Dir,
treefile: &mut Treefile,
) -> CxxResult<()> {
for name in treefile.parsed.base.remove_files.iter().flatten() {
let p = Path::new(name);
if p.is_absolute() {
return Err(anyhow!("Invalid absolute path: {}", name).into());
}
if name.contains("..") {
return Err(anyhow!("Invalid '..' in path: {}", name).into());
}
println!("Deleting: {}", name);
rootfs_dfd.remove_all_optional(name)?;
}
Ok(())
}
fn compose_postprocess_add_files(rootfs_dfd: &Dir, treefile: &mut Treefile) -> Result<()> {
let mut db = cap_std::fs::DirBuilder::new();
db.recursive(true);
db.mode(0o755);
// Make a deep copy here because get_add_file_fd() also wants an &mut
// reference.
let add_files: Vec<_> = treefile
.parsed
.base
.add_files
.iter()
.flatten()
.cloned()
.collect();
for (src, dest) in add_files {
let reldest = dest.trim_start_matches('/');
if reldest.is_empty() {
return Err(anyhow!("Invalid add-files destination: {}", dest));
}
let dest = if reldest.starts_with("etc/") {
Cow::Owned(format!("usr/{}", reldest))
} else {
Cow::Borrowed(reldest)
};
println!("Adding file {}", dest);
let dest = Path::new(&*dest);
if let Some(parent) = dest.parent() {
rootfs_dfd.ensure_dir_with(parent, &db)?;
}
let fd = treefile.get_add_file(&src);
fd.seek(std::io::SeekFrom::Start(0))?;
let mut reader = std::io::BufReader::new(fd);
let perms = reader.get_mut().metadata()?.permissions();
rootfs_dfd.atomic_replace_with(dest, |w| {
std::io::copy(&mut reader, w)?;
w.get_mut()
.as_file_mut()
.set_permissions(cap_std::fs::Permissions::from_std(perms))?;
Ok::<_, anyhow::Error>(())
})?;
}
Ok(())
}
#[context("Symlinking {}", TRADITIONAL_RPMDB_LOCATION)]
fn compose_postprocess_rpmdb(rootfs_dfd: &Dir) -> Result<()> {
/* This works around a potential issue with libsolv if we go down the
* rpmostree_get_pkglist_for_root() path. Though rpm has been using the
* /usr/share/rpm location (since the RpmOstreeContext set the _dbpath macro),
* the /var/lib/rpm directory will still exist, but be empty. libsolv gets
* confused because it sees the /var/lib/rpm dir and doesn't even try the
* /usr/share/rpm location, and eventually dies when it tries to load the
* data. XXX: should probably send a patch upstream to libsolv.
*
* So we set the symlink now. This is also what we do on boot anyway for
* compatibility reasons using tmpfiles.
* */
rootfs_dfd.remove_all_optional(TRADITIONAL_RPMDB_LOCATION)?;
rootfs_dfd.symlink(
format!("../../{}", RPMOSTREE_RPMDB_LOCATION),
TRADITIONAL_RPMDB_LOCATION,
)?;
Ok(())
}
/// Enables [email protected] for /usr/lib/opt and /usr/local. These
/// symlinks are also used later in the compose process (and client-side composes)
/// as a way to check that state overlays are turned on.
fn compose_postprocess_state_overlays(rootfs_dfd: &Dir) -> Result<()> {
let mut db = cap_std::fs::DirBuilder::new();
db.recursive(true);
db.mode(0o755);
let localfs_requires = Path::new(SD_LOCAL_FS_TARGET_REQUIRES);
rootfs_dfd.ensure_dir_with(localfs_requires, &db)?;
const UNITS: &[&str] = &[
];
UNITS.par_iter().try_for_each(|&unit| {
let target = Path::new("..").join(unit);
let linkpath = localfs_requires.join(unit);
rootfs_dfd
.symlink(target, linkpath)
.with_context(|| format!("Enabling {unit}"))
})?;
Ok(())
}
/// Rust portion of rpmostree_treefile_postprocessing()
pub fn compose_postprocess(
rootfs_dfd: i32,
treefile: &mut Treefile,
next_version: &str,
unified_core: bool,
) -> CxxResult<()> {
let rootfs = unsafe { &crate::ffiutil::ffi_dirfd(rootfs_dfd)? };
// One of several dances we do around this that really needs to be completely
// reworked.
if rootfs.try_exists("etc")? {
rootfs.rename("etc", rootfs, "usr/etc")?;
}
compose_postprocess_rpmdb(rootfs)?;
compose_postprocess_units(rootfs, treefile)?;
if let Some(t) = treefile.parsed.base.default_target.as_deref() {
compose_postprocess_default_target(rootfs, t)?;
}
if matches!(
treefile.parsed.base.opt_usrlocal,
Some(OptUsrLocal::StateOverlay)
) {
compose_postprocess_state_overlays(rootfs)?;
}
treefile.write_compose_json(rootfs)?;
let etc_guard = crate::core::prepare_tempetc_guard(rootfs_dfd.as_raw_fd())?;
// These ones depend on the /etc path
compose_postprocess_mutate_os_release(rootfs, treefile, next_version)?;
compose_postprocess_remove_files(rootfs, treefile)?;
compose_postprocess_add_files(rootfs, treefile)?;
etc_guard.undo()?;
compose_postprocess_scripts(rootfs, treefile, unified_core)?;
Ok(())
}
/// Implementation of the treefile `mutate-os-release` field.
#[context("Updating os-release with commit version")]
fn compose_postprocess_mutate_os_release(
rootfs: &Dir,
treefile: &mut Treefile,
next_version: &str,
) -> Result<()> {
let base_version = if let Some(base_version) = treefile.parsed.base.mutate_os_release.as_deref()
{
base_version
} else {
return Ok(());
};
if next_version.is_empty() {
println!("Ignoring mutate-os-release: no commit version specified.");
return Ok(());
}
// find the real path to os-release using bwrap; this is an overkill but safer way
// of resolving a symlink relative to a rootfs (see discussions in
// https://github.com/projectatomic/rpm-ostree/pull/410/)
let mut bwrap = crate::bwrap::Bubblewrap::new_with_mutability(
rootfs,
crate::ffi::BubblewrapMutability::Immutable,
)?;
bwrap.append_child_argv(["realpath", "/etc/os-release"]);
let cancellable = &gio::Cancellable::new();
let cancellable = Some(cancellable);
let path = bwrap.run_captured(cancellable)?;
let path = std::str::from_utf8(&path)
.context("Parsing realpath")?
.trim_start_matches('/')
.trim_end();
let path = if path.is_empty() {
// fallback on just overwriting etc/os-release
"etc/os-release"
} else {
path
};
println!("Updating {}", path);
let contents = rootfs
.read_to_string(path)
.with_context(|| format!("Reading {path}"))?;
let new_contents = mutate_os_release_contents(&contents, base_version, next_version);
rootfs
.atomic_write(path, new_contents.as_bytes())
.with_context(|| format!("Writing {path}"))?;
Ok(())
}
/// Given the contents of a /usr/lib/os-release file,
/// update the `VERSION` and `PRETTY_NAME` fields.
fn mutate_os_release_contents(contents: &str, base_version: &str, next_version: &str) -> String {
let mut buf = String::new();
for line in contents.lines() {
if line.is_empty() {
continue;
}
let prefixes = &["VERSION=", "PRETTY_NAME="];
if let Some((prefix, rest)) = strip_any_prefix(line, prefixes) {
buf.push_str(prefix);
let replaced = rest.replace(base_version, next_version);
buf.push_str(&replaced);
} else {
buf.push_str(line);
}
buf.push('\n');
}
let quoted_version = glib::shell_quote(next_version);
let quoted_version = quoted_version.to_str().unwrap();
// Unwrap safety: write! to a String can't fail
writeln!(buf, "OSTREE_VERSION={}", quoted_version).unwrap();
buf
}
/// Given a string and a set of possible prefixes, return the split
/// prefix and remaining string, or `None` if no matches.
fn strip_any_prefix<'a, 'b>(s: &'a str, prefixes: &[&'b str]) -> Option<(&'b str, &'a str)> {
prefixes
.iter()
.find_map(|&p| s.strip_prefix(p).map(|r| (p, r)))
}
/// Inject `altfiles` after `files` for `passwd:` and `group:` entries.
fn add_altfiles(buf: &str) -> Result<String> {
let mut r = String::with_capacity(buf.len());
for line in buf.lines() {
let parts = if let Some(p) = strip_any_prefix(line, &["passwd:", "group:"]) {
p
} else {
r.push_str(line);
r.push('\n');
continue;
};
let (prefix, rest) = parts;
r.push_str(prefix);
let mut inserted = false;
for elt in rest.split_whitespace() {
// Already have altfiles? We're done
if elt == "altfiles" {
return Ok(buf.to_string());
}
// We prefer `files altfiles`
if !inserted && elt == "files" {
r.push_str(" files altfiles");
inserted = true;
} else {
r.push(' ');
r.push_str(elt);
}
}
if !inserted {
r.push_str(" altfiles");
}
r.push('\n');
}
Ok(r)
}
/// Add `altfiles` entries to `nsswitch.conf`.
///
/// rpm-ostree currently depends on `altfiles`
#[context("Adding altfiles to /etc/nsswitch.conf")]
pub fn composepost_nsswitch_altfiles(rootfs_dfd: i32) -> CxxResult<()> {
let rootfs_dfd = unsafe { &crate::ffiutil::ffi_dirfd(rootfs_dfd)? };
let path = "usr/etc/nsswitch.conf";
if let Some(meta) = rootfs_dfd.symlink_metadata_optional(path)? {
// If it's a symlink, then something else e.g. authselect must own it.
if meta.is_symlink() {
return Ok(());
}
let nsswitch = rootfs_dfd.read_to_string(path)?;
let nsswitch = add_altfiles(&nsswitch)?;
rootfs_dfd.atomic_write(path, nsswitch.as_bytes())?;
}
Ok(())
}
/// Go over `/var` in the rootfs and convert them to tmpfiles.d entries. Only directories and
/// symlinks are handled. rpm-ostree itself creates some symlinks for various reasons.
///
/// In the non-unified core path, conversion is necessary to ensure that (1) any subdirs/symlinks
/// from the RPM itself and (2) any subdirs/symlinks from scriptlets will be created on first boot.
/// In the unified core path, (1) is handled by the importer, and (2) is blocked by bwrap, so it's
/// really just for rpm-ostree-created bits itself.
///
/// In theory, once we drop non-unified core support, we should be able to drop this and make those
/// few rpm-ostree compat symlinks just directly write tmpfiles.d dropins.
pub fn convert_var_to_tmpfiles_d(
rootfs_dfd: i32,
cancellable: &crate::FFIGCancellable,
) -> CxxResult<()> {
let rootfs = unsafe { crate::ffiutil::ffi_dirfd(rootfs_dfd)? };
let cancellable = &cancellable.glib_reborrow();
// TODO(lucab): unify this logic with the one in rpmostree-importer.cxx.
crate::var_to_tmpfiles(&rootfs, Some(cancellable))?;
Ok(())
}
fn state_overlay_enabled(rootfs_dfd: &cap_std::fs::Dir, state_overlay: &str) -> Result<bool> {
let linkname =
format!("{SD_LOCAL_FS_TARGET_REQUIRES}/ostree-state-overlay@{state_overlay}.service");
match rootfs_dfd.symlink_metadata_optional(&linkname)? {
Some(meta) if meta.is_symlink() => Ok(true),
Some(_) => Err(anyhow!("{linkname} is not a symlink")),
None => Ok(false),
}
}
/// Walk over the root filesystem and perform some core conversions
/// from RPM conventions to OSTree conventions.
///
/// For example:
/// - Symlink /usr/local -> /var/usrlocal
/// - If present, symlink /var/lib/alternatives -> /usr/lib/alternatives
/// - If present, symlink /var/lib/vagrant -> /usr/lib/vagrant
#[context("Preparing symlinks in rootfs")]
pub fn rootfs_prepare_links(
rootfs_dfd: i32,
treefile: &Treefile,
skip_usrlocal: bool,
) -> CxxResult<()> {
let rootfs = unsafe { &crate::ffiutil::ffi_dirfd(rootfs_dfd)? };
let mut db = dirbuilder_from_mode(0o755);
db.recursive(true);
if !skip_usrlocal {
let usrlocal_root = matches!(treefile.parsed.base.opt_usrlocal, Some(OptUsrLocal::Root));
if usrlocal_root || state_overlay_enabled(rootfs, "usr-local")? {
// because of the filesystem lua issue (see
// compose_init_rootfs_base()) we need to create this manually
rootfs.ensure_dir_with("usr/local", &db)?;
} else if !crate::ostree_prepareroot::transient_root_enabled(rootfs)? {
// Unconditionally drop /usr/local and replace it with a symlink.
rootfs
.remove_all_optional("usr/local")
.context("Removing /usr/local")?;
ensure_symlink(rootfs, "../var/usrlocal", "usr/local")
.context("Creating /usr/local symlink")?;
}
}
// Move existing content to /usr/lib, then put a symlink in its
// place under /var/lib.
rootfs
.ensure_dir_with("usr/lib", &db)
.context("Creating /usr/lib")?;
for entry in COMPAT_VARLIB_SYMLINKS {
let varlib_path = format!("var/lib/{}", entry);
let is_var_dir = rootfs
.symlink_metadata_optional(&varlib_path)?
.map(|m| m.is_dir())
.unwrap_or(false);
if !is_var_dir {
continue;
}
let usrlib_path = format!("usr/lib/{}", entry);
rootfs
.remove_all_optional(&usrlib_path)
.with_context(|| format!("Removing /{}", &usrlib_path))?;
rootfs
.rename(&varlib_path, rootfs, &usrlib_path)
.with_context(|| format!("Moving /{} to /{}", &varlib_path, &usrlib_path))?;
let target = format!("../../{}", &usrlib_path);
ensure_symlink(rootfs, &target, &varlib_path)
.with_context(|| format!("Creating /{} symlink", &varlib_path))?;
}
Ok(())
}
/// Create a symlink at `linkpath` if it does not exist, pointing to `target`.
///
/// This is idempotent and does not alter any content already existing at `linkpath`.
/// It returns `true` if the symlink has been created, `false` otherwise.
#[context("Symlinking '/{}' to empty directory '/{}'", linkpath, target)]
fn ensure_symlink(rootfs: &Dir, target: &str, linkpath: &str) -> Result<bool> {
let mut db = dirbuilder_from_mode(0o755);
db.recursive(true);
if let Some(meta) = rootfs.symlink_metadata_optional(linkpath)? {
if meta.is_symlink() {
// We assume linkpath already points to the correct target,
// thus this short-circuits in an idempotent way.
return Ok(false);
} else if meta.is_dir() {
rootfs.remove_dir(linkpath)?;
} else {
bail!("Content already exists at link path");
}
} else {
// For maximum compatibility, create parent directories too. This
// is necessary when we're doing layering on top of a base commit,
// and the /var will be empty. We should probably consider running
// systemd-tmpfiles to setup the temporary /var.
if let Some(parent) = Path::new(linkpath).parent() {
rootfs.ensure_dir_with(parent, &db)?;
}
}
rootfs.symlink(target, linkpath)?;
Ok(true)
}
pub fn workaround_selinux_cross_labeling(
rootfs_dfd: i32,
cancellable: Pin<&mut crate::FFIGCancellable>,
) -> CxxResult<()> {