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(sha256!(
168 "fixed:out:{}{}:{}",
169 ca_kind_prefix(ca_hash),
170 ca_hash.hash().to_nix_lowerhex_string(),
171 out_output
172 .path
173 .as_ref()
174 .map(StorePath::to_absolute_path)
175 .unwrap_or_default(),
176 ))
177 }
178
179 /// Calculates the hash of a derivation modulo fixed-output subderivations.
180 ///
181 /// This is called `hashDerivationModulo` in nixcpp.
182 ///
183 /// It returns the sha256 digest of the derivation ATerm representation,
184 /// except that:
185 /// - any input derivation paths have beed replaced "by the result of a
186 /// recursive call to this function" and that
187 /// - for fixed-output derivations the special
188 /// `fixed:out:${algo}:${digest}:${fodPath}` string is hashed instead of
189 /// the A-Term.
190 ///
191 /// It's up to the caller of this function to provide a (infallible) lookup
192 /// function to query the [Derivation::hash_derivation_modulo] of direct
193 /// input derivations, by their [StorePathRef].
194 /// It will only be called in case the derivation is not a fixed-output
195 /// derivation.
196 pub fn hash_derivation_modulo<F>(&self, fn_lookup_hash_derivation_modulo: F) -> [u8; 32]
197 where
198 F: Fn(&StorePathRef) -> [u8; 32],
199 {
200 // Fixed-output derivations return a fixed hash.
201 // Non-Fixed-output derivations return the sha256 digest of the ATerm
202 // notation, but with all input_derivation paths replaced by a recursive
203 // call to this function.
204 // We call [fn_lookup_hash_derivation_modulo] rather than recursing
205 // ourselves, so callers can precompute this.
206 self.fod_digest().unwrap_or({
207 // For each input_derivation, look up the hash derivation modulo,
208 // and replace the derivation path in the aterm with it's HEXLOWER digest.
209 let aterm_bytes = self.to_aterm_bytes_with_replacements(&BTreeMap::from_iter(
210 self.input_derivations
211 .iter()
212 .map(|(drv_path, output_names)| {
213 let hash = fn_lookup_hash_derivation_modulo(&drv_path.as_ref());
214
215 (hash, output_names.to_owned())
216 }),
217 ));
218
219 // write the ATerm of that to the hash function and return its digest.
220 Sha256::digest(aterm_bytes).into()
221 })
222 }
223
224 /// This calculates all output paths of a Derivation and updates the struct.
225 /// It requires the struct to be initially without output paths.
226 /// This means, self.outputs[$outputName].path needs to be an empty string,
227 /// and self.environment[$outputName] needs to be an empty string.
228 ///
229 /// Output path calculation requires knowledge of the
230 /// [Derivation::hash_derivation_modulo], which (in case of non-fixed-output
231 /// derivations) also requires knowledge of the
232 /// [Derivation::hash_derivation_modulo] of input derivations (recursively).
233 ///
234 /// To avoid recursing and doing unnecessary calculation, we simply
235 /// ask the caller of this function to provide the result of the
236 /// [Derivation::hash_derivation_modulo] call of the current [Derivation],
237 /// and leave it up to them to calculate it when needed.
238 ///
239 /// On completion, `self.environment[$outputName]` and
240 /// `self.outputs[$outputName].path` are set to the calculated output path for all
241 /// outputs.
242 pub fn calculate_output_paths(
243 &mut self,
244 name: &str,
245 hash_derivation_modulo: &[u8; 32],
246 ) -> Result<(), DerivationError> {
247 // The fingerprint and hash differs per output
248 for (output_name, output) in self.outputs.iter_mut() {
249 // Assert that outputs are not yet populated, to avoid using this function wrongly.
250 // We don't also go over self.environment, but it's a sufficient
251 // footgun prevention mechanism.
252 assert!(output.path.is_none());
253
254 let path_name = output_path_name(name, output_name);
255
256 // For fixed output derivation we use [build_ca_path], otherwise we
257 // use [build_output_path] with [hash_derivation_modulo].
258 let store_path = if let Some(ref hwm) = output.ca_hash {
259 build_ca_path(&path_name, hwm, Vec::<&str>::new(), false).map_err(|e| {
260 DerivationError::InvalidOutputDerivationPath(output_name.to_string(), e)
261 })?
262 } else {
263 build_output_path(hash_derivation_modulo, output_name, &path_name).map_err(|e| {
264 DerivationError::InvalidOutputDerivationPath(
265 output_name.to_string(),
266 store_path::BuildStorePathError::InvalidStorePath(e),
267 )
268 })?
269 };
270
271 self.environment.insert(
272 output_name.to_string(),
273 store_path.to_absolute_path().into(),
274 );
275 output.path = Some(store_path);
276 }
277
278 Ok(())
279 }
280}
281
282#[cfg(feature = "async")]
283#[allow(dead_code)]
284trait DerivationAsyncExt {
285 /// Parse an Derivation in ATerm serialization, and validate it passes
286 /// our set of validations, from a asynchronous buffered reader.
287 /// This is a streaming variant of [Derivation::from_aterm_bytes].
288 async fn from_streaming_aterm_bytes<R>(reader: R) -> Result<Derivation, parser::Error<Vec<u8>>>
289 where
290 R: tokio::io::AsyncBufRead + Unpin + Send;
291}
292
293#[cfg(feature = "async")]
294impl DerivationAsyncExt for Derivation {
295 async fn from_streaming_aterm_bytes<R>(
296 mut reader: R,
297 ) -> Result<Derivation, parser::Error<Vec<u8>>>
298 where
299 R: tokio::io::AsyncBufRead + Unpin + Send,
300 {
301 use tokio::io::AsyncBufReadExt;
302 let mut buffer = Vec::new();
303 loop {
304 let rest = reader.fill_buf().await.unwrap();
305 let length = rest.len();
306
307 // We reached EOF, we can stop and return incompleteness.
308 if length == 0 {
309 return Err(ParserError::Incomplete);
310 }
311
312 buffer.extend_from_slice(rest);
313
314 // Parse the so-far internal buffer of reader.
315 match parser::parse_streaming(&buffer) {
316 (Err(parser::Error::Incomplete), _) => {
317 reader.consume(length);
318 continue;
319 }
320 (Ok(derivation), leftover) => {
321 // We cannot inline it in the next call because `reader` is mutably borrowed
322 // and has a relationship with the lifetime of `leftover`.
323 let leftover_length = leftover.len();
324
325 // Well, if we already had consumed the leftovers of the past fetch
326 // while believing we were just parsing incomplete ATerm, there's nothing
327 // we can do about it. The protocol is made this way.
328 if length >= leftover_length {
329 // We still have leftover, let's not consume it.
330 // It's not for us.
331 reader.consume(length - leftover_length);
332 }
333 return Ok(derivation);
334 }
335 (Err(e), _) => {
336 return Err(e.into());
337 }
338 }
339 }
340 }
341}
342
343/// Calculate the name part of the store path of a derivation [Output].
344///
345/// It's the name, and (if it's the non-out output), the output name
346/// after a `-`.
347fn output_path_name(derivation_name: &str, output_name: &str) -> String {
348 let mut output_path_name = derivation_name.to_string();
349 if output_name != "out" {
350 output_path_name.push('-');
351 output_path_name.push_str(output_name);
352 }
353 output_path_name
354}
355
356/// For a [CAHash], return the "prefix" used for NAR purposes.
357/// For [CAHash::Flat], this is an empty string, for [CAHash::Nar], it's "r:".
358/// Panics for other [CAHash] kinds, as they're not valid in a derivation
359/// context.
360fn ca_kind_prefix(ca_hash: &CAHash) -> &'static str {
361 match ca_hash {
362 CAHash::Flat(_) => "",
363 CAHash::Nar(_) => "r:",
364 _ => panic!("invalid ca hash in derivation context: {ca_hash:?}"),
365 }
366}