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