nix_compat/derivation/mod.rs
1use crate::store_path::{
2 self, StorePath, StorePathRef, build_ca_path, build_output_path, build_text_path,
3};
4use bstr::BString;
5#[cfg(feature = "serde")]
6use serde::{Deserialize, Serialize};
7use sha2::{Digest, Sha256};
8use std::collections::{BTreeMap, BTreeSet};
9use std::io;
10
11mod errors;
12mod output;
13mod parse_error;
14mod parser;
15mod validate;
16mod write;
17
18#[cfg(test)]
19mod tests;
20
21// Public API of the crate.
22pub use crate::nixhash::{CAHash, NixHash};
23pub use errors::{DerivationError, OutputError};
24pub use output::Output;
25pub use parser::Error as ParserError;
26pub use validate::validate_output_name;
27
28use self::write::AtermWriteable;
29
30#[derive(Clone, Debug, Default, Eq, PartialEq)]
31#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
32pub struct Derivation {
33 #[cfg_attr(feature = "serde", serde(rename = "args"))]
34 pub arguments: Vec<String>,
35
36 pub builder: String,
37
38 #[cfg_attr(feature = "serde", serde(rename = "env"))]
39 pub environment: BTreeMap<String, BString>,
40
41 /// Map from drv path to output names used from this derivation.
42 #[cfg_attr(feature = "serde", serde(rename = "inputDrvs"))]
43 pub input_derivations: BTreeMap<StorePath<String>, BTreeSet<String>>,
44
45 /// Plain store paths of additional inputs.
46 #[cfg_attr(feature = "serde", serde(rename = "inputSrcs"))]
47 pub input_sources: BTreeSet<StorePath<String>>,
48
49 /// Maps output names to Output.
50 pub outputs: BTreeMap<String, Output>,
51
52 pub system: String,
53}
54
55impl Derivation {
56 /// write the Derivation to the given [std::io::Write], in ATerm format.
57 ///
58 /// The only errors returns are these when writing to the passed writer.
59 pub fn serialize(&self, writer: &mut impl std::io::Write) -> Result<(), io::Error> {
60 self.serialize_with_replacements(writer, &self.input_derivations)
61 }
62
63 /// Like `serialize` but allow replacing the input_derivations for hash calculations.
64 fn serialize_with_replacements(
65 &self,
66 writer: &mut impl std::io::Write,
67 input_derivations: &BTreeMap<impl AtermWriteable, BTreeSet<String>>,
68 ) -> Result<(), io::Error> {
69 use write::*;
70
71 writer.write_all(write::DERIVATION_PREFIX.as_bytes())?;
72 write_char(writer, write::PAREN_OPEN)?;
73
74 write_outputs(writer, &self.outputs)?;
75 write_char(writer, COMMA)?;
76
77 write_input_derivations(writer, input_derivations)?;
78 write_char(writer, COMMA)?;
79
80 write_input_sources(writer, &self.input_sources)?;
81 write_char(writer, COMMA)?;
82
83 write_system(writer, &self.system)?;
84 write_char(writer, COMMA)?;
85
86 write_builder(writer, &self.builder)?;
87 write_char(writer, COMMA)?;
88
89 write_arguments(writer, &self.arguments)?;
90 write_char(writer, COMMA)?;
91
92 write_environment(writer, &self.environment)?;
93
94 write_char(writer, PAREN_CLOSE)?;
95
96 Ok(())
97 }
98
99 /// return the ATerm serialization.
100 pub fn to_aterm_bytes(&self) -> Vec<u8> {
101 self.to_aterm_bytes_with_replacements(&self.input_derivations)
102 }
103
104 /// Like `to_aterm_bytes`, but accept a different BTreeMap for input_derivations.
105 /// This is used to render the ATerm representation of a Derivation "modulo
106 /// fixed-output derivations".
107 fn to_aterm_bytes_with_replacements(
108 &self,
109 input_derivations: &BTreeMap<impl AtermWriteable, BTreeSet<String>>,
110 ) -> Vec<u8> {
111 let mut buffer: Vec<u8> = Vec::new();
112
113 // invoke serialize and write to the buffer.
114 // Note we only propagate errors writing to the writer in serialize,
115 // which won't panic for the string we write to.
116 self.serialize_with_replacements(&mut buffer, input_derivations)
117 .unwrap();
118
119 buffer
120 }
121
122 /// Parse an Derivation in ATerm serialization, and validate it passes our
123 /// set of validations.
124 pub fn from_aterm_bytes(b: &[u8]) -> Result<Derivation, parser::Error<&[u8]>> {
125 parser::parse(b)
126 }
127
128 /// Returns the drv path of a [Derivation] struct.
129 ///
130 /// The drv path is calculated by invoking [build_text_path], using
131 /// the `name` with a `.drv` suffix as name, all [Derivation::input_sources] and
132 /// keys of [Derivation::input_derivations] as references, and the ATerm string of
133 /// the [Derivation] as content.
134 pub fn calculate_derivation_path(
135 &self,
136 name: &str,
137 ) -> Result<StorePath<String>, DerivationError> {
138 // append .drv to the name
139 let name = format!("{name}.drv");
140
141 // collect the list of paths from input_sources and input_derivations
142 // into a (sorted, guaranteed by BTreeSet) list of references
143 let references: BTreeSet<String> = self
144 .input_sources
145 .iter()
146 .chain(self.input_derivations.keys())
147 .map(StorePath::to_absolute_path)
148 .collect();
149
150 build_text_path(&name, self.to_aterm_bytes(), references)
151 .map_err(|_e| DerivationError::InvalidOutputName(name))
152 }
153
154 /// Returns the FOD digest, if the derivation is fixed-output, or None if
155 /// it's not.
156 /// TODO: this is kinda the string from [build_ca_path] with a
157 /// [CAHash::Flat], what's fed to `build_store_path_from_fingerprint_parts`
158 /// (except the out_output.path being an empty string)
159 pub fn fod_digest(&self) -> Option<[u8; 32]> {
160 if self.outputs.len() != 1 {
161 return None;
162 }
163
164 let out_output = self.outputs.get("out")?;
165 let ca_hash = out_output.ca_hash.as_ref()?;
166
167 Some(
168 Sha256::new_with_prefix(format!(
169 "fixed:out:{}{}:{}",
170 ca_kind_prefix(ca_hash),
171 ca_hash.hash().to_nix_lowerhex_string(),
172 out_output
173 .path
174 .as_ref()
175 .map(StorePath::to_absolute_path)
176 .unwrap_or_default(),
177 ))
178 .finalize()
179 .into(),
180 )
181 }
182
183 /// Calculates the hash of a derivation modulo fixed-output subderivations.
184 ///
185 /// This is called `hashDerivationModulo` in nixcpp.
186 ///
187 /// It returns the sha256 digest of the derivation ATerm representation,
188 /// except that:
189 /// - any input derivation paths have beed replaced "by the result of a
190 /// recursive call to this function" and that
191 /// - for fixed-output derivations the special
192 /// `fixed:out:${algo}:${digest}:${fodPath}` string is hashed instead of
193 /// the A-Term.
194 ///
195 /// It's up to the caller of this function to provide a (infallible) lookup
196 /// function to query the [Derivation::hash_derivation_modulo] of direct
197 /// input derivations, by their [StorePathRef].
198 /// It will only be called in case the derivation is not a fixed-output
199 /// derivation.
200 pub fn hash_derivation_modulo<F>(&self, fn_lookup_hash_derivation_modulo: F) -> [u8; 32]
201 where
202 F: Fn(&StorePathRef) -> [u8; 32],
203 {
204 // Fixed-output derivations return a fixed hash.
205 // Non-Fixed-output derivations return the sha256 digest of the ATerm
206 // notation, but with all input_derivation paths replaced by a recursive
207 // call to this function.
208 // We call [fn_lookup_hash_derivation_modulo] rather than recursing
209 // ourselves, so callers can precompute this.
210 self.fod_digest().unwrap_or({
211 // For each input_derivation, look up the hash derivation modulo,
212 // and replace the derivation path in the aterm with it's HEXLOWER digest.
213 let aterm_bytes = self.to_aterm_bytes_with_replacements(&BTreeMap::from_iter(
214 self.input_derivations
215 .iter()
216 .map(|(drv_path, output_names)| {
217 let hash = fn_lookup_hash_derivation_modulo(&drv_path.as_ref());
218
219 (hash, output_names.to_owned())
220 }),
221 ));
222
223 // write the ATerm of that to the hash function and return its digest.
224 Sha256::new_with_prefix(aterm_bytes).finalize().into()
225 })
226 }
227
228 /// This calculates all output paths of a Derivation and updates the struct.
229 /// It requires the struct to be initially without output paths.
230 /// This means, self.outputs[$outputName].path needs to be an empty string,
231 /// and self.environment[$outputName] needs to be an empty string.
232 ///
233 /// Output path calculation requires knowledge of the
234 /// [Derivation::hash_derivation_modulo], which (in case of non-fixed-output
235 /// derivations) also requires knowledge of the
236 /// [Derivation::hash_derivation_modulo] of input derivations (recursively).
237 ///
238 /// To avoid recursing and doing unnecessary calculation, we simply
239 /// ask the caller of this function to provide the result of the
240 /// [Derivation::hash_derivation_modulo] call of the current [Derivation],
241 /// and leave it up to them to calculate it when needed.
242 ///
243 /// On completion, `self.environment[$outputName]` and
244 /// `self.outputs[$outputName].path` are set to the calculated output path for all
245 /// outputs.
246 pub fn calculate_output_paths(
247 &mut self,
248 name: &str,
249 hash_derivation_modulo: &[u8; 32],
250 ) -> Result<(), DerivationError> {
251 // The fingerprint and hash differs per output
252 for (output_name, output) in self.outputs.iter_mut() {
253 // Assert that outputs are not yet populated, to avoid using this function wrongly.
254 // We don't also go over self.environment, but it's a sufficient
255 // footgun prevention mechanism.
256 assert!(output.path.is_none());
257
258 let path_name = output_path_name(name, output_name);
259
260 // For fixed output derivation we use [build_ca_path], otherwise we
261 // use [build_output_path] with [hash_derivation_modulo].
262 let store_path = if let Some(ref hwm) = output.ca_hash {
263 build_ca_path(&path_name, hwm, Vec::<&str>::new(), false).map_err(|e| {
264 DerivationError::InvalidOutputDerivationPath(output_name.to_string(), e)
265 })?
266 } else {
267 build_output_path(hash_derivation_modulo, output_name, &path_name).map_err(|e| {
268 DerivationError::InvalidOutputDerivationPath(
269 output_name.to_string(),
270 store_path::BuildStorePathError::InvalidStorePath(e),
271 )
272 })?
273 };
274
275 self.environment.insert(
276 output_name.to_string(),
277 store_path.to_absolute_path().into(),
278 );
279 output.path = Some(store_path);
280 }
281
282 Ok(())
283 }
284}
285
286#[cfg(feature = "async")]
287#[allow(dead_code)]
288trait DerivationAsyncExt {
289 /// Parse an Derivation in ATerm serialization, and validate it passes
290 /// our set of validations, from a asynchronous buffered reader.
291 /// This is a streaming variant of [Derivation::from_aterm_bytes].
292 async fn from_streaming_aterm_bytes<R>(reader: R) -> Result<Derivation, parser::Error<Vec<u8>>>
293 where
294 R: tokio::io::AsyncBufRead + Unpin + Send;
295}
296
297#[cfg(feature = "async")]
298impl DerivationAsyncExt for Derivation {
299 async fn from_streaming_aterm_bytes<R>(
300 mut reader: R,
301 ) -> Result<Derivation, parser::Error<Vec<u8>>>
302 where
303 R: tokio::io::AsyncBufRead + Unpin + Send,
304 {
305 use tokio::io::AsyncBufReadExt;
306 let mut buffer = Vec::new();
307 loop {
308 let rest = reader.fill_buf().await.unwrap();
309 let length = rest.len();
310
311 // We reached EOF, we can stop and return incompleteness.
312 if length == 0 {
313 return Err(ParserError::Incomplete);
314 }
315
316 buffer.extend_from_slice(rest);
317
318 // Parse the so-far internal buffer of reader.
319 match parser::parse_streaming(&buffer) {
320 (Err(parser::Error::Incomplete), _) => {
321 reader.consume(length);
322 continue;
323 }
324 (Ok(derivation), leftover) => {
325 // We cannot inline it in the next call because `reader` is mutably borrowed
326 // and has a relationship with the lifetime of `leftover`.
327 let leftover_length = leftover.len();
328
329 // Well, if we already had consumed the leftovers of the past fetch
330 // while believing we were just parsing incomplete ATerm, there's nothing
331 // we can do about it. The protocol is made this way.
332 if length >= leftover_length {
333 // We still have leftover, let's not consume it.
334 // It's not for us.
335 reader.consume(length - leftover_length);
336 }
337 return Ok(derivation);
338 }
339 (Err(e), _) => {
340 return Err(e.into());
341 }
342 }
343 }
344 }
345}
346
347/// Calculate the name part of the store path of a derivation [Output].
348///
349/// It's the name, and (if it's the non-out output), the output name
350/// after a `-`.
351fn output_path_name(derivation_name: &str, output_name: &str) -> String {
352 let mut output_path_name = derivation_name.to_string();
353 if output_name != "out" {
354 output_path_name.push('-');
355 output_path_name.push_str(output_name);
356 }
357 output_path_name
358}
359
360/// For a [CAHash], return the "prefix" used for NAR purposes.
361/// For [CAHash::Flat], this is an empty string, for [CAHash::Nar], it's "r:".
362/// Panics for other [CAHash] kinds, as they're not valid in a derivation
363/// context.
364fn ca_kind_prefix(ca_hash: &CAHash) -> &'static str {
365 match ca_hash {
366 CAHash::Flat(_) => "",
367 CAHash::Nar(_) => "r:",
368 _ => panic!("invalid ca hash in derivation context: {ca_hash:?}"),
369 }
370}