bootc_lib/bootc_composefs/
state.rs1use std::io::Write;
2use std::os::unix::fs::symlink;
3use std::path::Path;
4use std::{fs::create_dir_all, process::Command};
5
6use anyhow::{Context, Result};
7use bootc_initramfs_setup::overlay_transient;
8use bootc_kernel_cmdline::utf8::Cmdline;
9use bootc_mount::tempmount::TempMount;
10use bootc_utils::CommandRunExt;
11use camino::Utf8PathBuf;
12use canon_json::CanonJsonSerialize;
13use cap_std_ext::cap_std::ambient_authority;
14use cap_std_ext::cap_std::fs::{Dir, Permissions, PermissionsExt};
15use cap_std_ext::dirext::CapStdExtDirExt;
16use composefs::fsverity::{FsVerityHashValue, Sha512HashValue};
17use fn_error_context::context;
18
19use ostree_ext::container::deploy::ORIGIN_CONTAINER;
20use rustix::{
21 fs::{Mode, OFlags, open},
22 path::Arg,
23};
24
25use crate::bootc_composefs::boot::BootType;
26use crate::bootc_composefs::repo::get_imgref;
27use crate::bootc_composefs::status::{
28 ImgConfigManifest, StagedDeployment, get_sorted_type1_boot_entries,
29};
30use crate::parsers::bls_config::BLSConfigType;
31use crate::store::{BootedComposefs, Storage};
32use crate::{
33 composefs_consts::{
34 COMPOSEFS_CMDLINE, COMPOSEFS_STAGED_DEPLOYMENT_FNAME, COMPOSEFS_TRANSIENT_STATE_DIR,
35 ORIGIN_KEY_BOOT, ORIGIN_KEY_BOOT_DIGEST, ORIGIN_KEY_BOOT_TYPE, SHARED_VAR_PATH,
36 STATE_DIR_RELATIVE,
37 },
38 parsers::bls_config::BLSConfig,
39 spec::ImageReference,
40 utils::path_relative_to,
41};
42
43pub(crate) fn get_booted_bls(boot_dir: &Dir) -> Result<BLSConfig> {
44 let cmdline = Cmdline::from_proc()?;
45 let booted = cmdline
46 .find(COMPOSEFS_CMDLINE)
47 .ok_or_else(|| anyhow::anyhow!("Failed to find composefs parameter in kernel cmdline"))?;
48
49 let sorted_entries = get_sorted_type1_boot_entries(boot_dir, true)?;
50
51 for entry in sorted_entries {
52 match &entry.cfg_type {
53 BLSConfigType::EFI { efi } => {
54 let composefs_param_value = booted.value().ok_or_else(|| {
55 anyhow::anyhow!("Failed to get composefs kernel cmdline value")
56 })?;
57
58 if efi.as_str().contains(composefs_param_value) {
59 return Ok(entry);
60 }
61 }
62
63 BLSConfigType::NonEFI { options, .. } => {
64 let Some(opts) = options else {
65 anyhow::bail!("options not found in bls config")
66 };
67
68 let opts = Cmdline::from(opts);
69
70 if opts.iter().any(|v| v == booted) {
71 return Ok(entry);
72 }
73 }
74
75 BLSConfigType::Unknown => anyhow::bail!("Unknown BLS Config type"),
76 };
77 }
78
79 Err(anyhow::anyhow!("Booted BLS not found"))
80}
81
82#[context("Initializing /etc and /var for state")]
85pub(crate) fn initialize_state(
86 sysroot_path: &Utf8PathBuf,
87 erofs_id: &String,
88 state_path: &Utf8PathBuf,
89 initialize_var: bool,
90) -> Result<()> {
91 let sysroot_fd = open(
92 sysroot_path.as_std_path(),
93 OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC,
94 Mode::empty(),
95 )
96 .context("Opening sysroot")?;
97
98 let composefs_fd = bootc_initramfs_setup::mount_composefs_image(&sysroot_fd, &erofs_id, false)?;
99
100 let tempdir = TempMount::mount_fd(composefs_fd)?;
101
102 if initialize_var {
104 Command::new("cp")
105 .args([
106 "-a",
107 "--remove-destination",
108 &format!("{}/var/.", tempdir.dir.path().as_str()?),
109 &format!("{state_path}/var/."),
110 ])
111 .run_capture_stderr()?;
112 }
113
114 let cp_ret = Command::new("cp")
115 .args([
116 "-a",
117 "--remove-destination",
118 &format!("{}/etc/.", tempdir.dir.path().as_str()?),
119 &format!("{state_path}/etc/."),
120 ])
121 .run_capture_stderr();
122
123 cp_ret
124}
125
126fn add_update_in_origin(
129 storage: &Storage,
130 deployment_id: &str,
131 section: &str,
132 kv_pairs: &[(&str, &str)],
133) -> Result<()> {
134 let path = Path::new(STATE_DIR_RELATIVE).join(deployment_id);
135
136 let state_dir = storage
137 .physical_root
138 .open_dir(path)
139 .context("Opening state dir")?;
140
141 let origin_filename = format!("{deployment_id}.origin");
142
143 let origin_file = state_dir
144 .read_to_string(&origin_filename)
145 .context("Reading origin file")?;
146
147 let mut ini =
148 tini::Ini::from_string(&origin_file).context("Failed to parse file origin file as ini")?;
149
150 for (key, value) in kv_pairs {
151 ini = ini.section(section).item(*key, *value);
152 }
153
154 state_dir
155 .atomic_replace_with(origin_filename, move |f| -> std::io::Result<_> {
156 f.write_all(ini.to_string().as_bytes())?;
157 f.flush()?;
158
159 let perms = Permissions::from_mode(0o644);
160 f.get_mut().as_file_mut().set_permissions(perms)?;
161
162 Ok(())
163 })
164 .context("Writing to origin file")?;
165
166 Ok(())
167}
168
169pub(crate) fn update_target_imgref_in_origin(
171 storage: &Storage,
172 booted_cfs: &BootedComposefs,
173 imgref: &ImageReference,
174) -> Result<()> {
175 add_update_in_origin(
176 storage,
177 booted_cfs.cmdline.digest.as_ref(),
178 "origin",
179 &[(
180 ORIGIN_CONTAINER,
181 &format!(
182 "ostree-unverified-image:{}",
183 get_imgref(&imgref.transport, &imgref.image)
184 ),
185 )],
186 )
187}
188
189pub(crate) fn update_boot_digest_in_origin(
190 storage: &Storage,
191 digest: &str,
192 boot_digest: &str,
193) -> Result<()> {
194 add_update_in_origin(
195 storage,
196 digest,
197 ORIGIN_KEY_BOOT,
198 &[(ORIGIN_KEY_BOOT_DIGEST, boot_digest)],
199 )
200}
201
202#[context("Writing composefs state")]
229pub(crate) async fn write_composefs_state(
230 root_path: &Utf8PathBuf,
231 deployment_id: &Sha512HashValue,
232 target_imgref: &ImageReference,
233 staged: Option<StagedDeployment>,
234 boot_type: BootType,
235 boot_digest: String,
236 container_details: &ImgConfigManifest,
237) -> Result<()> {
238 let state_path = root_path
239 .join(STATE_DIR_RELATIVE)
240 .join(deployment_id.to_hex());
241
242 create_dir_all(state_path.join("etc"))?;
243
244 let actual_var_path = root_path.join(SHARED_VAR_PATH);
245 create_dir_all(&actual_var_path)?;
246
247 symlink(
248 path_relative_to(state_path.as_std_path(), actual_var_path.as_std_path())
249 .context("Getting var symlink path")?,
250 state_path.join("var"),
251 )
252 .context("Failed to create symlink for /var")?;
253
254 initialize_state(
255 &root_path,
256 &deployment_id.to_hex(),
257 &state_path,
258 staged.is_none(),
259 )?;
260
261 let ImageReference {
262 image: image_name,
263 transport,
264 ..
265 } = &target_imgref;
266
267 let imgref = get_imgref(&transport, &image_name);
268
269 let mut config = tini::Ini::new().section("origin").item(
270 ORIGIN_CONTAINER,
271 format!("ostree-unverified-image:{imgref}"),
273 );
274
275 config = config
276 .section(ORIGIN_KEY_BOOT)
277 .item(ORIGIN_KEY_BOOT_TYPE, boot_type);
278
279 config = config
280 .section(ORIGIN_KEY_BOOT)
281 .item(ORIGIN_KEY_BOOT_DIGEST, boot_digest);
282
283 let state_dir =
284 Dir::open_ambient_dir(&state_path, ambient_authority()).context("Opening state dir")?;
285
286 state_dir
289 .atomic_write(
290 format!("{}.imginfo", deployment_id.to_hex()),
291 serde_json::to_vec(&container_details)?,
292 )
293 .context("Failed to write to .imginfo file")?;
294
295 state_dir
296 .atomic_write(
297 format!("{}.origin", deployment_id.to_hex()),
298 config.to_string().as_bytes(),
299 )
300 .context("Failed to write to .origin file")?;
301
302 if let Some(staged) = staged {
303 std::fs::create_dir_all(COMPOSEFS_TRANSIENT_STATE_DIR)
304 .with_context(|| format!("Creating {COMPOSEFS_TRANSIENT_STATE_DIR}"))?;
305
306 let staged_depl_dir =
307 Dir::open_ambient_dir(COMPOSEFS_TRANSIENT_STATE_DIR, ambient_authority())
308 .with_context(|| format!("Opening {COMPOSEFS_TRANSIENT_STATE_DIR}"))?;
309
310 staged_depl_dir
311 .atomic_write(
312 COMPOSEFS_STAGED_DEPLOYMENT_FNAME,
313 staged
314 .to_canon_json_vec()
315 .context("Failed to serialize staged deployment JSON")?,
316 )
317 .with_context(|| format!("Writing to {COMPOSEFS_STAGED_DEPLOYMENT_FNAME}"))?;
318 }
319
320 Ok(())
321}
322
323pub(crate) fn composefs_usr_overlay() -> Result<()> {
324 let usr = Dir::open_ambient_dir("/usr", ambient_authority()).context("Opening /usr")?;
325 let is_usr_mounted = usr
326 .is_mountpoint(".")
327 .context("Failed to get mount details for /usr")?;
328
329 let is_usr_mounted =
330 is_usr_mounted.ok_or_else(|| anyhow::anyhow!("Failed to get mountinfo"))?;
331
332 if is_usr_mounted {
333 println!("A writeable overlayfs is already mounted on /usr");
334 return Ok(());
335 }
336
337 let usr_metadata = usr.metadata(".").context("Getting /usr metadata")?;
339 let usr_mode = Mode::from_raw_mode(usr_metadata.permissions().mode());
340
341 overlay_transient(usr, Some(usr_mode))?;
342
343 println!("A writeable overlayfs is now mounted on /usr");
344 println!("All changes there will be discarded on reboot.");
345
346 Ok(())
347}