1
//! Implementation of `compute-mds` method
2

            
3
use super::*;
4

            
5
/// routerdesc to microdesc processor
6
#[derive(Deftly)]
7
#[derive_deftly(New)]
8
pub(crate) struct Processor<'o> {
9
    /// Nominal time, at which to check routerdesc validity
10
    #[deftly(new(arg))]
11
    nominal_time: SystemTime,
12

            
13
    /// Where to write generated microdescs
14
    #[deftly(new(arg))]
15
    mds_out: &'o mut Writing,
16

            
17
    /// Where to write the metadata
18
    #[deftly(new(arg))]
19
    meta_out: &'o mut Writing,
20

            
21
    /// Input descriptors that we've already processed
22
    dedup_inputs: HashSet<RdDigest>,
23

            
24
    /// Output descriptors that we've already written
25
    dedup_outputs: HashSet<MdDigest>,
26

            
27
    /// Consensus methods that triggered `Bug` (for logging deduplication)
28
    bugs_occurred: HashSet<ConsensusMethod>,
29
}
30

            
31
/// One entry in the metadata file
32
///
33
/// This is, in fact, a whole network document, which has only an intro item.
34
#[derive(Deftly)]
35
#[derive_deftly(tor_netdoc::NetdocEncodable)]
36
struct MetaFileEntry {
37
    /// The item
38
    m: MetaItem,
39
}
40

            
41
/// Values in a metadata item
42
#[derive(Deftly)]
43
#[derive_deftly(tor_netdoc::ItemValueEncodable)]
44
struct MetaItem {
45
    /// `CONSENSUS_VERSION`
46
    method: ConsensusMethod,
47

            
48
    /// `RSAID
49
    hk_relayid_rsa: Base64Fingerprint,
50

            
51
    /// `DID`
52
    hk_relayid_ed: Ed25519Public,
53

            
54
    /// `DD`
55
    h_routerdesc: RdDigest,
56

            
57
    /// `MD`
58
    h_md: MdDigest,
59
}
60

            
61
/// Router descriptor hash
62
type RdDigest = FixedB64<{ tor_netdoc::doc::routerdesc::DOC_DIGEST_LEN }>;
63
/// Microdescriptor hash
64
type MdDigest = FixedB64<{ tor_netdoc::doc::microdesc::DOC_DIGEST_LEN }>;
65

            
66
/// Routerdesc, parsed, with its location in the file
67
struct InputDescriptor {
68
    /// Start byte position
69
    start: usize,
70

            
71
    /// End byte position
72
    end: usize,
73

            
74
    /// SHA-1 (as required for the metadata file)
75
    h_routerdesc: RdDigest,
76

            
77
    /// The parsed routerdesc
78
    rd: RouterDesc,
79
}
80

            
81
impl<'o> Processor<'o> {
82
    /// Process one input file
83
3
    pub(crate) fn process_input(&mut self, input: &parse2::ParseInput<'_>) -> Result<(), CliError> {
84
3
        let router_descs = parse2::parse_netdoc_multiple_sophisticated::<
85
3
            CTorAnnotated<RouterDescUnverified>,
86
3
        >(input)?;
87

            
88
3
        for (rd, start, end) in router_descs {
89
5
            let rd = rd.map(|CTorAnnotated(rd)| rd);
90

            
91
5
            let rd = match self.parse_verify_descriptor(rd, start, end) {
92
5
                Ok(y) => y,
93
                Err(e) => {
94
                    eprintln!("bad routerdesc at bytes {start}..{end}: {}", e.report(),);
95
                    continue;
96
                }
97
            };
98

            
99
5
            self.process_descriptor(&rd)?;
100
        }
101
3
        Ok(())
102
3
    }
103

            
104
    /// Resolve a parsed descriptor (or parse error) to a `InputDescriptor`
105
    ///
106
    /// Mostly, this function exists to provide an error handling context:
107
    /// errors which occur here are (always) logged,
108
    /// with the byte positions but not the routerdesc hash.
109
5
    fn parse_verify_descriptor(
110
5
        &self,
111
5
        rd: Result<RouterDescUnverified, parse2::ParseError>,
112
5
        start: usize,
113
5
        end: usize,
114
5
    ) -> Result<InputDescriptor, anyhow::Error> {
115
        // According to the plugin spec, the final routerdesc might be truncated.
116
        // That is be handled here, and so generates the log message, above.
117
        // That seems OK.
118
5
        let rd = rd.context("parse")?;
119

            
120
        let h_routerdesc = FixedB64(
121
5
            rd.sigs
122
5
                .hashes
123
5
                .sha1
124
                .ok_or_else(|| anyhow!("not hashed with SHA-1, wrong kind of signature?"))?,
125
        );
126

            
127
5
        let rd = rd
128
5
            .verify()
129
5
            .context("verify")?
130
5
            .if_valid_at(&self.nominal_time)
131
5
            .context("check timeliness")?;
132

            
133
5
        Ok(InputDescriptor {
134
5
            h_routerdesc,
135
5
            rd,
136
5
            start,
137
5
            end,
138
5
        })
139
5
    }
140

            
141
    /// Process a descriptor into its microdescriptor(s) and write them out
142
5
    fn process_descriptor(&mut self, rd: &InputDescriptor) -> Result<(), CliError> {
143
        use tor_error::ErrorKind as EK;
144

            
145
5
        if !self.dedup_inputs.insert(rd.h_routerdesc.clone()) {
146
            return Ok(());
147
5
        }
148

            
149
5
        let (errs, mds) = match tor_dirauth::consensus::compute_supported_microdescs(&rd.rd) {
150
5
            Ok(y) => (vec![], y),
151
            Err(r) => r,
152
        };
153

            
154
5
        for (method, err) in errs.into_iter().rev() {
155
            macro_rules! log_error { { $fmt:literal } => {
156
                eprintln!(
157
                    concat!($fmt, ": {}"),
158
                    format_args!(
159
                        "rd at bytes {}..{} with hash {}",
160
                        rd.start,
161
                        rd.end,
162
                        rd.h_routerdesc,
163
                    ),
164
                    err.report(),
165
                    method=method,
166
                )
167
            } }
168

            
169
            match err.kind() {
170
                EK::RemoteProtocolViolation => {
171
                    // ie, bad routerdesc.  ignore it then, presumably.
172
                }
173
                EK::BadApiUsage | EK::Internal => {
174
                    if self.bugs_occurred.insert(method.into()) {
175
                        log_error!("bug in method {method} triggered by {}");
176
                    }
177
                }
178
                _other_kind => {
179
                    log_error!("problem due to {}, method {method}");
180
                    // Report only one error per md.
181
                    break;
182
                }
183
            }
184
        }
185

            
186
5
        for (methods, md) in mds {
187
5
            let h_md = FixedB64(Sha256::digest(&md).into());
188

            
189
5
            if self.dedup_outputs.insert(h_md.clone()) {
190
5
                self.mds_out.append_with(|w| write!(w, "{md}"))?;
191
            }
192

            
193
5
            for method in methods.methods {
194
5
                self.meta_out.write_netdocs(&[MetaFileEntry {
195
                    m: MetaItem {
196
5
                        method,
197
5
                        h_md: h_md.clone(),
198
5
                        h_routerdesc: rd.h_routerdesc.clone(),
199
5
                        hk_relayid_ed: rd.rd.identity_ed25519.get()?.id_ed25519.into(),
200
5
                        hk_relayid_rsa: rd.rd.signing_key.to_rsa_identity().into(),
201
                    },
202
                }])?;
203
            }
204
        }
205

            
206
5
        Ok(())
207
5
    }
208
}
209

            
210
#[cfg(test)]
211
mod test {
212
    // @@ begin test lint list maintained by maint/add_warning @@
213
    #![allow(clippy::bool_assert_comparison)]
214
    #![allow(clippy::clone_on_copy)]
215
    #![allow(clippy::dbg_macro)]
216
    #![allow(clippy::mixed_attributes_style)]
217
    #![allow(clippy::print_stderr)]
218
    #![allow(clippy::print_stdout)]
219
    #![allow(clippy::single_char_pattern)]
220
    #![allow(clippy::unwrap_used)]
221
    #![allow(clippy::unchecked_time_subtraction)]
222
    #![allow(clippy::useless_vec)]
223
    #![allow(clippy::needless_pass_by_value)]
224
    #![allow(clippy::string_slice)] // See arti#2571
225
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
226
    use super::*;
227
    use crate::authority_plugin::test::test_invocation;
228
    use itertools::chain;
229
    use std::fs;
230
    use std::io::Write as _;
231
    use test_temp_dir::test_temp_dir;
232
    use tor_dirauth::consensus::SupportedConsensusMethod;
233
    use tor_netdoc::{
234
        doc::microdesc::Microdesc,
235
        parse2::{ParseInput, parse_netdoc_multiple_with_offsets},
236
        testdata_live::{self, relay_document_by_nick},
237
        types::B64,
238
    };
239

            
240
    #[test]
241
    fn test_compute_mds() -> anyhow::Result<()> {
242
        let consensus = testdata_live::netstatus_plain();
243
        let nominal_time = consensus.preamble.lifetime.valid_after();
244
        let tmp = test_temp_dir!();
245

            
246
        tmp.used_by(|tmp| {
247
            let tmp: String = tmp
248
                .as_os_str()
249
                .to_str()
250
                .expect("tmp must be utf-8")
251
                .to_owned();
252
            let mds_f = format!("{tmp}/mds");
253
            let meta_f = format!("{tmp}/meta");
254
            let input_empty_f = format!("{tmp}/input-empty");
255
            fs::write(&input_empty_f, "").context("write empty file")?;
256
            let input_f = format!("{tmp}/input");
257
            (|| {
258
                let mut input = fs::File::create(&input_f)?;
259
                for desc in testdata_live::RELAY_DESCRIPTORS {
260
                    writeln!(input, "@ nick={}", desc.nick)?;
261
                    write!(input, "{}", desc.data.plain)?;
262
                }
263
                input.flush()?;
264
                Ok::<_, anyhow::Error>(())
265
            })()
266
            .context("write input")?;
267

            
268
            let nominal_time_arg = Iso8601TimeNoSp(nominal_time).to_string();
269
            test_invocation(chain!(
270
                ["compute-mds"],
271
                ["-t", &nominal_time_arg],
272
                ["-i", &input_empty_f],
273
                ["-i", &input_f],
274
                ["-i", &input_empty_f],
275
                ["--mds-out", &mds_f],
276
                ["--meta-out", &meta_f],
277
            ))?;
278

            
279
            let meta_made = fs::read_to_string(&meta_f)?;
280
            let mds_made = fs::read_to_string(&mds_f)?;
281

            
282
            eprintln!("@@ EMTA_OUT:\n{meta_made}");
283
            eprintln!("@@ MDS_OUT:\n{mds_made}");
284

            
285
            let mds = parse_netdoc_multiple_with_offsets::<Microdesc>(&ParseInput::new(
286
                &mds_made,
287
                "<out mds>",
288
            ))?;
289

            
290
            let md_hashes = mds
291
                .iter()
292
                .map(|&(_, start, end)| Sha256::digest(&mds_made[start..end]).into())
293
                .collect::<HashSet<[u8; 32]>>();
294

            
295
            let n_expected = testdata_live::RELAY_DESCRIPTORS.len();
296
            eprintln!("expecting at least {n_expected} mds");
297

            
298
            assert!(
299
                mds.len() >= n_expected,
300
                "{} is too few mds;\n{mds:?}",
301
                mds.len(),
302
            );
303

            
304
            let meta_made = meta_made.split_terminator('\n');
305

            
306
            for method in SupportedConsensusMethod::iter_all() {
307
                eprintln!("checking method {method}");
308

            
309
                let n_got = meta_made
310
                    .clone()
311
                    .filter(|l| {
312
                        // ad-hoc parsing, so we have an independent Cross-check
313

            
314
                        let mut l = l.split_ascii_whitespace();
315
                        let mut next = || l.next().unwrap();
316
                        macro_rules! next { {} => { next().parse().unwrap() } }
317

            
318
                        assert_eq!(next(), "m");
319

            
320
                        let m: ConsensusMethod = next!();
321
                        let m: SupportedConsensusMethod = m.try_into().unwrap();
322

            
323
                        let rsaid: Base64Fingerprint = next!();
324
                        let edid: B64 = next!();
325
                        let rd_hash: B64 = next!();
326
                        let md_hash: B64 = next!();
327

            
328
                        let rs_plain = consensus
329
                            .routers
330
                            .iter()
331
                            .find(|rs| rs.r.doc_digest[..] == **rd_hash)
332
                            .expect("missing doc digest");
333

            
334
                        let rs_md = relay_document_by_nick(
335
                            rs_plain.r.nickname.as_ref(),
336
                            &testdata_live::relay_microdescs(),
337
                        );
338

            
339
                        assert_eq!(rsaid, rs_plain.r.identity);
340
                        assert_eq!(*edid, rs_md.ed25519_id.pk.as_bytes());
341
                        assert!(md_hashes.contains(&**md_hash));
342

            
343
                        m == method
344
                    })
345
                    .count();
346
                assert!(n_got >= n_expected, "{} is too few", n_got);
347
            }
348

            
349
            Ok(())
350
        })
351
        .into_untracked()
352
    }
353
}