-
Notifications
You must be signed in to change notification settings - Fork 192
Expand file tree
/
Copy pathlib.rs
More file actions
768 lines (699 loc) · 25.4 KB
/
lib.rs
File metadata and controls
768 lines (699 loc) · 25.4 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
//! Parse and generate systemd tmpfiles.d entries.
// SPDX-License-Identifier: Apache-2.0 OR MIT
use std::collections::{BTreeMap, BTreeSet};
use std::ffi::{OsStr, OsString};
use std::fmt::Write as WriteFmt;
use std::io::{BufRead, BufReader, Write as StdWrite};
use std::iter::Peekable;
use std::num::NonZeroUsize;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::path::{Path, PathBuf};
use camino::Utf8PathBuf;
use cap_std::fs::MetadataExt;
use cap_std::fs::{Dir, Permissions, PermissionsExt};
use cap_std_ext::cap_std;
use cap_std_ext::dirext::CapStdExtDirExt;
use rustix::fs::Mode;
use rustix::path::Arg;
use thiserror::Error;
const TMPFILESD: &str = "usr/lib/tmpfiles.d";
/// The path to the file we use for generation
const BOOTC_GENERATED_PREFIX: &str = "bootc-autogenerated-var";
/// The number of times we've generated a tmpfiles.d
#[derive(Debug, Default)]
struct BootcTmpfilesGeneration(u32);
impl BootcTmpfilesGeneration {
fn increment(&mut self) {
// SAFETY: We shouldn't ever wrap here
self.0 = self.0.checked_add(1).unwrap();
}
fn path(&self) -> Utf8PathBuf {
format!("{TMPFILESD}/{BOOTC_GENERATED_PREFIX}-{}.conf", self.0).into()
}
}
/// An error when translating tmpfiles.d.
#[derive(Debug, Error)]
#[allow(missing_docs)]
pub enum Error {
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("I/O (fmt) error")]
Fmt(#[from] std::fmt::Error),
#[error("I/O error on {path}: {err}")]
PathIo { path: PathBuf, err: std::io::Error },
#[error("User not found for id {0}")]
UserNotFound(uzers::uid_t),
#[error("Group not found for id {0}")]
GroupNotFound(uzers::gid_t),
#[error("Invalid non-UTF8 username: {uid} {name}")]
NonUtf8User { uid: uzers::uid_t, name: String },
#[error("Invalid non-UTF8 groupname: {gid} {name}")]
NonUtf8Group { gid: uzers::gid_t, name: String },
#[error("Missing {TMPFILESD}")]
MissingTmpfilesDir {},
#[error("Found /var/run as a non-symlink")]
FoundVarRunNonSymlink {},
#[error("Malformed tmpfiles.d")]
MalformedTmpfilesPath,
#[error("Malformed tmpfiles.d line {0}")]
MalformedTmpfilesEntry(String),
#[error("Unsupported regular file for tmpfiles.d {0}")]
UnsupportedRegfile(PathBuf),
#[error("Unsupported file of type {ty:?} for tmpfiles.d {path}")]
UnsupportedFile {
ty: rustix::fs::FileType,
path: PathBuf,
},
}
/// The type of Result.
pub type Result<T> = std::result::Result<T, Error>;
fn escape_path<W: std::fmt::Write>(path: &Path, out: &mut W) -> std::fmt::Result {
let path_bytes = path.as_os_str().as_bytes();
if path_bytes.is_empty() {
return Err(std::fmt::Error);
}
if let Ok(s) = path.as_os_str().as_str() {
if s.chars().all(|c| c.is_ascii_alphanumeric() || c == '/') {
return write!(out, "{s}");
}
}
for c in path_bytes.iter().copied() {
let is_special = c == b'\\';
let is_printable = c.is_ascii_alphanumeric() || c.is_ascii_punctuation();
if is_printable && !is_special {
out.write_char(c as char)?;
} else {
match c {
b'\\' => out.write_str(r"\\")?,
b'\n' => out.write_str(r"\n")?,
b'\t' => out.write_str(r"\t")?,
b'\r' => out.write_str(r"\r")?,
o => write!(out, "\\x{o:02x}")?,
}
}
}
std::fmt::Result::Ok(())
}
fn impl_unescape_path_until<I>(
src: &mut Peekable<I>,
buf: &mut Vec<u8>,
end_of_record_is_quote: bool,
) -> Result<()>
where
I: Iterator<Item = u8>,
{
let should_take_next = |c: &u8| {
let c = *c;
if end_of_record_is_quote {
c != b'"'
} else {
!c.is_ascii_whitespace()
}
};
while let Some(c) = src.next_if(should_take_next) {
if c != b'\\' {
buf.push(c);
continue;
};
let Some(c) = src.next() else {
return Err(Error::MalformedTmpfilesPath);
};
let c = match c {
b'\\' => b'\\',
b'n' => b'\n',
b'r' => b'\r',
b't' => b'\t',
b'x' => {
let mut s = String::new();
s.push(src.next().ok_or(Error::MalformedTmpfilesPath)?.into());
s.push(src.next().ok_or(Error::MalformedTmpfilesPath)?.into());
u8::from_str_radix(&s, 16).map_err(|_| Error::MalformedTmpfilesPath)?
}
_ => return Err(Error::MalformedTmpfilesPath),
};
buf.push(c);
}
Ok(())
}
fn unescape_path<I>(src: &mut Peekable<I>) -> Result<PathBuf>
where
I: Iterator<Item = u8>,
{
let mut r = Vec::new();
if src.next_if_eq(&b'"').is_some() {
impl_unescape_path_until(src, &mut r, true)?;
} else {
impl_unescape_path_until(src, &mut r, false)?;
};
let r = OsString::from_vec(r);
Ok(PathBuf::from(r))
}
/// Canonicalize and escape a path value for tmpfiles.d
/// At the current time the only canonicalization we do is remap /var/run -> /run.
fn canonicalize_escape_path<W: std::fmt::Write>(path: &Path, out: &mut W) -> std::fmt::Result {
// systemd-tmpfiles complains loudly about writing to /var/run;
// ideally, all of the packages get fixed for this but...eh.
let path = if path.starts_with("/var/run") {
let rest = &path.as_os_str().as_bytes()[4..];
Path::new(OsStr::from_bytes(rest))
} else {
path
};
escape_path(path, out)
}
/// In tmpfiles.d we only handle directories and symlinks. Directories
/// just have a mode, and symlinks just have a target.
enum FileMeta {
Directory(Mode),
Symlink(PathBuf),
}
impl FileMeta {
fn from_fs(dir: &Dir, path: &Path) -> Result<Option<Self>> {
let meta = dir.symlink_metadata(path)?;
let ftype = meta.file_type();
let r = if ftype.is_dir() {
FileMeta::Directory(Mode::from_raw_mode(meta.mode()))
} else if ftype.is_symlink() {
let target = dir.read_link_contents(path)?;
FileMeta::Symlink(target)
} else {
return Ok(None);
};
Ok(Some(r))
}
}
/// Translate a filepath entry to an equivalent tmpfiles.d line.
pub(crate) fn translate_to_tmpfiles_d(
abs_path: &Path,
meta: FileMeta,
username: &str,
groupname: &str,
) -> Result<String> {
let mut bufwr = String::new();
let filetype_char = match &meta {
FileMeta::Directory(_) => 'd',
FileMeta::Symlink(_) => 'L',
};
write!(bufwr, "{filetype_char} ")?;
canonicalize_escape_path(abs_path, &mut bufwr)?;
match meta {
FileMeta::Directory(mode) => {
write!(bufwr, " {mode:04o} {username} {groupname} - -")?;
}
FileMeta::Symlink(target) => {
bufwr.push_str(" - - - - ");
canonicalize_escape_path(&target, &mut bufwr)?;
}
};
Ok(bufwr)
}
/// The result of a tmpfiles.d generation run
#[derive(Debug, Default)]
pub struct TmpfilesWrittenResult {
/// Set if we generated entries; this is the count and the path.
pub generated: Option<(NonZeroUsize, Utf8PathBuf)>,
/// Total number of unsupported files that were skipped
pub unsupported: usize,
}
/// Translate the content of `/var` underneath the target root to use tmpfiles.d.
pub fn var_to_tmpfiles<U: uzers::Users, G: uzers::Groups>(
rootfs: &Dir,
users: &U,
groups: &G,
) -> Result<TmpfilesWrittenResult> {
let (existing_tmpfiles, generation) = read_tmpfiles(rootfs)?;
// We should never have /var/run as a non-symlink. Don't recurse into it, it's
// a hard error.
if let Some(meta) = rootfs.symlink_metadata_optional("var/run")? {
if !meta.is_symlink() {
return Err(Error::FoundVarRunNonSymlink {});
}
}
// Require that the tmpfiles.d directory exists; it's part of systemd.
if !rootfs.try_exists(TMPFILESD)? {
return Err(Error::MissingTmpfilesDir {});
}
let mut entries = BTreeSet::new();
let mut prefix = PathBuf::from("/var");
let mut unsupported = Vec::new();
convert_path_to_tmpfiles_d_recurse(
&TmpfilesConvertConfig {
users,
groups,
rootfs,
existing: &existing_tmpfiles,
readonly: false,
},
&mut entries,
&mut unsupported,
&mut prefix,
)?;
// If there's no entries, don't write a file
let Some(entries_count) = NonZeroUsize::new(entries.len()) else {
return Ok(TmpfilesWrittenResult::default());
};
let path = generation.path();
// This should not exist
assert!(!rootfs.try_exists(&path)?);
rootfs.atomic_replace_with(&path, |bufwr| -> Result<()> {
let mode = Permissions::from_mode(0o644);
bufwr.get_mut().as_file_mut().set_permissions(mode)?;
for line in entries.iter() {
bufwr.write_all(line.as_bytes())?;
writeln!(bufwr)?;
}
if !unsupported.is_empty() {
let (samples, rest) = bootc_utils::iterator_split(unsupported.iter(), 5);
for elt in samples {
writeln!(bufwr, "# bootc ignored: {elt:?}")?;
}
let rest = rest.count();
if rest > 0 {
writeln!(bufwr, "# bootc ignored: ...and {rest} more")?;
}
}
Ok(())
})?;
Ok(TmpfilesWrittenResult {
generated: Some((entries_count, path)),
unsupported: unsupported.len(),
})
}
/// Configuration for recursive tmpfiles conversion
struct TmpfilesConvertConfig<'a, U: uzers::Users, G: uzers::Groups> {
users: &'a U,
groups: &'a G,
rootfs: &'a Dir,
existing: &'a BTreeMap<PathBuf, String>,
readonly: bool,
}
/// Recursively explore target directory and translate content to tmpfiles.d entries. See
/// `convert_var_to_tmpfiles_d` for more background.
///
/// This proceeds depth-first and progressively deletes translated subpaths as it goes.
/// `prefix` is updated at each recursive step, so that in case of errors it can be
/// used to pinpoint the faulty path.
fn convert_path_to_tmpfiles_d_recurse<U: uzers::Users, G: uzers::Groups>(
config: &TmpfilesConvertConfig<'_, U, G>,
out_entries: &mut BTreeSet<String>,
out_unsupported: &mut Vec<PathBuf>,
prefix: &mut PathBuf,
) -> Result<()> {
let relpath = prefix.strip_prefix("/").unwrap();
for subpath in config.rootfs.read_dir(relpath)? {
let subpath = subpath?;
let meta = subpath.metadata()?;
let fname = subpath.file_name();
prefix.push(fname);
let has_tmpfiles_entry = config.existing.contains_key(prefix);
// Translate this file entry.
if !has_tmpfiles_entry {
let entry = {
// SAFETY: We know this path is absolute
let relpath = prefix.strip_prefix("/").unwrap();
let Some(tmpfiles_meta) = FileMeta::from_fs(config.rootfs, &relpath)? else {
out_unsupported.push(relpath.into());
assert!(prefix.pop());
continue;
};
let uid = meta.uid();
let gid = meta.gid();
let user = config
.users
.get_user_by_uid(meta.uid())
.ok_or(Error::UserNotFound(uid))?;
let username = user.name();
let username: &str = username.to_str().ok_or_else(|| Error::NonUtf8User {
uid,
name: username.to_string_lossy().into_owned(),
})?;
let group = config
.groups
.get_group_by_gid(gid)
.ok_or(Error::GroupNotFound(gid))?;
let groupname = group.name();
let groupname: &str = groupname.to_str().ok_or_else(|| Error::NonUtf8Group {
gid,
name: groupname.to_string_lossy().into_owned(),
})?;
translate_to_tmpfiles_d(&prefix, tmpfiles_meta, &username, &groupname)?
};
out_entries.insert(entry);
}
if meta.is_dir() {
// SAFETY: We know this path is absolute
let relpath = prefix.strip_prefix("/").unwrap();
// Avoid traversing mount points by default
if config.rootfs.open_dir_noxdev(relpath)?.is_some() {
convert_path_to_tmpfiles_d_recurse(config, out_entries, out_unsupported, prefix)?;
let relpath = prefix.strip_prefix("/").unwrap();
if !config.readonly {
config.rootfs.remove_dir_all(relpath)?;
}
}
} else {
// SAFETY: We know this path is absolute
let relpath = prefix.strip_prefix("/").unwrap();
if !config.readonly {
config.rootfs.remove_file(relpath)?;
}
}
assert!(prefix.pop());
}
Ok(())
}
/// Convert /var for the current root to use systemd tmpfiles.d.
#[allow(unsafe_code)]
pub fn convert_var_to_tmpfiles_current_root() -> Result<TmpfilesWrittenResult> {
let rootfs = Dir::open_ambient_dir("/", cap_std::ambient_authority())?;
// See the docs for why this is unsafe
let usergroups = unsafe { uzers::cache::UsersSnapshot::new() };
var_to_tmpfiles(&rootfs, &usergroups, &usergroups)
}
/// The result of processing tmpfiles.d
#[derive(Debug)]
pub struct TmpfilesResult {
/// The resulting tmpfiles.d entries
pub tmpfiles: BTreeSet<String>,
/// Paths which could not be processed
pub unsupported: Vec<PathBuf>,
}
/// Convert /var for the current root to use systemd tmpfiles.d.
#[allow(unsafe_code)]
pub fn find_missing_tmpfiles_current_root() -> Result<TmpfilesResult> {
use uzers::cache::UsersSnapshot;
let rootfs = Dir::open_ambient_dir("/", cap_std::ambient_authority())?;
// See the docs for why this is unsafe
let usergroups = unsafe { UsersSnapshot::new() };
let existing_tmpfiles = read_tmpfiles(&rootfs)?.0;
let mut prefix = PathBuf::from("/var");
let mut tmpfiles = BTreeSet::new();
let mut unsupported = Vec::new();
convert_path_to_tmpfiles_d_recurse(
&TmpfilesConvertConfig {
users: &usergroups,
groups: &usergroups,
rootfs: &rootfs,
existing: &existing_tmpfiles,
readonly: true,
},
&mut tmpfiles,
&mut unsupported,
&mut prefix,
)?;
Ok(TmpfilesResult {
tmpfiles,
unsupported,
})
}
/// Read all tmpfiles.d entries in the target directory, and return a mapping
/// from (file path) => (single tmpfiles.d entry line)
fn read_tmpfiles(rootfs: &Dir) -> Result<(BTreeMap<PathBuf, String>, BootcTmpfilesGeneration)> {
let Some(tmpfiles_dir) = rootfs.open_dir_optional(TMPFILESD)? else {
return Ok(Default::default());
};
let mut result = BTreeMap::new();
let mut generation = BootcTmpfilesGeneration::default();
for entry in tmpfiles_dir.entries()? {
let entry = entry?;
let name = entry.file_name();
let (Some(stem), Some(extension)) =
(Path::new(&name).file_stem(), Path::new(&name).extension())
else {
continue;
};
if extension != "conf" {
continue;
}
if let Ok(s) = stem.as_str() {
if s.starts_with(BOOTC_GENERATED_PREFIX) {
generation.increment();
}
}
let r = BufReader::new(entry.open()?);
for line in r.lines() {
let line = line?;
if line.is_empty() || line.starts_with("#") {
continue;
}
let path = tmpfiles_entry_get_path(&line)?;
result.insert(path.to_owned(), line);
}
}
Ok((result, generation))
}
fn tmpfiles_entry_get_path(line: &str) -> Result<PathBuf> {
let err = || Error::MalformedTmpfilesEntry(line.to_string());
let mut it = line.as_bytes().iter().copied().peekable();
// Skip leading whitespace
while it.next_if(|c| c.is_ascii_whitespace()).is_some() {}
// Skip the file type
let mut found_ftype = false;
while it.next_if(|c| !c.is_ascii_whitespace()).is_some() {
found_ftype = true
}
if !found_ftype {
return Err(err());
}
// Skip trailing whitespace
while it.next_if(|c| c.is_ascii_whitespace()).is_some() {}
unescape_path(&mut it)
}
/// A parsed tmpfiles entry kind and path of interest.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TmpfilesEntryRef {
/// The entry type character (e.g. 'd', 'L', 'z', 'Z', ...)
pub kind: char,
/// The target path for the entry
pub path: PathBuf,
}
/// Chown-affecting tmpfiles.d entries summary
#[derive(Debug, Default, Clone)]
pub struct TmpfilesChowners {
/// Exact chown entries (non-recursive) i.e. kind 'z'
pub exact: BTreeSet<PathBuf>,
/// Recursive chown entries (apply to all children) i.e. kind 'Z'
pub recursive: BTreeSet<PathBuf>,
}
impl TmpfilesChowners {
/// Returns true if a chown entry would apply to the specified absolute path
pub fn covers(&self, p: &Path) -> bool {
if self.exact.contains(p) {
return true;
}
// For recursive entries, any ancestor match qualifies
for anc in p.ancestors() {
if self.recursive.contains(anc) {
return true;
}
}
false
}
}
fn tmpfiles_entry_get_kind(line: &str) -> Option<char> {
let mut it = line.bytes();
// Skip leading whitespace
while let Some(c) = it.next() {
if !c.is_ascii_whitespace() {
return Some(c as char);
}
}
None
}
/// Read tmpfiles.d entries and return only those affecting chown operations (z/Z)
pub fn read_tmpfiles_chowners(rootfs: &Dir) -> Result<TmpfilesChowners> {
let Some(tmpfiles_dir) = rootfs.open_dir_optional(TMPFILESD)? else {
return Ok(Default::default());
};
let mut out = TmpfilesChowners::default();
for entry in tmpfiles_dir.entries()? {
let entry = entry?;
// Only process .conf files
let name = entry.file_name();
let path = Path::new(&name);
if path.extension() != Some(OsStr::new("conf")) {
continue;
}
let r = BufReader::new(entry.open()?);
for line in r.lines() {
let line = line?;
if line.is_empty() || line.starts_with('#') {
continue;
}
let Some(kind) = tmpfiles_entry_get_kind(&line) else { continue };
if kind != 'z' && kind != 'Z' {
continue;
}
let path = tmpfiles_entry_get_path(&line)?;
match kind {
'z' => {
out.exact.insert(path);
}
'Z' => {
out.recursive.insert(path);
}
_ => unreachable!(),
}
}
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use cap_std::fs::DirBuilder;
use cap_std_ext::cap_std::fs::DirBuilderExt as _;
#[test]
fn test_tmpfiles_entry_get_path() {
let cases = [
("z /dev/kvm 0666 - kvm -", "/dev/kvm"),
("d /run/lock/lvm 0700 root root -", "/run/lock/lvm"),
("a+ /var/lib/tpm2-tss/system/keystore - - - - default:group:tss:rwx", "/var/lib/tpm2-tss/system/keystore"),
("d \"/run/file with spaces/foo\" 0700 root root -", "/run/file with spaces/foo"),
(
r#"d /spaces\x20\x20here/foo 0700 root root -"#,
"/spaces here/foo",
),
];
for (input, expected) in cases {
let path = tmpfiles_entry_get_path(input).unwrap();
assert_eq!(path, Path::new(expected), "Input: {input}");
}
}
fn newroot() -> Result<cap_std_ext::cap_tempfile::TempDir> {
let root = cap_std_ext::cap_tempfile::tempdir(cap_std::ambient_authority())?;
root.create_dir_all(TMPFILESD)?;
Ok(root)
}
fn mock_userdb() -> uzers::mock::MockUsers {
let testuid = rustix::process::getuid();
let testgid = rustix::process::getgid();
let mut users = uzers::mock::MockUsers::with_current_uid(testuid.as_raw());
users.add_user(uzers::User::new(
testuid.as_raw(),
"testuser",
testgid.as_raw(),
));
users.add_group(uzers::Group::new(testgid.as_raw(), "testgroup"));
users
}
#[test]
fn test_tmpfiles_d_translation() -> anyhow::Result<()> {
// Prepare a minimal rootfs as playground.
let rootfs = &newroot()?;
let userdb = &mock_userdb();
let mut db = DirBuilder::new();
db.recursive(true);
db.mode(0o755);
rootfs.write(
Path::new(TMPFILESD).join("systemd.conf"),
indoc::indoc! { r#"
d /var/lib 0755 - - -
d /var/lib/private 0700 root root -
d /var/log/private 0700 root root -
"#},
)?;
// Add test content.
rootfs.ensure_dir_with("var/lib/systemd", &db)?;
rootfs.ensure_dir_with("var/lib/private", &db)?;
rootfs.ensure_dir_with("var/lib/nfs", &db)?;
let global_rwx = Permissions::from_mode(0o777);
rootfs.ensure_dir_with("var/lib/test/nested", &db).unwrap();
rootfs.set_permissions("var/lib/test", global_rwx.clone())?;
rootfs.set_permissions("var/lib/test/nested", global_rwx)?;
rootfs.symlink("../", "var/lib/test/nested/symlink")?;
rootfs.symlink_contents("/var/lib/foo", "var/lib/test/absolute-symlink")?;
var_to_tmpfiles(rootfs, userdb, userdb).unwrap();
// This is the first run
let mut gen = BootcTmpfilesGeneration(0);
let autovar_path = &gen.path();
assert!(rootfs.try_exists(autovar_path).unwrap());
let entries: Vec<String> = rootfs
.read_to_string(autovar_path)
.unwrap()
.lines()
.map(|s| s.to_owned())
.collect();
let expected = &[
"L /var/lib/test/absolute-symlink - - - - /var/lib/foo",
"L /var/lib/test/nested/symlink - - - - ../",
"d /var/lib/nfs 0755 testuser testgroup - -",
"d /var/lib/systemd 0755 testuser testgroup - -",
"d /var/lib/test 0777 testuser testgroup - -",
"d /var/lib/test/nested 0777 testuser testgroup - -",
];
similar_asserts::assert_eq!(entries, expected);
assert!(!rootfs.try_exists("var/lib").unwrap());
// Now pretend we're doing a layered container build, and so we need
// a new tmpfiles.d run
rootfs.create_dir_all("var/lib/gen2-test")?;
let w = var_to_tmpfiles(rootfs, userdb, userdb).unwrap();
let wg = w.generated.as_ref().unwrap();
assert_eq!(wg.0, NonZeroUsize::new(1).unwrap());
assert_eq!(w.unsupported, 0);
gen.increment();
let autovar_path = &gen.path();
assert_eq!(autovar_path, &wg.1);
assert!(rootfs.try_exists(autovar_path).unwrap());
Ok(())
}
/// Verify that we emit ignores for regular files
#[test]
fn test_log_regfile() -> anyhow::Result<()> {
// Prepare a minimal rootfs as playground.
let rootfs = &newroot()?;
let userdb = &mock_userdb();
rootfs.create_dir_all("var/log/dnf")?;
rootfs.write("var/log/dnf/dnf.log", b"some dnf log")?;
rootfs.create_dir_all("var/log/foo")?;
rootfs.write("var/log/foo/foo.log", b"some other log")?;
let gen = BootcTmpfilesGeneration(0);
var_to_tmpfiles(rootfs, userdb, userdb).unwrap();
let tmpfiles = rootfs.read_to_string(&gen.path()).unwrap();
let ignored = tmpfiles
.lines()
.filter(|line| line.starts_with("# bootc ignored"))
.count();
assert_eq!(ignored, 2);
Ok(())
}
#[test]
fn test_canonicalize_escape_path() {
let intact_cases = vec!["/", "/var", "/var/foo", "/run/foo"];
for entry in intact_cases {
let mut s = String::new();
canonicalize_escape_path(Path::new(entry), &mut s).unwrap();
similar_asserts::assert_eq!(&s, entry);
}
let quoting_cases = &[
("/var/foo bar", r#"/var/foo\x20bar"#),
("/var/run", "/run"),
("/var/run/foo bar", r#"/run/foo\x20bar"#),
];
for (input, expected) in quoting_cases {
let mut s = String::new();
canonicalize_escape_path(Path::new(input), &mut s).unwrap();
similar_asserts::assert_eq!(&s, expected);
}
}
#[test]
fn test_translate_to_tmpfiles_d() {
let path = Path::new(r#"/var/foo bar"#);
let username = "testuser";
let groupname = "testgroup";
{
// Directory
let meta = FileMeta::Directory(Mode::from_raw_mode(0o721));
let out = translate_to_tmpfiles_d(path, meta, username, groupname).unwrap();
let expected = r#"d /var/foo\x20bar 0721 testuser testgroup - -"#;
similar_asserts::assert_eq!(out, expected);
}
{
// Symlink
let meta = FileMeta::Symlink("/mytarget".into());
let out = translate_to_tmpfiles_d(path, meta, username, groupname).unwrap();
let expected = r#"L /var/foo\x20bar - - - - /mytarget"#;
similar_asserts::assert_eq!(out, expected);
}
}
}