1
//! Directory Mirror Operation.
2
//!
3
//! # Specifications
4
//!
5
//! * [Directory cache operation](https://spec.torproject.org/dir-spec/directory-cache-operation.html).
6
//!
7
//! # Rationale
8
//!
9
//! This module implements the "core operation" of a directory mirror.
10
//! "Core operation" primarily refers to the logic involved in downloading
11
//! network documents from an upstream authority and inserting them into the
12
//! database.  This module notably **DOES NOT** provide any public (in the HTTP
13
//! sense) endpoints for querying documents.  This is purposely behind a different
14
//! module, so that the directory authority implementation can also make use of it.
15
//! You can think of this module as the one implementing the things unique
16
//! to directory mirrors.
17

            
18
use std::{
19
    collections::{HashMap, HashSet, VecDeque},
20
    fmt::Debug,
21
    hash::Hash,
22
    marker::PhantomData,
23
    mem,
24
    net::SocketAddr,
25
    time::Duration,
26
};
27

            
28
use educe::Educe;
29
use r2d2::Pool;
30
use r2d2_sqlite::SqliteConnectionManager;
31
use rand::Rng;
32
use rusqlite::Transaction;
33
use thiserror::Error;
34
use tokio::net::TcpStream;
35
use tokio_util::compat::TokioAsyncReadCompatExt;
36
use tor_checkable::TimeBound;
37
use tor_dirclient::{
38
    Error as DirClientError, RequestError, RequestFailedError,
39
    request::{
40
        AuthCertRequest, ConsensusRequest, MicrodescRequest, Requestable, RouterDescRequest,
41
    },
42
};
43
use tor_dircommon::{authority::AuthorityContacts, config::DirTolerance};
44
use tor_error::internal;
45
use tor_netdoc::{
46
    doc::{
47
        authcert::{AuthCert, AuthCertKeyIds, AuthCertUnverified},
48
        microdesc::Microdesc,
49
        netstatus::{ConsensusFlavor, ConsensusVerifiabilityError},
50
        routerdesc::RouterDescUnverified,
51
    },
52
    parse2::{
53
        self, NetdocParseable, NetdocParseableUnverified, ParseError, ParseInput, VerifyFailed,
54
    },
55
};
56
use tor_rtcompat::PreferredRuntime;
57
use tracing::{debug, warn};
58

            
59
use crate::{
60
    database::{
61
        self as db, AuthCertMeta, ConsensusMeta, ContentEncoding, DatabaseError, DescriptorMeta,
62
        Sha1, Sha256, Timestamp,
63
    },
64
    types::{
65
        FlavoredConsensusUnverified, FlavoredDescriptor, FlavoredDescriptorMd,
66
        FlavoredDescriptorPlain,
67
    },
68
};
69

            
70
/// The duration to try verifying an unverified consensus.
71
///
72
/// This exists primarily to properly handle the
73
/// [`ConsensusVerifiabilityError::InsufficientTrustedSigners`] error.  Besides,
74
/// it also serves as an upper-limit for the time we can spend in the phase for
75
/// fetching authority certificates, which could otherwise run for a very long
76
/// time, as long as every request makes progress and finishes before a
77
/// connection timeout is reached.
78
///
79
/// Obviously, we cannot use the values inside the consensus, as they are
80
/// untrusted.
81
const UNVERIFIED_TTL: Duration = Duration::from_mins(10);
82

            
83
/// Query a maximum.
84
const DESCRIPTOR_LIMIT: Option<u64> = Some(92);
85

            
86
/// The endpoint(s) of a download authority identifying it.
87
type DownloadAuthority = [SocketAddr];
88

            
89
/// An error while performing a request at a directory authority.
90
#[derive(Debug, Error)]
91
#[non_exhaustive]
92
pub(crate) enum AuthorityRequestError {
93
    /// TCP connection to the endpoint failed.
94
    #[error("tcp connection error: {0}")]
95
    TcpConnect(std::io::Error),
96

            
97
    /// [`tor_dirclient`] failed at performing the request.
98
    ///
99
    /// This usually indicates some failures in HTTP/1.0, such as the response
100
    /// not being valid HTTP/1.0; although Tor generally has some specialities
101
    /// here and there with regard to this, hence why we have dirclient in the
102
    /// first place.
103
    #[error("dirclient error: {0}")]
104
    Request(Box<tor_dirclient::RequestFailedError>),
105

            
106
    /// A response does not make semantic sense.
107
    ///
108
    /// This for example may include cases where we got more netdocs than we
109
    /// requested for.
110
    #[error("response error: {0}")]
111
    Response(&'static str),
112

            
113
    /// A request led to no progress being made.
114
    ///
115
    /// This is the case if the response only consists of netdocs we did not
116
    /// request or no netdocs at all, leading to no progress.
117
    ///
118
    /// The correct error handling strategy for this case is to pick a different
119
    /// endpoint, as the current one is either not useful for us anymore or
120
    /// is maliciously tricking us into something that should not happen.
121
    #[error("request resulted in no progress")]
122
    NoRequestedDocumentsReturned,
123

            
124
    /// An internal error.
125
    #[error("internal error")]
126
    Bug(#[from] tor_error::Bug),
127
}
128

            
129
impl From<tor_dirclient::RequestFailedError> for AuthorityRequestError {
130
    fn from(value: tor_dirclient::RequestFailedError) -> Self {
131
        Self::Request(Box::new(value))
132
    }
133
}
134

            
135
/// An error related to an operation in the dirmirror FSM.
136
//
137
// TODO: Rename this to MirrorOperationError.
138
#[derive(Debug, Error)]
139
#[non_exhaustive]
140
pub(crate) enum OperationError {
141
    /// Request to a directory authority failed.
142
    #[error("authority request error: {0}")]
143
    AuthorityRequest(#[from] AuthorityRequestError),
144

            
145
    /// Access to the database failed for good.
146
    #[error("database error: {0}")]
147
    Database(#[from] DatabaseError),
148

            
149
    /// Verificaton of a network document has failed.
150
    ///
151
    /// This also includes checks for timeliness.
152
    ///
153
    /// We do not consider this fatal but simply discard the unverified network
154
    /// document.
155
    #[error("verification error: {0}")]
156
    VerifyFailed(#[from] VerifyFailed),
157

            
158
    /// An internal error.
159
    #[error("Internal error")]
160
    Bug(#[from] tor_error::Bug),
161
}
162

            
163
/// The various states for the [`StaticEngine`].
164
// TODO 2881: Document the state transitions once the refactoring is done.
165
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display)]
166
enum State {
167
    /// Loads the most recent valid (and verified) consensus from the database
168
    /// into memory.
169
    LoadConsensus,
170

            
171
    /// Downloads the most recent consensus from a directory authority.
172
    // TODO DIRMIRROR: What to do in the case of getting an invalid consensus
173
    // such as junk data?  The normal retry logic sounds reasonable here.
174
    FetchConsensus,
175

            
176
    /// Downloads, validates, and stores the missing authority certificates from
177
    /// the downloaded unvalidated consensus into the database.
178
    AuthCerts,
179

            
180
    /// Validates and stores the downloaded unvalidated consensus into the
181
    /// database.
182
    StoreConsensus,
183

            
184
    /// Downloads missing network documents (descriptors) from a directory
185
    /// authority.
186
    Descriptors,
187

            
188
    /// Hibernate because nothing is left.
189
    Hibernate,
190
}
191

            
192
/// The execution engine for the finite state machine.
193
///
194
/// The states themselves are explained in [`State`].
195
///
196
/// This data structure itself is static and contains no state, but merely
197
/// configuration primitives that stay constant throughout the runtime of the
198
/// program, such as the [`AuthorityContacts`], and the
199
/// [`DirTolerance`].  It can be kept throughout the entire runtime and only
200
/// consists for convenience in order to not give each state machine related
201
/// (then static) method a super long signature containing these fields.
202
///
203
/// Besides these dynamic fields, there is also a generic parameter specifying
204
/// the consensus flavor that is being used.
205
///
206
/// The state itself is computed fully deterministically from the data found
207
/// within the database and [`ConsensusBoundData`].
208
///
209
/// This is the reason on why this structure is not called `StateMachine`,
210
/// because this implies that the type in itself carries state, which is not
211
/// true, because the state is stored entirely external, with this engine
212
/// only processing and modifying it.
213
///
214
/// See [`StaticEngine::determine_state()`] for more details.
215
#[derive(Debug)]
216
struct StaticEngine<T> {
217
    /// The authorities we are acknowledging.
218
    authorities: AuthorityContacts,
219

            
220
    /// The document tolerance we are accepting.
221
    tolerance: DirTolerance,
222

            
223
    /// The preferred runtime for compatibility with other arti crates.
224
    ///
225
    /// Generally obtained through [`PreferredRuntime::current()`].
226
    rt: PreferredRuntime,
227

            
228
    /// The content encodings we apply to documents.
229
    encodings: HashSet<ContentEncoding>,
230

            
231
    /// Utilizes the generic type parameter.
232
    _phantom: PhantomData<T>,
233
}
234

            
235
/// Additional state machine data concerning a single consensus.
236
///
237
/// This data type exists to store data that cannot be stored in the database,
238
/// including the consensus that is currently verified, the consensus that is
239
/// currently served, the timestamp until we will serve it, etc.
240
///
241
/// # Field Requirements
242
///
243
/// In order for a field to be contained here, at least one of the following
244
/// criteria should be met:
245
/// * The item needs to persist between multiple invocation and cannot be
246
///   obtained from the database.
247
/// * The item itself serves as an identifier to the database and querying it
248
///   it again can not be done in a pure fashion, e.g. a [`ConsensusMeta`]
249
///   identifier.
250
/// * The item exists purely for optimization purposes and can be thrown away
251
///   at any time without data loss, such as content-addressable caches.
252
///   These caches must be pure in the sense that a cache miss must always
253
///   return the same result as a cache hit and vice versa.
254
//
255
// TODO DIRMIRROR: This is probably better of as a struct instead of an enum.
256
#[derive(Debug, Clone)]
257
enum ConsensusBoundData<T: FlavoredConsensusUnverified> {
258
    /// No state is loaded in memory at the moment.
259
    None,
260

            
261
    /// We have downloaded a consensus but it is not yet verified.
262
    Unverified {
263
        /// The unverified parsed consensus we have.
264
        consensus: T,
265

            
266
        /// The unparsed raw consensus we have.
267
        raw: String,
268

            
269
        /// When to stop dealing with this consensus and download again.
270
        ///
271
        /// Useful to have in order to not stuck forever in a verification
272
        /// loop, i.e. due to unavailable authentication certificates, etc.
273
        ttl: Timestamp,
274
    },
275

            
276
    /// We have downloaded and verified a consensus.
277
    Verified {
278
        /// The verified consensus we have.
279
        ///
280
        /// Contained in this structure because it is the only way we can
281
        /// uniquely identify a consensus, which is crucial for operation, as
282
        /// things like the `ttl` are derived from it.
283
        ///
284
        /// While methods like [`ConsensusMeta::query`] would probably also
285
        /// work correctly, relying on them feels rather wrong, as they were
286
        /// not made to be pure.
287
        consensus: ConsensusMeta<T>,
288

            
289
        /// When to stop dealing with this consensus and fetching a new one.
290
        ttl: Timestamp,
291

            
292
        /// Descriptors we refuse to further download.
293
        ///
294
        /// Right now, this state gets cleaned, everytime we restart or obtain
295
        /// a new consensus.  This is probably okay, as we most likely do not
296
        /// want to store it on disk.
297
        futile: Box<FutileDescriptors>,
298
    },
299
}
300

            
301
impl<T: FlavoredConsensusUnverified> StaticEngine<T> {
302
    /// Determines the [`State`] only from the database and [`ConsensusBoundData`].
303
    ///
304
    /// This method is fully idempotent, meaning it only depends upon the data
305
    /// found within the database and the [`ConsensusBoundData`]; there is no
306
    /// internal `state` variable or something contained within [`StaticEngine`].
307
8
    fn determine_state(
308
8
        &self,
309
8
        tx: &Transaction<'_>,
310
8
        data: &ConsensusBoundData<T>,
311
8
        now: Timestamp,
312
8
    ) -> Result<State, DatabaseError> {
313
        // Determine the state primarily upon ConsensusBoundData combined with
314
        // a few database queries, as well as the current time of course.
315
8
        let state = match data {
316
            // ConsensusBoundData::None means that we currently have no
317
            // consensus in memory.  This may be the case because we just
318
            // started up or because we just downloaded, validated, and inserted
319
            // a consensus into the database and reset ConsensusBoundData to
320
            // None afterwards.
321
            ConsensusBoundData::None => {
322
                // Check whether there is a valid consensus in the database at all.
323
2
                match self.recent_consensus(tx, now)? {
324
                    // Some consensus means we can load it.
325
1
                    Some(_) => State::LoadConsensus,
326

            
327
                    // None means we must download it.
328
1
                    None => State::FetchConsensus,
329
                }
330
            }
331

            
332
            // ConsensusBoundData::Unverified means that we recently downloaded
333
            // a consensus through State::FetchConsensus.  It is not fully
334
            // validated yet and we may not even be able due to missing
335
            // authority certificates.
336
4
            ConsensusBoundData::Unverified { consensus, ttl, .. } if now < *ttl => {
337
4
                let certs_already = self.certs_already(tx, now)?;
338
4
                match consensus.can_verify(self.authorities.v3idents(), &certs_already) {
339
                    // We can verify and insert the consensus.
340
2
                    Ok(()) => State::StoreConsensus,
341

            
342
                    // We will never be able to verify the consensus, better
343
                    // times may come ...
344
                    Err(ConsensusVerifiabilityError::InsufficientTrustedSigners) => {
345
1
                        State::Hibernate
346
                    }
347

            
348
                    // We need to fetch more authority certificates from the
349
                    // network.
350
1
                    Err(ConsensusVerifiabilityError::MissingAuthCerts { .. }) => State::AuthCerts,
351
                }
352
            }
353

            
354
            ConsensusBoundData::Unverified { .. } => State::FetchConsensus,
355

            
356
            // ConsensusBoundData::Verified means that we have successfully
357
            // loaded a recent valid consensus from the database using
358
            // State::LoadConsensus.  Depending on this, we download the missing
359
            // network documents (descriptors) from a directory authority, if
360
            // any.
361
            ConsensusBoundData::Verified {
362
                consensus,
363
                ttl,
364
                futile,
365
            } => {
366
                // See if there are any missing descriptors that are not Refused
367
                // yet.  It is important to not exclude the NotFound descriptors
368
                // here because they may be available at a different authority.
369
                //
370
                // TODO DIRMIRROR: What to do in the case there is no authority
371
                // left in our list of endpoints?  Right now, this module of the
372
                // code is not aware of the endpoints to try and it is the
373
                // responsibility of the caller to check this.  Perhaps we
374
                // should provide a possibility to force hibernate, as in passing
375
                // an Option<DownloadAuthority> or an empty list.  An alternative
376
                // worth exploring might also be to perform the RetryDelay
377
                // wait logic, as in to not let the caller perform any timeouts
378
                // themselves.  Either way, we want to wait to hibernate and
379
                // wait for the next consensus in the case that no authority
380
                // is left.
381
                //
382
                // TODO DIRMIRROR: This appears to be prone to copy and paste
383
                // errors, we should do something about it, as in macros and/or
384
                // traits.
385
                let (missing_routers, missing_micros, missing_extras) = (
386
2
                    consensus.missing_routers(tx, futile.routers.refused(), Some(1))?,
387
2
                    consensus.missing_micros(tx, futile.micros.refused(), Some(1))?,
388
2
                    consensus.missing_extras(tx, futile.extras.refused(), Some(1))?,
389
                );
390

            
391
2
                if *ttl <= now {
392
                    // The ttl has been surpassed, download a new
393
                    // consensus.  It is very important TO NOT transition to
394
                    // State::LoadConsensus here, because the current consensus
395
                    // may still be valid but not fresh anymore, in which case
396
                    // State::LoadConsensus will continue to obtain it from the
397
                    // database until valid-after has been surpassed, which is
398
                    // most definitely not what we want.
399
                    State::FetchConsensus
400
2
                } else if missing_routers.is_empty()
401
1
                    && missing_micros.is_empty()
402
                    && missing_extras.is_empty()
403
                {
404
                    // All queues are empty, meaning we are done, until ttl
405
                    // ends.
406
                    State::Hibernate
407
                } else {
408
                    // The ttl has not been surpassed and we have stuff
409
                    // to download, so we need to obtain the descriptors.
410
2
                    State::Descriptors
411
                }
412
            }
413
        };
414
8
        Ok(state)
415
8
    }
416

            
417
    /// Executes a single state iteration in the finite state machine.
418
    // TODO 2881: Explain how this is called externally.
419
    // TODO: Use tracing instrumentation here.
420
    // TODO DIRMIRROR: Document the state transition check which we have to do
421
    // because of database invariances no longer holding true.
422
    async fn execute<R: Rng>(
423
        &self,
424
        pool: &Pool<SqliteConnectionManager>,
425
        data: &mut ConsensusBoundData<T>,
426
        endpoint: &DownloadAuthority,
427
        now: Timestamp,
428
        rng: &mut R,
429
    ) -> Result<(), OperationError> {
430
        // TODO DIRMIRROR: Right now, we pass around the pool object which is
431
        // not very nice.  Instead, we should match based on the following
432
        // criteria: Needs write transaction, needs read transaction, needs
433
        // pool, needs no database access.
434

            
435
        // TODO: Should we return DatabaseError or something like
436
        // StateDeterminationError?  Either way, both cases should be seriously
437
        // fatal.
438
        let state = db::read_tx(pool, |tx| self.determine_state(tx, data, now))??;
439
        debug!("state is {state}");
440

            
441
        match state {
442
            State::LoadConsensus => self.load_consensus(pool, data, now, rng),
443
            State::FetchConsensus => Ok(self.fetch_consensus(data, endpoint, now).await?),
444
            State::AuthCerts => self.auth_certs(pool, data, endpoint, now).await,
445
            State::StoreConsensus => self.store_consensus(pool, data, now),
446
            State::Descriptors => self.descriptors(pool, data, endpoint, now).await,
447
            State::Hibernate => self.hibernate(data, now).await,
448
        }
449
    }
450

            
451
    /// Executes [`State::LoadConsensus`].
452
    ///
453
    /// This method does the following:
454
    /// * Load the most recent valid consensus from the database.
455
    /// * Compute the ttl for it.
456
    /// * Compute the missing descriptors for it.
457
4
    fn load_consensus<R: Rng>(
458
4
        &self,
459
4
        pool: &Pool<SqliteConnectionManager>,
460
4
        data: &mut ConsensusBoundData<T>,
461
4
        now: Timestamp,
462
4
        rng: &mut R,
463
4
    ) -> Result<(), OperationError> {
464
        // Load the most recent valid consensus from the database.
465
        //
466
        // If there is no consensus, we should have not entered the state, which
467
        // means that the database must have been externally verified.
468
        // In this case, it is probably better to return a bug, as external
469
        // applications arbitrarily modifying the database while we are running
470
        // leaves too much room for wrong/weird behavior.
471
4
        let consensus = db::read_tx(pool, |tx| self.recent_consensus(tx, now))??
472
            .ok_or_else(|| internal!("database externally modified?"))?;
473
4
        let ttl = consensus.ttl(rng);
474
4
        let futile = Box::new(FutileDescriptors::default());
475

            
476
4
        *data = ConsensusBoundData::Verified {
477
4
            consensus,
478
4
            ttl,
479
4
            futile,
480
4
        };
481
4
        Ok(())
482
4
    }
483

            
484
    /// Fetches a consensus from an upstream authority.
485
    // TODO DIRMIRROR: Add logging.
486
    #[allow(clippy::string_slice)] // TODO
487
1
    async fn fetch_consensus(
488
1
        &self,
489
1
        data: &mut ConsensusBoundData<T>,
490
1
        endpoint: &DownloadAuthority,
491
1
        now: Timestamp,
492
1
    ) -> Result<(), AuthorityRequestError> {
493
        // Obtain the consensus.
494
1
        let (raw, consensus) = self
495
1
            .send_request(endpoint, ConsensusRequest::new(T::flavor()))
496
1
            .await?;
497
1
        let mut consensus = consensus.into_iter().collect::<VecDeque<_>>();
498

            
499
        // Check for the correct number of results.
500
1
        if consensus.len() != 1 {
501
            return Err(AuthorityRequestError::Response(
502
                "invalid number of consensus?",
503
            ));
504
1
        }
505
1
        let (consensus, start, end) = match consensus.pop_front().expect("pop failed?") {
506
1
            (Ok(consensus), start, end) => (consensus, start, end),
507
            // We do not mark unparseable consensuses as futile because they
508
            // cannot be referenced in a semi-unique fashion but rather depend
509
            // on the time only.
510
            //
511
            // TODO DIRMIRROR: Return a more descriptive error; ideally in
512
            // all places where only one document was returned and that document
513
            // failed to parse.
514
            (Err(_), _, _) => {
515
                return Err(AuthorityRequestError::Response(
516
                    "invalid consensus received",
517
                ));
518
            }
519
        };
520
1
        let raw = raw[start..end].to_string();
521

            
522
1
        let ttl = now + UNVERIFIED_TTL;
523

            
524
        // And store it.
525
1
        *data = ConsensusBoundData::Unverified {
526
1
            consensus,
527
1
            raw,
528
1
            ttl,
529
1
        };
530

            
531
1
        Ok(())
532
1
    }
533

            
534
    /// Fetches, validates, and stores authority certificates.
535
    #[allow(clippy::string_slice)] // TODO
536
1
    async fn auth_certs(
537
1
        &self,
538
1
        pool: &Pool<SqliteConnectionManager>,
539
1
        data: &mut ConsensusBoundData<T>,
540
1
        endpoint: &DownloadAuthority,
541
1
        now: Timestamp,
542
1
    ) -> Result<(), OperationError> {
543
1
        let certs_already = db::read_tx(pool, |tx| self.certs_already(tx, now))??;
544

            
545
        // Obtain the missing authority certificate identifiers.
546
1
        let missing = match data {
547
            ConsensusBoundData::Unverified { consensus, .. } => {
548
1
                match consensus.can_verify(self.authorities.v3idents(), &certs_already) {
549
1
                    Err(ConsensusVerifiabilityError::MissingAuthCerts { missing, .. }) => missing,
550
                    _ => return Err(OperationError::Bug(internal!("we have all auth certs"))),
551
                }
552
            }
553
            _ => return Err(OperationError::Bug(internal!("data is not unverified"))),
554
        };
555

            
556
        // Compose the request.
557
1
        let mut requ = AuthCertRequest::new();
558
1
        for kp in missing.iter().copied() {
559
4
            requ.push(kp);
560
        }
561

            
562
        // Fire it off.
563
1
        let (resp, certs) = self
564
1
            .send_request::<_, AuthCertUnverified>(endpoint, requ)
565
1
            .await?;
566

            
567
        // Verify each certificate.  Invalid certificates and other problems get
568
        // logged and filtered out, with the result being then inserted into
569
        // the database.
570
1
        let certs = certs
571
1
            .into_iter()
572
4
            .filter_map(|(unverified, start, end)| {
573
4
                let unverified = match unverified {
574
4
                    Ok(v) => v,
575
                    Err(e) => {
576
                        // We do not mark unparseable authority certificates as
577
                        // futile because they do not have an authoritative
578
                        // digest we could ad-hoc compare them against.
579
                        debug!("ignoring invalid authority certificate: {e}");
580
                        return None;
581
                    }
582
                };
583
4
                let kp = unverified.inspect_unverified().0.key_ids();
584

            
585
                // Skip certificates we did not asked for.
586
                //
587
                // Not much of an issue because certificate verification will
588
                // usually fail anyways, except for this weird edge-case where we
589
                // actually have that id fingerprint in the v3idents.
590
4
                if !missing.contains(&kp) {
591
                    debug!("authority returned certificate we did not asked for: {kp:?}");
592
                    return None;
593
4
                }
594

            
595
4
                let verified = match unverified.verify(self.authorities.v3idents()) {
596
4
                    Ok(c) => c,
597
                    Err(e) => {
598
                        debug!("received invalid auth cert ({kp:?}): {e}");
599
                        return None;
600
                    }
601
                };
602

            
603
4
                let timely = match self
604
4
                    .tolerance
605
4
                    .extend_tolerance(verified)
606
4
                    .if_valid_at(&now.into())
607
                {
608
4
                    Ok(c) => c,
609
                    Err(e) => {
610
                        debug!("received non-timely auth cert ({kp:?}): {e}");
611
                        return None;
612
                    }
613
                };
614

            
615
4
                Some((timely, &resp[start..end]))
616
4
            })
617
            .collect::<Vec<_>>();
618

            
619
        // When we have reached this, it means that this call made no progress,
620
        // i.e. the authority only returned certificates we were not interested
621
        // in.
622
1
        if certs.is_empty() {
623
            Err(AuthorityRequestError::NoRequestedDocumentsReturned)?;
624
1
        }
625

            
626
        // Finally, insert them all into the database.
627
1
        db::rw_tx(pool, |tx| {
628
1
            for (cert, data) in certs {
629
4
                AuthCertMeta::insert(tx, self.encodings.iter().copied(), &cert, data)?;
630
            }
631
1
            Ok::<_, DatabaseError>(())
632
1
        })??;
633

            
634
1
        Ok(())
635
1
    }
636

            
637
    /// Verifies a consensus and inserts it into the database.
638
1
    fn store_consensus(
639
1
        &self,
640
1
        pool: &Pool<SqliteConnectionManager>,
641
1
        data: &mut ConsensusBoundData<T>,
642
1
        now: Timestamp,
643
1
    ) -> Result<(), OperationError> {
644
        // It is fine to replace data with ConsensusBoundData::None because in
645
        // both cases, the following state of this will always be LoadConsensus
646
        // or FetchConsensus, both of them no longer requiring the previous data.
647
        //
648
        // Yes, we want to explicitly discard this in the case of a recoverable
649
        // error in order to retry again by fetching a new consensus from a
650
        // different authority.
651
1
        let (unverified, raw) = match mem::replace(data, ConsensusBoundData::None) {
652
1
            ConsensusBoundData::Unverified { consensus, raw, .. } => (consensus, raw),
653
            _ => return Err(OperationError::Bug(internal!("data is not unverified"))),
654
        };
655

            
656
        // TODO DIRMIRROR: Somewhere in here, we should generate the consensus
657
        // diffs.  However, this is a CPU intensive task and needs further
658
        // coordination with the orport developers.  See arti#2706
659

            
660
1
        db::rw_tx(pool, |tx| {
661
1
            let certs_already = self.certs_already(tx, now)?;
662
1
            let (verified, sigs) = self.verify_consensus(unverified, &certs_already, now)?;
663
1
            ConsensusMeta::<T>::insert(
664
1
                tx,
665
1
                self.encodings.iter().copied(),
666
1
                (&verified, &sigs),
667
1
                &raw,
668
1
            )?;
669
1
            Ok::<_, OperationError>(())
670
1
        })?
671
1
    }
672

            
673
    /// Downloads, verifies, and inserts the descriptors associated with the
674
    /// currently served consensus.
675
4
    async fn descriptors(
676
4
        &self,
677
4
        pool: &Pool<SqliteConnectionManager>,
678
4
        data: &mut ConsensusBoundData<T>,
679
4
        endpoint: &DownloadAuthority,
680
4
        now: Timestamp,
681
4
    ) -> Result<(), OperationError> {
682
4
        match T::flavor() {
683
            ConsensusFlavor::Plain => {
684
                // TODO DIRMIRROR: Add extras.
685
2
                self.descriptors_rd(pool, data, endpoint, now).await
686
            }
687
2
            ConsensusFlavor::Microdesc => self.descriptors_md(pool, data, endpoint, now).await,
688
        }
689
4
    }
690

            
691
    /// Router descriptor part of [`StaticEngine::descriptors()`].
692
2
    async fn descriptors_rd(
693
2
        &self,
694
2
        pool: &Pool<SqliteConnectionManager>,
695
2
        data: &mut ConsensusBoundData<T>,
696
2
        endpoint: &DownloadAuthority,
697
2
        now: Timestamp,
698
2
    ) -> Result<(), OperationError> {
699
2
        debug_assert_eq!(T::flavor(), ConsensusFlavor::Plain);
700
2
        self.descriptors_agnostic::<RdDownloader>(pool, data, endpoint, now)
701
2
            .await
702
2
    }
703

            
704
    /// Micro descriptor part of [`StaticEngine::descriptors()`].
705
2
    async fn descriptors_md(
706
2
        &self,
707
2
        pool: &Pool<SqliteConnectionManager>,
708
2
        data: &mut ConsensusBoundData<T>,
709
2
        endpoint: &DownloadAuthority,
710
2
        now: Timestamp,
711
2
    ) -> Result<(), OperationError> {
712
2
        debug_assert_eq!(T::flavor(), ConsensusFlavor::Microdesc);
713
2
        self.descriptors_agnostic::<MdDownloader>(pool, data, endpoint, now)
714
2
            .await
715
2
    }
716

            
717
    /// Descriptor flavor agnostic engine driving the download, verification,
718
    /// and insertion of descriptors using [`DescriptorDownloader`].
719
4
    async fn descriptors_agnostic<D: DescriptorDownloader<T>>(
720
4
        &self,
721
4
        pool: &Pool<SqliteConnectionManager>,
722
4
        data: &mut ConsensusBoundData<T>,
723
4
        endpoint: &DownloadAuthority,
724
4
        now: Timestamp,
725
4
    ) -> Result<(), OperationError> {
726
4
        let (meta, futile) = match data {
727
            ConsensusBoundData::Verified {
728
                consensus, futile, ..
729
4
            } => (consensus, futile),
730
            _ => return Err(OperationError::Bug(internal!("data not verified"))),
731
        };
732

            
733
        // Obtain the missing descriptors.
734
4
        let descriptors = db::read_tx(pool, |tx| D::query(tx, meta, futile, endpoint))??;
735
4
        if descriptors.is_empty() {
736
            // This is equivalent to sending off an empty request and failing
737
            // afterwards because no progress was made, but it saves us
738
            // bandwidth by not doing a redundant HTTP request.  We may enter
739
            // this branch if there are no descriptors left that are not marked
740
            // as not found or refused, in which case we must try the next
741
            // authority as it may have the not found descriptors.
742
            debug!("not downloading any descriptors");
743
            Err(OperationError::AuthorityRequest(
744
                AuthorityRequestError::NoRequestedDocumentsReturned,
745
            ))?;
746
4
        }
747

            
748
4
        debug!("downloading the following descriptors: {descriptors:?}");
749
4
        let requ = D::make_request(&descriptors);
750
4
        let (raw, docs) = self.send_request::<_, D::Response>(endpoint, requ).await?;
751

            
752
        // Verify each descriptor.
753
        // Process all downloads isolated, so that we do not return early
754
        // on accident.  While we still have one minor exception below with
755
        // regard to DatabaseError, that one is well documented.
756
4
        let downloads = DescriptorDownloads::from_missing(descriptors.into_iter());
757
4
        let downloads = D::process_downloads(self, downloads, docs, raw, now);
758

            
759
        // Determine if we made progress by checking whether we have any
760
        // descriptors that are either found or refused.  If this is the case,
761
        // we will return later, once the descriptors are marked as such.
762
4
        let progress = downloads
763
4
            .values()
764
23
            .find(|x| !matches!(x, DescriptorDownloadResult::NotFound))
765
            .map(|_| ()); // Do not borrow.
766

            
767
        // Insert the obtained descriptors in one large bulk transaction or
768
        // mark them as futile.
769
        //
770
        // It is okay if we fail before setting the descriptors as futile here,
771
        // because database failures are pretty much irrecoverable anyways.
772
        // Doing this together in the same loop saves us from having to
773
        // filter and split the large HashMap into multiple ones.  It should be
774
        // secure because the inner closure has the return error type of
775
        // DatabaseError, meaning only these fatal errors can return early.
776
4
        db::rw_tx(pool, |tx| D::insert(self, tx, futile, downloads, endpoint))??;
777

            
778
        // If no progress, return with an error.  We can do so here because
779
        // we have finally marked descriptors as futile.
780
4
        if progress.is_none() {
781
1
            Err(OperationError::AuthorityRequest(
782
1
                AuthorityRequestError::NoRequestedDocumentsReturned,
783
1
            ))?;
784
3
        }
785

            
786
3
        Ok(())
787
4
    }
788

            
789
    /// Hibernates for the remaining ttl of the consensus.
790
    async fn hibernate(
791
        &self,
792
        data: &mut ConsensusBoundData<T>,
793
        now: Timestamp,
794
    ) -> Result<(), OperationError> {
795
        match data {
796
            ConsensusBoundData::None => {
797
                return Err(internal!("hibernating without a consensus?").into());
798
            }
799
            // TODO DIRMIRROR: Should the Unverified case be an error or a
800
            // success? In other words: Should we exclude the current authority
801
            // from the set of the next authorities to try?
802
            ConsensusBoundData::Verified { ttl, .. }
803
            | ConsensusBoundData::Unverified { ttl, .. } => {
804
                let timeout = *ttl - now;
805
                debug!("hibernating for {}s", timeout.as_secs());
806
                tokio::time::sleep(timeout).await;
807
            }
808
        }
809

            
810
        Ok(())
811
    }
812

            
813
    /// Convenience wrapper around [`tor_dirclient::send_request()`].
814
    ///
815
    /// It opens a TCP connection, performs the request, and parses the result.
816
    ///
817
    /// Returns the raw response alongside the output of
818
    /// [`parse2::parse_netdoc_multiple_sophisticated()`].
819
    ///
820
    /// An important distinction towards [`tor_dirclient::send_request()`] is,
821
    /// that we do not consider an empty response or a 404 response as an error.
822
    /// Instead, we just return [`Ok`] with an empty [`String`] and an empty
823
    /// [`Vec`] instead.  The reason for this is, that the futile document
824
    /// strategy (i.e. determing which documents of the request are missing)
825
    /// should be the same for responses containing zero (requested) documents
826
    /// and responses containing at least one but less than the number of
827
    /// the originally requested documents.
828
    ///
829
    /// The output is required because we need the raw document alongside the
830
    /// offsets to have the actual data we will insert into the database later
831
    /// on.
832
6
    async fn send_request<R: Requestable, D: NetdocParseable>(
833
6
        &self,
834
6
        endpoint: &DownloadAuthority,
835
6
        requ: R,
836
6
    ) -> Result<(String, Vec<(Result<D, ParseError>, usize, usize)>), AuthorityRequestError> {
837
        // The check is required to not let Tokio panic.
838
6
        if endpoint.is_empty() {
839
            return Err(AuthorityRequestError::Bug(internal!("empty endpoint?")));
840
6
        }
841

            
842
        // Open the TCP connection.
843
6
        let mut stream = TcpStream::connect(endpoint)
844
6
            .await
845
6
            .map_err(AuthorityRequestError::TcpConnect)?
846
            .compat();
847

            
848
        // Perform the request and map the result nicely.
849
6
        let resp = tor_dirclient::send_request(&self.rt, &requ, &mut stream, None)
850
6
            .await
851
6
            .map(|resp| {
852
6
                resp.output_string()
853
6
                    .map(|resp| resp.to_owned())
854
                    // Allows us to flatten the result.
855
6
                    .map_err(tor_dirclient::Error::from)
856
6
            });
857

            
858
        // We can immediately drop the connection now, no need to occupy even
859
        // more resources from the authority.  Doing so is fine, it is HTTP/1.0
860
        // and there is no connection reuse anyways.
861
6
        drop(stream);
862

            
863
        // Non-trivial error handling strategy explained in the rustdoc comment
864
        // above.
865
6
        let resp = match resp.flatten() {
866
6
            Ok(resp) => Ok(resp),
867

            
868
            // This error might actually be Ok in certain cases.
869
            Err(DirClientError::RequestFailed(
870
                ref outer @ RequestFailedError {
871
                    error: ref inner, ..
872
                },
873
            )) => match inner {
874
                // If one of these errors occurs, do not fail but rather return
875
                // no documents.
876
                RequestError::EmptyRequest => {
877
                    warn!("we should not send an empty request");
878
                    return Ok(Default::default());
879
                }
880
                RequestError::EmptyResponse | RequestError::HttpStatus(404, _) => {
881
                    return Ok(Default::default());
882
                }
883

            
884
                // All other errors imply an underlying error with the
885
                // respective endpoint, suggesting a switch.
886
                _ => Err(outer.clone().into()),
887
            },
888

            
889
            // Should not happen because the other DirClientErrors are either
890
            // Bug or related to CircMgr, which we do not use.
891
            Err(e) => Err(AuthorityRequestError::Bug(internal!(
892
                "unhandled dirclient error: {e}"
893
            ))),
894
        }?;
895

            
896
        // Parse the response.
897
6
        let parsed = parse2::parse_netdoc_multiple_sophisticated(&ParseInput::new(&resp, ""))?;
898

            
899
6
        Ok((resp, parsed))
900
6
    }
901

            
902
    /// Queries and validates the most recent consensus from the database.
903
    ///
904
    /// Effectively a wrapper around [`StaticEngine::verify_consensus()`] with
905
    /// the data obtained from the database.
906
6
    fn recent_consensus(
907
6
        &self,
908
6
        tx: &Transaction<'_>,
909
6
        now: Timestamp,
910
6
    ) -> Result<Option<ConsensusMeta<T>>, DatabaseError> {
911
6
        let meta = match ConsensusMeta::<T>::query(tx)?.as_slice() {
912
6
            &[front] | &[front, ..] => front,
913
            &[] => return Ok(None),
914
        };
915
6
        let raw = meta.data(tx)?;
916

            
917
6
        let unverified = match parse2::parse_netdoc::<T>(&ParseInput::new(&raw, "<database>")) {
918
6
            Ok(unverified) => unverified,
919
            Err(e) => {
920
                // TODO DIRMIRROR: Perhaps we should remove it?
921
                debug!("unparseable consensus in database: {meta:?} {e}");
922
                return Ok(None);
923
            }
924
        };
925

            
926
6
        let certs_already = self.certs_already(tx, now)?;
927

            
928
6
        match self.verify_consensus(unverified, &certs_already, now) {
929
5
            Ok(_) => Ok(Some(meta)),
930
            Err(e) => {
931
                // TODO DIRMIRROR: Perhaps we should remove it?
932
1
                debug!("ignoring invalid consensus in database: {meta:?} {e}");
933
1
                Ok(None)
934
            }
935
        }
936
6
    }
937

            
938
    /// Parses and verifies a raw consensus in a database agnostic fashion.
939
7
    fn verify_consensus(
940
7
        &self,
941
7
        unverified: T,
942
7
        certs_already: &[AuthCert],
943
7
        now: Timestamp,
944
7
    ) -> Result<(T::Body, T::Signatures), VerifyFailed> {
945
7
        let sigs = unverified.sigs().clone();
946

            
947
7
        let verified = unverified.verify(self.authorities.v3idents(), certs_already)?;
948

            
949
6
        self.tolerance
950
6
            .extend_tolerance(verified)
951
6
            .if_valid_at(&now.into())
952
6
            .map(|body| (body, sigs))
953
            .map_err(|e| e.into())
954
7
    }
955

            
956
    /// Loads all authority certificates from the database into a [`Vec<AuthCert>`].
957
    ///
958
    /// Performance wise, it is quite inefficient as it parses and verifies all
959
    /// certificates over again.  However, this should be fine as the N for
960
    /// directory authorities is usually very small.
961
15
    fn certs_already(
962
15
        &self,
963
15
        tx: &Transaction<'_>,
964
15
        now: Timestamp,
965
15
    ) -> Result<Vec<AuthCert>, DatabaseError> {
966
15
        let raw_certs = AuthCertMeta::query(tx)?
967
            .into_iter()
968
52
            .map(|meta| Ok::<_, DatabaseError>((meta, meta.data(tx)?)))
969
            .collect::<Result<Vec<_>, _>>()?;
970

            
971
15
        let mut certs_already = Vec::new();
972
15
        for (meta, raw) in raw_certs {
973
            // Only used for debugging.
974
            // TODO DIRMIRROR: Put this into span with tracing.
975
52
            let key_ids = AuthCertKeyIds {
976
52
                id_fingerprint: meta.kp_auth_id_rsa_sha1.0.into(),
977
52
                sk_fingerprint: meta.kp_auth_sign_rsa_sha1.0.into(),
978
52
            };
979

            
980
52
            let unverified = match parse2::parse_netdoc::<AuthCertUnverified>(&ParseInput::new(
981
52
                &raw,
982
52
                "<database>",
983
52
            )) {
984
52
                Ok(c) => c,
985
                Err(e) => {
986
                    // TODO DIRMIRROR: Perhaps we should remove it?
987
                    debug!("unparseable auth cert ({key_ids:?}) in database: {e}");
988
                    continue;
989
                }
990
            };
991

            
992
52
            let verified = match unverified.verify(self.authorities.v3idents()) {
993
48
                Ok(c) => c,
994
                Err(e) => {
995
4
                    debug!("ignoring invalid auth cert ({key_ids:?}): {e}");
996
4
                    continue;
997
                }
998
            };
999

            
48
            let timely = match self
48
                .tolerance
48
                .extend_tolerance(verified)
48
                .if_valid_at(&now.into())
            {
40
                Ok(c) => c,
                Err(e) => {
8
                    debug!("ignoring non-timely auth cert ({key_ids:?}): {e}");
8
                    continue;
                }
            };
40
            certs_already.push(timely);
        }
15
        Ok(certs_already)
15
    }
}
/// Helper trait for reducing the copy and paste we have to do in the
/// [`StaticEngine::descriptors`] method, as parts of the logic overlap a lot
/// between router and micro descriptors.
trait DescriptorDownloader<T: FlavoredConsensusUnverified> {
    /// The document digest by which we query the respective descriptors.
    type DocDigest: Debug + Hash + Eq + Clone + Copy;
    /// The actual descriptor type we are working with.
    type Descriptor: FlavoredDescriptor;
    /// The [`tor_dirclient`] request data type we are emitting.
    type Request: Requestable;
    /// The response data type we expect from the dirserver we are contacting.
    type Response: NetdocParseable;
    /// Queries the database for the missing descriptor document digests
    /// contained within a [`HashSet`].
    ///
    /// This is usually just a wrapper around [`ConsensusMeta::missing_routers()`]
    /// and similar methods.
    fn query(
        tx: &Transaction<'_>,
        meta: &ConsensusMeta<T>,
        futile: &FutileDescriptors,
        endpoint: &DownloadAuthority,
    ) -> Result<HashSet<Self::DocDigest>, DatabaseError>;
    /// Creates a [`Requestable`] from the missing descriptors returned through
    /// [`Self::query()`].
    fn make_request(digests: &HashSet<Self::DocDigest>) -> Self::Request;
    /// Processes the response after it has been received.
    ///
    /// It's inputs are a [`DescriptorDownloads`] that contains all the
    /// requested digests set to [`DescriptorDownloadResult::NotFound`].
    ///
    /// The purpose of this function is to populate this struct accordingly and
    /// return it in the end.  The function itself must not fail, hence why
    /// it does not return a Result.
    fn process_downloads(
        engine: &StaticEngine<T>,
        downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
        docs: Vec<(Result<Self::Response, ParseError>, usize, usize)>,
        raw: String,
        now: Timestamp,
    ) -> DescriptorDownloads<Self::DocDigest, Self::Descriptor>;
    /// Finally, insert all descriptors either into the database or populate
    /// [`FutileDescriptors`] accordingly.  This function may still leave the
    /// [`FutileDescriptors`] in an inconsistent state, but only in the case
    /// of an irrecoverable [`DatabaseError`], which is ok.
    fn insert(
        engine: &StaticEngine<T>,
        tx: &Transaction<'_>,
        futile: &mut FutileDescriptors,
        downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
        endpoint: &DownloadAuthority,
    ) -> Result<(), DatabaseError>;
}
/// Common implementation of [`DescriptorDownloader::insert()`].
///
/// Signature is almost identical to the respective origianl one, except that it
/// additionally accepts a function item that returns the respective
/// [`FutileDescriptorSet`] item out of [`FutileDescriptors`]; this is to avoid
/// duplication.
// TODO: Once we have extra-info support, consider moving this implementation
// into the trait method.
4
fn downloader_common_insert<T: FlavoredConsensusUnverified, D: DescriptorDownloader<T>>(
4
    engine: &StaticEngine<T>,
4
    tx: &Transaction<'_>,
4
    futile: &mut FutileDescriptors,
4
    downloads: DescriptorDownloads<D::DocDigest, D::Descriptor>,
4
    endpoint: &DownloadAuthority,
4
    get_futile: fn(&mut FutileDescriptors) -> &mut FutileDescriptorSet<D::DocDigest>,
4
) -> Result<(), DatabaseError> {
4
    for (digest, res) in downloads.into_iter() {
52
        match res {
            DescriptorDownloadResult::NotFound => {
25
                get_futile(futile).set_not_found(digest, endpoint);
            }
            DescriptorDownloadResult::Refused => get_futile(futile).set_refused(digest),
            DescriptorDownloadResult::Found(descriptor, raw) => {
27
                DescriptorMeta::insert(tx, engine.encodings.iter().copied(), &descriptor, &raw)?;
            }
        }
    }
4
    Ok(())
4
}
/// Unit type implementing [`DescriptorDownloader`] for router descriptors.
struct RdDownloader;
impl<T: FlavoredConsensusUnverified> DescriptorDownloader<T> for RdDownloader {
    type DocDigest = Sha1;
    type Descriptor = FlavoredDescriptorPlain;
    type Request = RouterDescRequest;
    type Response = RouterDescUnverified;
4
    fn query(
4
        tx: &Transaction<'_>,
4
        meta: &ConsensusMeta<T>,
4
        futile: &FutileDescriptors,
4
        endpoint: &DownloadAuthority,
4
    ) -> Result<HashSet<Self::DocDigest>, DatabaseError> {
4
        meta.missing_routers(tx, futile.routers.excluded(endpoint), DESCRIPTOR_LIMIT)
4
    }
2
    fn make_request(digests: &HashSet<Self::DocDigest>) -> Self::Request {
26
        RouterDescRequest::from_iter(digests.iter().map(|sha1| sha1.0))
2
    }
2
    fn process_downloads(
2
        engine: &StaticEngine<T>,
2
        mut downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
2
        docs: Vec<(Result<Self::Response, ParseError>, usize, usize)>,
2
        raw: String,
2
        now: Timestamp,
2
    ) -> DescriptorDownloads<Self::DocDigest, Self::Descriptor> {
2
        for (unverified, start, end) in docs {
25
            let Ok(unverified) = unverified else {
                // TODO DIRMIRROR: Handle parser failures as potentially futile.
                //
                // This is going to be a big can of worms, because in the case
                // of a parser failure, we must check whether the part between
                // "router" and "router-signature" matches the digest of a
                // requested descriptor, while checking that the body and
                // signature parts of the document alone parse just fine.
                //
                // body_ok && signature_ok => the parser has not failed, unreachable
                // body_ok && !signature_ok => not futile
                // !body_ok && signature_ok => futile
                // !body_ok && !signature_ok => futile
                //
                // (with ok meaning that the parser suceeded, no statement
                // of cryptographic validity is being made here)
                //
                // The `RoutereDescUnverifiedParsedBody as NetdocParseable`
                // pattern may be useful for this check.
                continue;
            };
            // Defensive internal checks.
25
            let Some(raw) = raw.get(start..end) else {
                warn!("parse2 returned invalid string slice: {start}..{end}");
                continue;
            };
25
            let raw = raw.to_string();
25
            let Some(sha1) = unverified.sigs.hashes.sha1 else {
                warn!("accumulator contains no SHA-1?");
                continue;
            };
25
            let sha1 = Sha1(sha1);
            // Checks whether the response is weird, as in containing
            // unrequested or duplicate descriptors.
25
            match downloads.get(&sha1) {
13
                Some(DescriptorDownloadResult::NotFound) => {}
                Some(DescriptorDownloadResult::Found(_, _) | DescriptorDownloadResult::Refused) => {
                    debug!("{sha1:?} contained multiple times in response");
                    continue;
                }
                None => {
12
                    debug!("ignoring unrequested router descriptor: {sha1:?}");
12
                    continue;
                }
            };
            // Perform the relevant cryptographic checks.
13
            let sigs = unverified.sigs.clone();
13
            let verified = match unverified.verify() {
13
                Ok(verified) => verified,
                Err(e) => {
                    // Continuing here implicitly marks the descriptor as not
                    // found after the loop ends.
                    debug!("ignoring invalid router descriptor: {sha1:?}: {e}");
                    continue;
                }
            };
13
            let timely = match engine
13
                .tolerance
13
                .extend_tolerance(verified)
13
                .if_valid_at(&now.into())
            {
13
                Ok(timely) => timely,
                Err(e) => {
                    // Untimely is considered as refused for the lifespan of the
                    // current consensus.
                    debug!("ignoring untimely router descriptor: {sha1:?}: {e}");
                    let prev = downloads.insert(sha1, DescriptorDownloadResult::Refused);
                    debug_assert!(matches!(prev, Some(DescriptorDownloadResult::NotFound)));
                    continue;
                }
            };
13
            let prev = downloads.insert(sha1, DescriptorDownloadResult::Found((timely, sigs), raw));
13
            debug_assert!(matches!(prev, Some(DescriptorDownloadResult::NotFound)));
        }
2
        downloads
2
    }
2
    fn insert(
2
        engine: &StaticEngine<T>,
2
        tx: &Transaction<'_>,
2
        futile: &mut FutileDescriptors,
2
        downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
2
        endpoint: &DownloadAuthority,
2
    ) -> Result<(), DatabaseError> {
2
        downloader_common_insert::<T, RdDownloader>(
2
            engine,
2
            tx,
2
            futile,
2
            downloads,
2
            endpoint,
13
            |futile| &mut futile.routers,
        )
2
    }
}
/// Unit type implementing [`DescriptorDownloader`] for micro descriptors.
struct MdDownloader;
impl<T: FlavoredConsensusUnverified> DescriptorDownloader<T> for MdDownloader {
    type DocDigest = Sha256;
    type Descriptor = FlavoredDescriptorMd;
    type Request = MicrodescRequest;
    type Response = Microdesc;
4
    fn query(
4
        tx: &Transaction<'_>,
4
        meta: &ConsensusMeta<T>,
4
        futile: &FutileDescriptors,
4
        endpoint: &DownloadAuthority,
4
    ) -> Result<HashSet<Self::DocDigest>, DatabaseError> {
4
        meta.missing_micros(tx, futile.micros.excluded(endpoint), DESCRIPTOR_LIMIT)
4
    }
2
    fn make_request(digests: &HashSet<Self::DocDigest>) -> Self::Request {
26
        MicrodescRequest::from_iter(digests.iter().map(|sha256| sha256.0))
2
    }
2
    fn process_downloads(
2
        _engine: &StaticEngine<T>,
2
        mut downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
2
        docs: Vec<(Result<Self::Response, ParseError>, usize, usize)>,
2
        raw: String,
2
        _now: Timestamp,
2
    ) -> DescriptorDownloads<Self::DocDigest, Self::Descriptor> {
2
        for (md, start, end) in docs {
            // Defensive internal check.
40
            let Some(raw) = raw.get(start..end) else {
                warn!("parse2 returned invalid string slice: {start}..{end}");
                continue;
            };
40
            let raw = raw.to_string();
            // Calculate the SHA-256 over the entire document; we can do this
            // before accessing the parsed result.
40
            let sha256 = Sha256::digest(raw.as_bytes());
40
            match downloads.get(&sha256) {
14
                Some(DescriptorDownloadResult::NotFound) => {}
                Some(DescriptorDownloadResult::Found(_, _) | DescriptorDownloadResult::Refused) => {
                    debug!("{sha256:?} contained multiple times in response");
                    continue;
                }
                None => {
26
                    debug!("ignoring unrequested micro descriptor: {sha256:?}");
26
                    continue;
                }
            }
            // Check whether the parsing was successful in the first place.
            // If not, we mark the descriptor as refused, because we have
            // implicitly verified it's cryptographic integrity above through
            // the digest.
14
            let Ok(md) = md else {
                let prev = downloads.insert(sha256, DescriptorDownloadResult::Refused);
                debug_assert!(matches!(prev, Some(DescriptorDownloadResult::NotFound)));
                continue;
            };
14
            let sha1 = Sha1::digest(raw.as_bytes());
14
            let prev = downloads.insert(
14
                sha256,
14
                DescriptorDownloadResult::Found((md, sha1, sha256), raw),
14
            );
14
            debug_assert!(matches!(prev, Some(DescriptorDownloadResult::NotFound)));
        }
2
        downloads
2
    }
2
    fn insert(
2
        engine: &StaticEngine<T>,
2
        tx: &Transaction<'_>,
2
        futile: &mut FutileDescriptors,
2
        downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
2
        endpoint: &DownloadAuthority,
2
    ) -> Result<(), DatabaseError> {
2
        downloader_common_insert::<T, MdDownloader>(
2
            engine,
2
            tx,
2
            futile,
2
            downloads,
2
            endpoint,
12
            |futile| &mut futile.micros,
        )
2
    }
}
/// Records which allow us to avoid futile download attempts
///
/// One set of records of "futile" documents, for each kind of document.
#[derive(Debug, Clone, Default)]
struct FutileDescriptors {
    /// The futile router descriptors.
    routers: FutileDescriptorSet<Sha1>,
    /// The futile extra-infos.
    extras: FutileDescriptorSet<Sha1>,
    /// The futile micro descriptors.
    micros: FutileDescriptorSet<Sha256>,
}
/// A generic struct storing which document are futile for which reason.
///
/// A document is "futile" if there is no point retrying its download.
/// More precisely,
///
///   * We note which authorities didn't have a document when we tried to download it.
///     This avoids us trying that same document again, uselessly.
// TODO DIRMIRROR but what if the authority acquires the document in the meantime?
//
///   * We note the hashes of documents we couldn't parse.
///     If the hash matched, but the parse failed, there is no point trying to get
///     this document at all because the same hash means the same document
///     and therefore the same parse error.
// TODO: Right now, we allow a value to be present in both: not_found and refused.
// Do we want to allow this or should we potentially change the representation
// similar to the way we are doing it in DescriptorDownloadResult?  Not blocking,
// as a hazard here is not the end of the world, but solving it may be more
// elegant.
#[derive(Educe)]
// bound(false) works around an infelicity in educe, https://github.com/magiclen/educe/issues/55
#[educe(Debug(bound(false)), Clone, Default)]
struct FutileDescriptorSet<T: Debug + Copy + Eq + Hash> {
    /// The descriptors that are not found on a given endpoint.
    not_found: HashSet<(T, Box<DownloadAuthority>)>,
    /// The descriptor that are outright refused.
    refused: HashSet<T>,
}
impl<T: Debug + Clone + Copy + Eq + Hash> FutileDescriptorSet<T> {
    /// Returns an iterator over the digest that are not found.
8
    fn not_found(&self, endpoint: &DownloadAuthority) -> impl Iterator<Item = T> {
8
        self.not_found
8
            .iter()
            .filter(|(_, this_endpoint)| **this_endpoint == *endpoint)
            .map(|(d, _)| *d)
8
    }
    /// Returns an iterator over the digest that are refused.
14
    fn refused(&self) -> impl Iterator<Item = T> {
14
        self.refused.iter().copied()
14
    }
    /// Chaining of `.not_found()` and `.refused()`.
8
    fn excluded(&self, endpoint: &DownloadAuthority) -> impl Iterator<Item = T> {
8
        self.not_found(endpoint).chain(self.refused())
8
    }
    /// Marks a digest in combination with an authority as not found.
25
    fn set_not_found(&mut self, digest: T, endpoint: &DownloadAuthority) {
25
        self.not_found.insert((digest, endpoint.into()));
25
    }
    /// Marks a digest as refused.
    fn set_refused(&mut self, digest: T) {
        self.refused.insert(digest);
    }
}
/// Intermediate data structure for storing the result of a downloaded
/// descriptor within a batch of downloads.
///
/// Populated before the insertion into [`FutileDescriptors`] takes place,
/// so that the actual population of [`FutileDescriptors`] remains atomic.
#[derive(Debug, Clone)]
enum DescriptorDownloadResult<D: FlavoredDescriptor> {
    /// The descriptor was found and verified.
    Found(D, String),
    /// The descriptor was not found; implicit default.
    NotFound,
    /// We do not accept this descriptor.
    Refused,
}
/// Collection of [`DescriptorDownloadResult`] values indexed by their digest.
///
/// Used during downloading a batch in order to atomically update
/// [`FutileDescriptors`].
#[derive(Debug, Clone, derive_more::Deref, derive_more::DerefMut, derive_more::IntoIterator)]
struct DescriptorDownloads<K, D: FlavoredDescriptor>(HashMap<K, DescriptorDownloadResult<D>>);
impl<K: Eq + Hash, D: FlavoredDescriptor> DescriptorDownloads<K, D> {
    /// Creates a [`DescriptorDownloads`] from a set of all missing descriptors.
    ///
    /// The idea is to call this right after the database call and before
    /// any downloads are actually being made, as it initializes the data
    /// structure with all the keys to [`DescriptorDownloadResult::NotFound`].
4
    fn from_missing(digests: impl Iterator<Item = K>) -> Self {
        Self(
4
            digests
52
                .map(|digest| (digest, DescriptorDownloadResult::NotFound))
                .collect(),
        )
4
    }
}
#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    #![allow(clippy::string_slice)] // See arti#2571
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
    use std::{collections::HashSet, iter};
    use rusqlite::params;
    use strum::IntoEnumIterator;
    use tokio::{
        io::{AsyncReadExt, AsyncWriteExt},
        net::TcpListener,
    };
    use tor_basic_utils::test_rng::testing_rng;
    use crate::{database::sql, testdata2};
    use super::*;
    type Plain = tor_netdoc::doc::netstatus::plain::NetworkStatusUnverified;
    type Md = tor_netdoc::doc::netstatus::md::NetworkStatusUnverified;
    /// Returns a [`StaticEngine`] for testing.
    fn static_engine<T>() -> StaticEngine<T> {
        StaticEngine {
            authorities: testdata2::current_auth_cert_contacts(),
            tolerance: DirTolerance::default(),
            rt: PreferredRuntime::current().unwrap(),
            encodings: ContentEncoding::iter().collect(),
            _phantom: Default::default(),
        }
    }
    /// Tests whether the load consensus state computes missing descriptors
    /// properly.
    ///
    /// For this, the test removes a present router descriptor from the storage
    /// to verify that it is detected as missing and added to the download
    /// queue.
    #[tokio::test]
    async fn state_load_consensus() {
        let pool = testdata2::test_db();
        let mut data = ConsensusBoundData::<Plain>::None;
        let engine = static_engine();
        let time: Timestamp = testdata2::valid_system_time().into();
        let fresh_until: Timestamp = testdata2::current_consensus_ns()
            .0
            .preamble
            .lifetime
            .fresh_until
            .0
            .into();
        let valid_until: Timestamp = testdata2::current_consensus_ns()
            .0
            .preamble
            .lifetime
            .valid_until
            .0
            .into();
        // This is the middle of valid_until and fresh_until.
        let fresh_until_half = fresh_until + ((valid_until - fresh_until) / 2);
        // Remove a single router descriptor from our storage to see whether it
        // appears in the download queue as expected.
        let relay_to_remove = &testdata2::current_consensus_ns().0.routers[0];
        let relay_to_remove = db::Sha1::from(*relay_to_remove.doc_digest());
        pool.get()
            .unwrap()
            .execute(
                sql!("DELETE FROM descriptor WHERE sha1 = ?1"),
                params![relay_to_remove],
            )
            .unwrap();
        engine
            .load_consensus(&pool, &mut data, time, &mut testing_rng())
            .unwrap();
        // El-cheapo assert_eq due to lack of PartialEq for tor-netdoc poc.
        match data {
            ConsensusBoundData::Verified { consensus, ttl, .. } => {
                // If everything worked properly, then the queue should only
                // contain the relay we removed, because that is missing now.
                db::read_tx(&pool, |tx| {
                    assert_eq!(
                        consensus.missing_routers(tx, iter::empty(), None).unwrap(),
                        HashSet::from([relay_to_remove])
                    );
                    assert!(
                        consensus
                            .missing_extras(tx, iter::empty(), None)
                            .unwrap()
                            .is_empty()
                    );
                    assert!(
                        consensus
                            .missing_micros(tx, iter::empty(), None)
                            .unwrap()
                            .is_empty()
                    );
                })
                .unwrap();
                assert!(ttl >= fresh_until);
                assert!(ttl <= fresh_until_half);
            }
            _ => panic!("data is not verified"),
        }
    }
    /// Tests whether the fetch consensus state properly fetches a consensus
    /// and keeps it in memory as unverified.
    ///
    /// For this, we spawn a tokio task simulating a web server which responds
    /// with a consensus.
    #[tokio::test]
    async fn state_fetch_consensus() {
        let pool = testdata2::test_db();
        let mut data = ConsensusBoundData::<Plain>::None;
        let engine = static_engine();
        let now = Timestamp::from(testdata2::invalid_system_time());
        let state = db::read_tx(&pool, |tx| engine.determine_state(tx, &data, now))
            .unwrap()
            .unwrap();
        assert_eq!(state, State::FetchConsensus);
        let server = TcpListener::bind("[::1]:0").await.unwrap();
        let saddr = server.local_addr().unwrap();
        tokio::spawn(async move {
            let (mut stream, _) = server.accept().await.unwrap();
            let mut buf = vec![0; 1024];
            let _ = stream.read(&mut buf).await.unwrap();
            let consensus = testdata2::current_consensus_ns().2;
            let resp = format!(
                "HTTP/1.0 200 OK\r\nContent-Encoding: identity\r\nContent-Length: {}\r\n\r\n{consensus}",
                consensus.len()
            );
            stream.write_all(resp.as_bytes()).await.unwrap();
        });
        engine
            .fetch_consensus(&mut data, &[saddr], now)
            .await
            .unwrap();
        match data {
            ConsensusBoundData::Unverified { raw, ttl, .. } => {
                assert_eq!(raw, testdata2::current_consensus_ns().2);
                assert_eq!(ttl, now + UNVERIFIED_TTL);
            }
            _ => panic!("data is not unverified"),
        }
    }
    /// Tests the download, verification, and insertion of authority certificates.
    ///
    /// For this, it starts by removing an existing one from the test database
    /// to see it getting re-downloaded, re-verified, and re-inserted again.
    #[tokio::test]
    async fn state_auth_certs() {
        let pool = testdata2::test_db();
        let mut data = ConsensusBoundData::<Plain>::Unverified {
            consensus: parse2::parse_netdoc(&ParseInput::new(
                testdata2::current_consensus_ns().2,
                "",
            ))
            .unwrap(),
            raw: testdata2::current_consensus_ns().2.to_owned(),
            ttl: Timestamp::from(testdata2::valid_system_time()) + UNVERIFIED_TTL,
        };
        let mut engine = static_engine();
        // We want to download authority certificates; for this, remove
        // one of them from the database.
        pool.get()
            .unwrap()
            .execute(
                sql!(
                    "
                    DELETE FROM authority_key_certificate
                    WHERE :kp_auth_id_rsa_sha1 = ?1
                    "
                ),
                params![db::Sha1::from(
                    testdata2::current_auth_cert_ids()[0].to_bytes()
                )],
            )
            .unwrap();
        assert_eq!(
            db::read_tx(&pool, |tx| engine.determine_state(
                tx,
                &data,
                testdata2::valid_system_time().into()
            ))
            .unwrap()
            .unwrap(),
            State::AuthCerts
        );
        let server = TcpListener::bind("[::1]:0").await.unwrap();
        let saddr = server.local_addr().unwrap();
        tokio::spawn(async move {
            let mut buf = [0; 1024];
            let (mut stream, _) = server.accept().await.unwrap();
            let _ = stream.read(&mut buf).await.unwrap();
            let authcerts = testdata2::current_auth_certs()
                .into_iter()
                .map(|x| x.1)
                .collect::<String>();
            stream.write_all(format!(
                "HTTP/1.0 200 OK\r\nContent-Encoding: identity\r\nContent-Length: {}\r\n\r\n{authcerts}",
                authcerts.len()
            ).as_bytes()).await.unwrap();
        });
        // Fetch all authcerts.
        engine
            .auth_certs(
                &pool,
                &mut data,
                &[saddr],
                testdata2::valid_system_time().into(),
            )
            .await
            .unwrap();
        // Check whether we are done with all authcerts.
        assert_eq!(
            db::read_tx(&pool, |tx| engine.determine_state(
                tx,
                &data,
                testdata2::valid_system_time().into(),
            ))
            .unwrap()
            .unwrap(),
            State::StoreConsensus
        );
        // Check whether we now have all auth certs in the database.
        let certs = db::read_tx(&pool, |tx| {
            engine.certs_already(tx, testdata2::valid_system_time().into())
        })
        .unwrap()
        .unwrap();
        let got = certs
            .into_iter()
            .map(|c| c.dir_identity_key.to_rsa_identity())
            .collect::<HashSet<_>>();
        let expect = engine.authorities.v3idents().iter().copied().collect();
        assert_eq!(got, expect);
        // Check an edge case of not having enough trusted signers.
        engine.authorities = AuthorityContacts::builder().build().unwrap();
        let state = db::read_tx(&pool, |tx| {
            engine.determine_state(tx, &data, testdata2::valid_system_time().into())
        })
        .unwrap()
        .unwrap();
        assert_eq!(state, State::Hibernate);
    }
    /// Checks whether we can probably load and parse all certificates from
    /// the database.
    #[tokio::test]
    async fn certs_already() {
        let pool = testdata2::test_db();
        let engine = static_engine::<Plain>();
        db::read_tx(&pool, |tx| {
            // With a correct system time, this should align with all authority
            // fingerprints we have.
            let certs_already = engine
                .certs_already(tx, testdata2::valid_system_time().into())
                .unwrap();
            assert_eq!(certs_already.len(), engine.authorities.v3idents().len());
            assert!(certs_already.iter().all(|c| {
                engine
                    .authorities
                    .v3idents()
                    .contains(&c.dir_identity_key.to_rsa_identity())
            }));
            // With an invalid system time, it should be empty.
            let certs_already = engine
                .certs_already(tx, testdata2::invalid_system_time().into())
                .unwrap();
            assert!(certs_already.is_empty());
        })
        .unwrap();
    }
    /// Ensures that an unverified consensus gets properly inserted into the
    /// database.
    #[tokio::test]
    async fn state_store_consensus() {
        let pool = testdata2::test_db();
        let unverified: Plain =
            parse2::parse_netdoc(&ParseInput::new(testdata2::current_consensus_ns().2, ""))
                .unwrap();
        let engine = static_engine();
        let now = Timestamp::from(testdata2::valid_system_time());
        let mut data = ConsensusBoundData::<Plain>::Unverified {
            consensus: unverified.clone(),
            raw: testdata2::current_consensus_ns().2.to_string(),
            ttl: now + UNVERIFIED_TTL,
        };
        // Clean all consensus related tables.
        pool.get()
            .unwrap()
            .execute_batch(sql!(
                "
                DELETE FROM consensus_descriptor_member;
                DELETE FROM consensus_authority_voter;
                DELETE FROM consensus;
                "
            ))
            .unwrap();
        // Execute the StoreConsensus state.
        let state = db::read_tx(&pool, |tx| engine.determine_state(tx, &data, now))
            .unwrap()
            .unwrap();
        assert_eq!(state, State::StoreConsensus);
        engine.store_consensus(&pool, &mut data, now).unwrap();
        assert!(matches!(&data, ConsensusBoundData::None));
        // Verify that it got inserted.
        let state = db::read_tx(&pool, |tx| engine.determine_state(tx, &data, now))
            .unwrap()
            .unwrap();
        assert_eq!(state, State::LoadConsensus);
        engine
            .load_consensus(&pool, &mut data, now, &mut testing_rng())
            .unwrap();
        assert!(matches!(data, ConsensusBoundData::Verified { .. }));
    }
    /// Agnostic test for the descriptor state.
    async fn state_descriptors_agnostic<
        T: FlavoredConsensusUnverified,
        D: DescriptorDownloader<T>,
    >(
        descriptors: Vec<String>,
        get_futile: fn(&FutileDescriptors) -> &FutileDescriptorSet<D::DocDigest>,
    ) {
        let pool = testdata2::test_db();
        let engine = static_engine::<T>();
        let now = Timestamp::from(testdata2::valid_system_time());
        let mut data = ConsensusBoundData::None;
        let rng = &mut testing_rng();
        // Server task that can at most handle two requests.
        //
        // The first response contains all available descriptors
        // statically, whereas the second one only contains a single
        // descriptor.
        let listener = TcpListener::bind("[::1]:0").await.unwrap();
        let endpoint = listener.local_addr().unwrap();
        tokio::spawn(async move {
            let mut buf = [0; 1024];
            let full = descriptors.iter().cloned().collect::<String>();
            let single = descriptors.iter().take(1).cloned().collect::<String>();
            let (mut stream, _) = listener.accept().await.unwrap();
            let _ = stream.read(&mut buf).await.unwrap();
            stream
                .write_all(
                    format!(
                        "HTTP/1.0 200 OK\r\nContent-Length: {}\r\n\r\n{}",
                        full.len(),
                        full
                    )
                    .as_bytes(),
                )
                .await
                .unwrap();
            drop(stream);
            let (mut stream, _) = listener.accept().await.unwrap();
            let _ = stream.read(&mut buf).await.unwrap();
            stream
                .write_all(
                    format!(
                        "HTTP/1.0 200 OK\r\nContent-Length: {}\r\n\r\n{}",
                        single.len(),
                        single
                    )
                    .as_bytes(),
                )
                .await
                .unwrap();
        });
        // Delete all descriptors from the database and then load
        // a consensus into ConsensusBoundData.
        db::rw_tx(&pool, |tx| tx.execute(sql!("DELETE FROM descriptor"), ()))
            .unwrap()
            .unwrap();
        engine.load_consensus(&pool, &mut data, now, rng).unwrap();
        let state = db::read_tx(&pool, |tx| engine.determine_state(tx, &data, now))
            .unwrap()
            .unwrap();
        assert_eq!(state, State::Descriptors);
        // Successful bootstrap of all descriptors.
        engine
            .descriptors(&pool, &mut data, &[endpoint], now)
            .await
            .unwrap();
        // Afterwards, the queue for missing descriptors should be empty
        // as well as futile.
        let (meta, futile) = match &data {
            ConsensusBoundData::Verified {
                consensus: meta,
                futile,
                ..
            } => (*meta, futile.clone()),
            _ => panic!(),
        };
        let missing = db::read_tx(&pool, |tx| D::query(tx, &meta, &futile, &[endpoint]))
            .unwrap()
            .unwrap();
        assert!(missing.is_empty());
        assert!(get_futile(&futile).not_found.is_empty());
        assert!(get_futile(&futile).refused.is_empty());
        // Now, if we do this again, futile should be populated.
        db::rw_tx(&pool, |tx| tx.execute(sql!("DELETE FROM descriptor"), ()))
            .unwrap()
            .unwrap();
        // Because this time the server will only return a single descriptor,
        // it may either succeed or fail because it returned a descriptor that
        // we did not asked for.  Either way, it does not really matter because
        // we want to test whether the remaining ones get set as missing or not,
        // which is done in the next step.
        let res = engine.descriptors(&pool, &mut data, &[endpoint], now).await;
        assert!(matches!(
            res,
            Ok(())
                | Err(OperationError::AuthorityRequest(
                    AuthorityRequestError::NoRequestedDocumentsReturned
                ))
        ));
        // Now, the missing descriptors should equal the ones that were not
        // found on the authority, as in being in the futile set.
        let missing = db::read_tx(&pool, |tx| D::query(tx, &meta, &futile, &[endpoint]))
            .unwrap()
            .unwrap();
        let futile = match &data {
            ConsensusBoundData::Verified { futile, .. } => futile,
            _ => panic!(),
        };
        assert!(!missing.is_empty());
        assert_eq!(
            missing,
            get_futile(futile)
                .not_found
                .iter()
                .filter_map(|(digest, this_endpoint)| if **this_endpoint == [endpoint] {
                    Some(*digest)
                } else {
                    None
                })
                .collect::<HashSet<_>>()
        );
        assert!(get_futile(futile).refused.is_empty());
    }
    /// Tests the descriptor bootstrapping for router descriptors.
    #[tokio::test]
    async fn state_descriptors_plain() {
        state_descriptors_agnostic::<Plain, RdDownloader>(
            testdata2::current_router_descs()
                .into_iter()
                .map(|(_, _, raw)| raw)
                .collect(),
            |futile| &futile.routers,
        )
        .await;
    }
    #[tokio::test]
    async fn state_descriptors_md() {
        state_descriptors_agnostic::<Md, MdDownloader>(
            testdata2::current_micro_descs()
                .into_iter()
                .map(|(_, raw)| raw)
                .collect(),
            |futile| &futile.micros,
        )
        .await;
    }
}