Skip to main content

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