1
//! Access to the database schema.
2
//!
3
//! This module is not intended to provide a high-level ORM, instead it serves
4
//! the purpose of initializing and upgrading the database, if necessary.
5
//!
6
//! # Synchronous or Asynchronous?
7
//!
8
//! The question on whether the database and access to it shall be synchronous
9
//! or asynchronous has been fairly long debate that eventually got settled
10
//! after realizing that an asynchronous approach does not work.  This comment
11
//! should serve as a reminder for future devs, wondering why we use certain
12
//! synchronous primitives in an otherwise asynchronous codebase.
13
//!
14
//! Early on, it was clear that we would need some sort of connection pool,
15
//! primarily for two reasons:
16
//! 1. Performing frequent open and close calls in every task would be costly.
17
//! 2. Sharing a single connection object with a Mutex would be a waste
18
//!
19
//! Because the application itself is primarily asynchronous, we decided to go
20
//! with an asynchronous connection pool as well, leading to the choose of
21
//! `deadpool` initially.
22
//!
23
//! However, soon thereafter, problems with `deadpool` became evident.  Those
24
//! problems mostly stemmed from the synchronous nature of SQLite itself.  In our
25
//! case, this problem was initially triggered by figuring out a way to solve
26
//! `SQLITE_BUSY` handling.  In the end, we decided to settle upon the following
27
//! approach: Set `PRAGMA busy_timeout` to a certain value and create write
28
//! transactions with `BEGIN EXCLUSIVE`.  This way, SQLite would try to obtain
29
//! a write transaction for `busy_timeout` milliseconds by blocking the current
30
//! thread.  Due to this blocking, async no longer made any sense and was in
31
//! fact quite counter-productive because those potential sleep could screw a
32
//! lot of things up, which became very evident while trying to test this.
33
//!
34
//! Besides, throughout refactoring the code base, we realized that, even while
35
//! still using `deadpool`, the actual "asynchronous" calls interfacing with the
36
//! database became smaller and smaller.  In the end, the asynchronous code just
37
//! involved parts of obtaining a connection and creating a transaction,
38
//! eventually resulting in a calling a synchronous function taking the
39
//! transaction handle to perform the lion's share of the operation.
40

            
41
// TODO DIRMIRROR: This could benefit from methods by wrapping the pool into a
42
// custom type.
43

            
44
use std::{
45
    collections::HashSet,
46
    fmt::Display,
47
    io::{Cursor, Write},
48
    marker::PhantomData,
49
    num::NonZero,
50
    ops::{Add, Sub},
51
    path::Path,
52
    rc::Rc,
53
    time::{Duration, SystemTime},
54
};
55

            
56
use digest::Digest;
57
use educe::Educe;
58
use flate2::write::{DeflateEncoder, GzEncoder};
59
use r2d2::Pool;
60
use r2d2_sqlite::SqliteConnectionManager;
61
use rand::Rng;
62
use rusqlite::{
63
    OptionalExtension, ToSql, Transaction, TransactionBehavior, named_params, params,
64
    types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, Value, ValueRef},
65
};
66
use saturating_time::SaturatingTime;
67
use thiserror::Error;
68
use tor_basic_utils::RngExt;
69
use tor_error::{internal, into_internal};
70
use tor_netdoc::doc::{authcert::AuthCert, netstatus::ConsensusFlavor};
71

            
72
use crate::types::{
73
    FlavoredConsensusBody, FlavoredConsensusSignatures, FlavoredConsensusUnverified,
74
    FlavoredDescriptor,
75
};
76

            
77
/// Version 1 of the database schema.
78
///
79
/// TODO DIRMIRROR: Before the release, figure out where to use rowid and where
80
/// to use docid.
81
const V1_SCHEMA: &str = include_str!("schema_v1.sql");
82

            
83
/// Global options set in every connection.
84
const GLOBAL_OPTIONS: &str = sql!(
85
    "
86
PRAGMA journal_mode=WAL;
87
PRAGMA foreign_keys=ON;
88
PRAGMA busy_timeout=1000;
89
"
90
);
91

            
92
/// An error while interacting with a database.
93
///
94
/// This error should be returned by all functions that interact with the
95
/// database in one way or another.
96
#[derive(Debug, Error)]
97
#[non_exhaustive]
98
pub(crate) enum DatabaseError {
99
    /// A low-level SQLite error has occurred, which can have a basically
100
    /// infinite amount of reasons, all of them outlined in the actual SQLite
101
    /// and [`rusqlite`] documentation.
102
    #[error("low-level rusqlite error: {0}")]
103
    LowLevel(#[from] rusqlite::Error),
104

            
105
    /// This is an application level error meaning that the database can be
106
    /// successfully accessed but its content implies it is of a schema version
107
    /// we do not support.
108
    ///
109
    /// Keep in mind that an unrecognized schema is not equal to no schema.
110
    /// In the latter case we actually initialize the database, whereas in the
111
    /// previous one, we fail early in order to not corrupt an existing database.
112
    /// Future versions of this crate should continue with this promise in order
113
    /// to ensure forward compatibility.
114
    #[error("incompatible schema version: {version}")]
115
    IncompatibleSchema {
116
        /// The incompatible schema version found in the database.
117
        version: String,
118
    },
119

            
120
    /// Interaction with our database pool, [`r2d2`], has failed.
121
    ///
122
    /// Unlike other database pools, this error is fairly straightforward and
123
    /// may only be obtained in the cases in which we try to obtain a connection
124
    /// handle from the pool.  Notably, it does not fail if, for example,
125
    /// the low-level [`rusqlite`] has a failure.
126
    #[error("pool error: {0}")]
127
    Pool(#[from] r2d2::Error),
128

            
129
    /// An internal error.
130
    #[error("Internal error")]
131
    Bug(#[from] tor_error::Bug),
132
}
133

            
134
/// Convenience macro for implementing a hash type in a rusqlite compatible fashion.
135
///
136
/// This macro accepts the following parameters:
137
/// 1. `name` for specifying an identifier of the type, such as [`Sha256`].
138
/// 2. `algo` for specifying the type from the rust-crypto [`digest`] ecosystem,
139
///    such as [`tor_llcrypto::d::Sha256`].
140
/// 3. The size in bytes of the hash output, such as `32` for [`Sha256`].
141
///     * Unfortunately, we cannot use something like [`Digest::output_size()`]
142
///       because it is not a constant.
143
///
144
/// It generates a struct with `name` as the identifier, which implements the
145
/// following methods:
146
/// * `digest` for wrapping around [`Digest::digest()`].
147
///
148
/// It also implements the following traits:
149
/// * [`Display`]
150
/// * [`FromSql`]
151
/// * [`ToSql`]
152
/// * [`PartialEq<&str>`] for base16 comparisons
153
/// * [`From<u8; $size>`]
154
macro_rules! impl_hash_wrapper {
155
    ($name:ident, $algo:ty, $size:literal) => {
156
        /// Database wrapper type for $name.
157
        ///
158
        /// Serves as a database friendly wrapper around [`tor_llcrypto::d`]
159
        /// with features such as SQL support.
160
        #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
161
        pub(crate) struct $name(pub [u8; $size]);
162

            
163
        impl $name {
164
            /// Computes the hash from arbitrary data.
165
2066
            pub(crate) fn digest(data: &[u8]) -> Self {
166
2066
                Self(<$algo>::digest(data).into())
167
2066
            }
168
        }
169

            
170
        impl Display for $name {
171
            /// Formats the hash in uppercase hexadecimal.
172
5049
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173
5049
                write!(f, "{}", hex::encode_upper(self.0))
174
5049
            }
175
        }
176

            
177
        impl FromSql for $name {
178
327
            fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
179
                // We read the hash as a hexadecimal string from the database.
180
                // Convert it to binary data and check length afterwards.
181
327
                let data: [u8; $size] = value
182
327
                    .as_str()
183
327
                    .map(hex::decode)?
184
                    .map_err(|e| {
185
                        FromSqlError::Other(Box::new(tor_error::internal!(
186
                            "non hex data in database? {e}"
187
                        )))
188
                    })?
189
                    .try_into()
190
                    .map_err(|_| {
191
                        FromSqlError::Other(Box::new(tor_error::internal!(
192
                            "$name with invalid length in database?"
193
                        )))
194
                    })?;
195

            
196
327
                Ok(Self(data))
197
327
            }
198
        }
199

            
200
        impl ToSql for $name {
201
5022
            fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
202
                // Because Self is only constructed with FromSql and digest
203
                // data, it is safe to assume it is valid.
204
5022
                Ok(ToSqlOutput::from(self.to_string()))
205
5022
            }
206
        }
207

            
208
        impl From<$name> for Value {
209
26
            fn from(value: $name) -> Value {
210
26
                Value::Text(value.to_string())
211
26
            }
212
        }
213

            
214
        impl PartialEq<&str> for $name {
215
1
            fn eq(&self, other: &&str) -> bool {
216
1
                self.to_string() == other.to_uppercase()
217
1
            }
218
        }
219

            
220
        impl From<[u8; $size]> for $name {
221
1230
            fn from(value: [u8; $size]) -> Self {
222
1230
                Self(value)
223
1230
            }
224
        }
225
    };
226
}
227

            
228
impl_hash_wrapper!(Sha1, tor_llcrypto::d::Sha1, 20);
229
impl_hash_wrapper!(Sha256, tor_llcrypto::d::Sha256, 32);
230
impl_hash_wrapper!(Sha3_256, tor_llcrypto::d::Sha3_256, 32);
231

            
232
/// The identifier for documents in the content-addressable cache.
233
///
234
/// Right now, this is a [`Sha256`] hash, but this may change in future.
235
pub(crate) type DocumentId = Sha256;
236

            
237
/// The supported content encodings.
238
#[derive(
239
    Debug, Clone, Copy, PartialEq, Eq, Hash, strum::EnumString, strum::Display, strum::EnumIter,
240
)]
241
#[strum(serialize_all = "kebab-case", ascii_case_insensitive)]
242
pub(crate) enum ContentEncoding {
243
    /// RFC2616 section 3.5.
244
    Identity,
245
    /// RFC2616 section 3.5.
246
    Deflate,
247
    /// RFC2616 section 3.5.
248
    Gzip,
249
    /// The zstandard compression algorithm (www.zstd.net).
250
    XZstd,
251
    /// The lzma compression algorithm with a "present" value no higher than 6.
252
    XTorLzma,
253
}
254

            
255
/// A wrapper around [`SystemTime`] with convenient features.
256
///
257
/// Please use this type throughout the crate internally, instead of
258
/// [`SystemTime`].
259
///
260
/// # Conversion
261
///
262
/// This type can be safely converted from and into a [`SystemTime`], because
263
/// it is just a wrapper type.
264
///
265
/// # Saturating Arithmetic
266
///
267
/// This type implements [`Add`] and [`Sub`] for [`Duration`] and [`Timestamp`]
268
/// ([`Sub`] only) using saturating arithmetic from the [`saturating_time`]
269
/// crate.  It means that addition and subtraction can be safely performed
270
/// without the potential risk of an unexpected panic, instead wrapping to
271
/// a local maximum/minimum or [`Duration::ZERO`] depending on the type.
272
///
273
/// Note that we don't provide a saturating version of [`Duration`], so addition
274
/// or subtraction of two [`Duration`]s still needs care to avoid panics.
275
///
276
/// # SQLite Interaction
277
///
278
/// This type implements [`FromSql`] and [`ToSql`], making it convenient to
279
/// integrate into SQL statements, as the database schema represents timestamps
280
/// internally using a non-negative [`i64`] storing the seconds since the epoch.
281
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
282
pub(crate) struct Timestamp(SystemTime);
283

            
284
impl From<SystemTime> for Timestamp {
285
20203
    fn from(value: SystemTime) -> Self {
286
20203
        Self(value)
287
20203
    }
288
}
289

            
290
impl From<Timestamp> for SystemTime {
291
71
    fn from(value: Timestamp) -> Self {
292
71
        value.0
293
71
    }
294
}
295

            
296
impl Add<Duration> for Timestamp {
297
    type Output = Self;
298

            
299
    /// Performs a saturating addition wrapping to [`SystemTime::max_value()`].
300
10009
    fn add(self, rhs: Duration) -> Self::Output {
301
10009
        Self(self.0.saturating_add(rhs))
302
10009
    }
303
}
304

            
305
impl Sub<Duration> for Timestamp {
306
    type Output = Self;
307

            
308
    /// Performs a saturating subtraction wrapping to [`SystemTime::min_value()`].
309
    fn sub(self, rhs: Duration) -> Self::Output {
310
        Self(self.0.saturating_sub(rhs))
311
    }
312
}
313

            
314
impl Sub<Timestamp> for Timestamp {
315
    type Output = Duration;
316

            
317
    /// Performs a saturating duration_since wrapping to [`Duration::ZERO`].
318
10005
    fn sub(self, rhs: Timestamp) -> Self::Output {
319
        #[allow(unstable_name_collisions)]
320
10005
        self.0.saturating_duration_since(rhs.0)
321
10005
    }
322
}
323

            
324
impl FromSql for Timestamp {
325
140
    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
326
140
        let mut res = SystemTime::UNIX_EPOCH;
327
140
        res = res.saturating_add(Duration::from_secs(value.as_i64()?.try_into().unwrap_or(0)));
328
140
        Ok(Self(res))
329
140
    }
330
}
331

            
332
impl ToSql for Timestamp {
333
182
    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
334
        #[allow(unstable_name_collisions)]
335
182
        Ok(ToSqlOutput::from(
336
182
            self.0
337
182
                .saturating_duration_since(SystemTime::UNIX_EPOCH)
338
182
                .as_secs()
339
182
                .try_into()
340
182
                .unwrap_or(i64::MAX),
341
182
        ))
342
182
    }
343
}
344

            
345
/// Representation of consensus metadata from the database.
346
#[derive(Educe)]
347
#[educe(Debug, Clone, Copy, PartialEq, Eq)]
348
pub(crate) struct ConsensusMeta<T> {
349
    /// The document id uniquely identifying the consensus.
350
    pub docid: DocumentId,
351

            
352
    /// The SHA3 of the unsigned part of the consensus.
353
    pub sha3_256: Sha3_256,
354

            
355
    /// The time after which this consensus is valid.
356
    pub valid_after: Timestamp,
357

            
358
    /// The time after which this consensus stops being fresh.
359
    pub fresh_until: Timestamp,
360

            
361
    /// The time after which this consensus stops being valid.
362
    pub valid_until: Timestamp,
363

            
364
    /// The flavor of the consensus; determined at compile time.
365
    flavor: PhantomData<T>,
366
}
367

            
368
impl<T: FlavoredConsensusUnverified> ConsensusMeta<T> {
369
    /// Select the missing router descriptors.
370
    ///
371
    /// A router descriptor is considered missing if it exists in
372
    /// `consensus_descriptor_member` but not in `descriptor`
373
    /// because the first entry is added once the consensus got parsed,
374
    /// whereas the second entry is added once we have actually retrieved it.
375
    ///
376
    /// It works by doing a left join on descriptor and filtering for
377
    /// all entries where the join is NULL, as that implies we are aware of
378
    /// the descriptor but not have it stored.
379
    ///
380
    /// Parameters:
381
    /// :docid - The docid of the consensus.
382
    /// :exclude - The descriptors to skip.
383
    /// :limit - The maximum number of descriptors to return.
384
    //
385
    // TODO DIRMIRROR: Potentially constify more queries.
386
    const MISSING_ROUTERS_QUERY: &'static str = sql!(
387
        "
388
        SELECT cr.sha1, RANDOM() AS rand
389
        FROM consensus_descriptor_member AS cr
390
          LEFT JOIN descriptor AS router ON cr.sha1 = router.sha1
391
        WHERE
392
          cr.consensus_docid = :docid
393
          AND cr.sha1 IS NOT NULL
394
          AND cr.sha1 NOT IN rarray(:exclude)
395
          AND router.sha1 IS NULL
396
        ORDER BY rand
397
        LIMIT :limit
398
        "
399
    );
400

            
401
    /// Obtains all consensuses found in the database.
402
    ///
403
    /// This should be reasonable size-wise, given that a ConsensusMeta instance
404
    /// is very small and that the garbage collector removes old consensuses
405
    /// anyways.  If this becomes a problem, we may want to add an optional
406
    /// limit.
407
12
    pub(crate) fn query(tx: &Transaction) -> Result<Vec<Self>, DatabaseError> {
408
        // Select the most recent flavored consensus document from the database.
409
12
        let mut meta_stmt = tx.prepare_cached(sql!(
410
12
            "
411
12
            SELECT docid, sha3_256, valid_after, fresh_until, valid_until
412
12
            FROM consensus
413
12
            WHERE
414
12
              flavor = :flavor
415
12
            ORDER BY valid_after DESC
416
12
            "
417
12
        ))?;
418

            
419
        // Actually execute the query.
420
12
        let rows = meta_stmt.query_map(
421
12
            named_params! {
422
12
                ":flavor": T::flavor().name(),
423
            },
424
12
            |row| {
425
                Ok(Self {
426
12
                    docid: row.get(0)?,
427
12
                    sha3_256: row.get(1)?,
428
12
                    valid_after: row.get(2)?,
429
12
                    fresh_until: row.get(3)?,
430
12
                    valid_until: row.get(4)?,
431
12
                    flavor: Default::default(),
432
                })
433
12
            },
434
        )?;
435

            
436
12
        Ok(rows.collect::<Result<Vec<_>, _>>()?)
437
12
    }
438

            
439
    /// Queries the raw data of a [`ConsensusMeta`].
440
6
    pub(crate) fn data(&self, tx: &Transaction<'_>) -> Result<String, DatabaseError> {
441
6
        let mut stmt = tx.prepare_cached(sql!(
442
6
            "
443
6
            SELECT content
444
6
            FROM store
445
6
            WHERE docid = :docid
446
6
            "
447
6
        ))?;
448

            
449
6
        let raw = stmt.query_one(named_params! {":docid": self.docid}, |row| {
450
6
            row.get::<_, Vec<u8>>(0)
451
6
        })?;
452
6
        let raw = String::from_utf8(raw).map_err(into_internal!("utf-8 constraint violated?"))?;
453
6
        Ok(raw)
454
6
    }
455

            
456
    /// Calculates the [`Timestamp`] at which the authorities will be queried again.
457
    ///
458
    /// # Specifications
459
    ///
460
    /// * <https://spec.torproject.org/dir-spec/directory-cache-operation.html#download-ns-from-auth>
461
10004
    pub(crate) fn ttl<R: Rng>(&self, rng: &mut R) -> Timestamp {
462
10004
        assert!(self.fresh_until < self.valid_until);
463

            
464
10004
        let offset = rng
465
10004
            .gen_range_checked(0..=((self.valid_until - self.fresh_until).as_secs() / 2))
466
10004
            .expect("invalid range?");
467

            
468
10004
        self.fresh_until + Duration::from_secs(offset)
469
10004
    }
470

            
471
    /// Returns the missing router descriptors for this consensus.
472
    ///
473
    /// `limit` may be given to specify an optional upper limit, in which case
474
    /// the result will contain at most `limit` missing descriptors.
475
    ///
476
    /// # Performance
477
    ///
478
    /// The performance here is O(n * log n) for each 64-element batch, leading
479
    /// to an overall performance of O(n^2 * (log n)/64) per consensus period,
480
    /// which sould be acceptable.  See the link below for a further discussion
481
    /// on performance related matters:
482
    ///
483
    /// <https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/4378#note_3467300>
484
    // TODO DIRMIRROR: This has a large overlap with missing_extras and
485
    // missing_micros, we should genericise or macrofy this at one point.
486
15
    pub(crate) fn missing_routers(
487
15
        &self,
488
15
        tx: &Transaction<'_>,
489
15
        exclude: impl Iterator<Item = Sha1>,
490
15
        limit: Option<u64>,
491
15
    ) -> Result<HashSet<Sha1>, DatabaseError> {
492
15
        if T::flavor() != ConsensusFlavor::Plain {
493
1
            return Ok(HashSet::new());
494
14
        }
495

            
496
14
        let mut stmt = tx.prepare_cached(Self::MISSING_ROUTERS_QUERY)?;
497

            
498
14
        let exclude = exclude.map(Value::from).collect();
499
14
        let exclude: Rc<Vec<Value>> = Rc::new(exclude);
500
14
        let limit = limit.map_or(-1, |n| n.try_into().unwrap_or(i64::MAX));
501
14
        let missing = stmt
502
            .query_map(
503
14
                named_params! {":docid": self.docid, ":limit": limit, ":exclude": exclude},
504
94
                |row| row.get(0),
505
            )?
506
            .collect::<Result<HashSet<_>, _>>()?;
507
14
        Ok(missing)
508
15
    }
509

            
510
    /// Returns the missing extra infos for this consensus to the best of our abilities.
511
    ///
512
    /// Keep in mind that this does not return **all** missing extra infos but
513
    /// only the missing extra infos of router descriptors we have.
514
    ///
515
    /// `limit` may be given to specify an optional upper limit, in which case
516
    /// the result will contain at most `limit` missing extra-infos.
517
    ///
518
    /// See [`ConsensusMeta::missing_routers()`] for a discussion on
519
    /// performance.
520
4
    pub(crate) fn missing_extras(
521
4
        &self,
522
4
        tx: &Transaction<'_>,
523
4
        exclude: impl Iterator<Item = Sha1>,
524
4
        limit: Option<u64>,
525
4
    ) -> Result<HashSet<Sha1>, DatabaseError> {
526
4
        if T::flavor() != ConsensusFlavor::Plain {
527
1
            return Ok(HashSet::new());
528
3
        }
529

            
530
        // Select the missing extra infos for this consensus.
531
        //
532
        // This return value is not complete because we only know the missing
533
        // extra-infos to the best of our abilities.  In other words: We are
534
        // only aware of a missing extra-info if we have parsed the respective
535
        // router descriptor.
536
        //
537
        // It works by doing an inner join from
538
        // `consensus_descriptor_member` to `descriptor` because
539
        // we can only know about the extra-infos of which we have the router
540
        // descriptors from.  Afterwards, we do a left join with the
541
        // `extra_info` table and filter for all results where the left
542
        // join result is null, hence where we have a router descriptor but not
543
        // the respective extra-info.
544
        //
545
        // Parameters:
546
        // :docid - The docid of the consensus.
547
        // :exclude - The descriptors to skip.
548
        // :limit - The maximum number of descriptors to return.
549
3
        let mut stmt = tx.prepare_cached(sql!(
550
3
            "
551
3
            SELECT router.extra_sha1, RANDOM() AS rand
552
3
            FROM consensus_descriptor_member AS cr
553
3
              INNER JOIN descriptor AS router ON cr.sha1 = router.sha1
554
3
              LEFT JOIN extra_info AS extra ON router.extra_sha1 = extra.sha1
555
3
            WHERE
556
3
              cr.consensus_docid = :docid
557
3
              AND router.extra_sha1 IS NOT NULL
558
3
              AND extra.sha1 IS NULL
559
3
              AND extra.sha1 NOT IN rarray(:exclude)
560
3
            ORDER BY rand
561
3
            LIMIT :limit
562
3
            "
563
3
        ))?;
564

            
565
3
        let exclude = exclude.map(Value::from).collect();
566
3
        let exclude: Rc<Vec<Value>> = Rc::new(exclude);
567
3
        let limit = limit.map_or(-1, |n| n.try_into().unwrap_or(i64::MAX));
568
3
        let missing = stmt
569
            .query_map(
570
3
                named_params! {":docid": self.docid, ":limit": limit, ":exclude": exclude},
571
                |row| row.get(0),
572
            )?
573
            .collect::<Result<HashSet<_>, _>>()?;
574
3
        Ok(missing)
575
4
    }
576

            
577
    /// Returns the missing micro descriptors for this consensus.
578
    ///
579
    /// `limit` may be given to specify an optional upper limit, in which case
580
    /// the result will contain at most `limit` missing descriptors.
581
    ///
582
    /// See [`ConsensusMeta::missing_routers()`] for a discussion on
583
    /// performance.
584
9
    pub(crate) fn missing_micros(
585
9
        &self,
586
9
        tx: &Transaction<'_>,
587
9
        exclude: impl Iterator<Item = Sha256>,
588
9
        limit: Option<u64>,
589
9
    ) -> Result<HashSet<Sha256>, DatabaseError> {
590
9
        if T::flavor() != ConsensusFlavor::Microdesc {
591
2
            return Ok(HashSet::new());
592
7
        }
593

            
594
        // Select the missing micro descriptors.
595
        //
596
        // A micro descriptor is considered missing if it exists in
597
        // `consensus_descriptor_member` but not in `descriptor`
598
        // because the first entry is added once the consensus got parsed,
599
        // whereas the second entry is added once we have actually retrieved it.
600
        //
601
        // It works by doing a left join on descriptor and filtering for
602
        // all entries where the join is NULL, as that implies we are aware of
603
        // the descriptor but not have it stored.
604
        //
605
        // Parameters:
606
        // :docid - The docid of the consensus.
607
        // :limit - The maximum number of descriptors to return.
608
7
        let mut stmt = tx.prepare_cached(sql!(
609
7
            "
610
7
            SELECT cr.sha2, RANDOM() AS rand
611
7
            FROM consensus_descriptor_member AS cr
612
7
              LEFT JOIN descriptor AS micro ON cr.sha2 = micro.sha2
613
7
            WHERE
614
7
              cr.consensus_docid = :docid
615
7
              AND cr.sha2 IS NOT NULL
616
7
              AND cr.sha2 NOT IN rarray(:exclude)
617
7
              AND micro.sha2 IS NULL
618
7
            ORDER BY rand
619
7
            LIMIT :limit
620
7
            "
621
7
        ))?;
622

            
623
7
        let exclude = exclude.map(Value::from).collect();
624
7
        let exclude: Rc<Vec<Value>> = Rc::new(exclude);
625
7
        let limit = limit.map_or(-1, |n| n.try_into().unwrap_or(i64::MAX));
626
7
        let missing = stmt
627
            .query_map(
628
7
                named_params! {":docid": self.docid, ":limit": limit, ":exclude": exclude},
629
53
                |row| row.get(0),
630
            )?
631
            .collect::<Result<HashSet<_>, _>>()?;
632
7
        Ok(missing)
633
9
    }
634

            
635
    /// Inserts a verified consensus into the database.
636
    ///
637
    /// This method *DOES NOT* compute any consensus diffs but populates
638
    /// associated meta tables such as `consensus_descriptor_member`
639
    /// and `consensus_authority_voter` properly.
640
26
    pub(crate) fn insert<I>(
641
26
        tx: &Transaction<'_>,
642
26
        encodings: I,
643
26
        (body, sigs): (&T::Body, &T::Signatures),
644
26
        data: &str,
645
26
    ) -> Result<ConsensusMeta<T>, DatabaseError>
646
26
    where
647
26
        I: Iterator<Item = ContentEncoding>,
648
    {
649
        // Insert a consensus into the consensus meta table.
650
        //
651
        // This requires the consensus to already be present in the `store`
652
        // table.
653
        //
654
        // Parameters:
655
        // :docid - The docid of the consensus.
656
        // :sha3_256 - The SHA3-256 sum of the part of the consensus
657
        //   without signatures but a trailing `\ndirectory-signature<SPACE>`.
658
        // :flavor - The consensus flavor to use.
659
        // :valid_after, :fresh_until, :valid_until - The respective validities.
660
26
        let mut cons_stmt = tx.prepare_cached(sql!(
661
26
            "
662
26
            INSERT INTO consensus
663
26
            (docid, sha3_256, flavor, valid_after, fresh_until, valid_until)
664
26
            VALUES
665
26
            (:docid, :sha3_256, :flavor, :valid_after, :fresh_until, :valid_until)
666
26
            ON CONFLICT DO NOTHING
667
26
            "
668
26
        ))?;
669

            
670
        // Insert the relationship between a router status to a consensus.
671
        //
672
        // Parameters:
673
        // :docid - The consensus docid.
674
        // :sha1 - The router descriptor digest (plain consensus only, NULL otherwise).
675
        // :sha2 - The micro descriptor digest (microdesc consensus only, NULL otherwise).
676
26
        let mut cons_rs_member_stmt = tx.prepare_cached(sql!(
677
26
            "
678
26
            INSERT INTO consensus_descriptor_member
679
26
            (consensus_docid, sha1, sha2)
680
26
            VALUES
681
26
            (:docid, :sha1, :sha2)
682
26
            ON CONFLICT DO NOTHING
683
26
            "
684
26
        ))?;
685

            
686
        // Insert the relationship between authority certificate to consensus votes.
687
        //
688
        // Parameters:
689
        // :cons - The consensus docid.
690
        // :auth - The authority certificate docid.
691
26
        let mut cons_auth_voter = tx.prepare_cached(sql!(
692
26
            "
693
26
            INSERT INTO consensus_authority_voter
694
26
            (consensus_docid, kp_auth_id_rsa_sha1)
695
26
            VALUES
696
26
            (:consensus_docid, :id_rsa)
697
26
            ON CONFLICT DO NOTHING
698
26
            "
699
26
        ))?;
700

            
701
        // First, insert the consensus as is.
702
26
        let docid = store_insert(tx, data.as_bytes(), encodings)?;
703

            
704
        // TODO DIRMIRROR: We *need* this in tor-netdoc!!!
705
26
        let sha3_256 = Sha3_256::digest(
706
26
            data.split_inclusive("\ndirectory-signature ")
707
26
                .next()
708
                .ok_or_else(|| internal!("verified document without signatures?"))?
709
                .as_bytes(),
710
        );
711

            
712
26
        let lifetime = body.lifetime();
713
26
        let meta = ConsensusMeta {
714
26
            docid,
715
26
            sha3_256,
716
26
            valid_after: lifetime.valid_after.0.into(),
717
26
            fresh_until: lifetime.fresh_until.0.into(),
718
26
            valid_until: lifetime.valid_until.0.into(),
719
26
            flavor: Default::default(),
720
26
        };
721
26
        cons_stmt.execute(named_params! {
722
26
            ":docid": meta.docid,
723
26
            ":sha3_256": meta.sha3_256,
724
26
            ":valid_after": meta.valid_after,
725
26
            ":fresh_until": meta.fresh_until,
726
26
            ":valid_until": meta.valid_until,
727
26
            ":flavor": T::flavor().name(),
728
26
        })?;
729

            
730
        // Insert all router descriptor member relationships.
731
        //
732
        // Many small queries are fast in sqlite, so this shouldn't be a perf problem.
733
        // https://sqlite.org/np1queryprob.html
734
        //
735
        // Depending on the flavor, we map the document digests to an iterator
736
        // of a tuple of Option's, where one of the values is always None.
737
        // This represents the fact that router descriptors use SHA-1 and micro
738
        // descriptors SHA-256.
739
26
        for (sha1, sha2) in body.doc_digests() {
740
338
            cons_rs_member_stmt.execute(named_params! {
741
338
                ":docid": docid,
742
338
                ":sha1": sha1,
743
338
                ":sha2": sha2,
744
338
            })?;
745
        }
746

            
747
26
        for sig in sigs.signatories() {
748
104
            cons_auth_voter.execute(named_params! {
749
104
                ":consensus_docid": docid,
750
104
                ":id_rsa": Sha1(sig.id_fingerprint.to_bytes()),
751
104
            })?;
752
        }
753

            
754
26
        Ok(meta)
755
26
    }
756
}
757

            
758
/// Representation of authority certificate metadata from the database.
759
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
760
pub(crate) struct AuthCertMeta {
761
    /// The document id uniquely identifying the consensus.
762
    pub docid: DocumentId,
763

            
764
    /// The SHA-1 fingerprint of the identity key.
765
    // TODO DIRMIRROR: Change this to RsaIdentity.
766
    pub kp_auth_id_rsa_sha1: Sha1,
767

            
768
    /// The SHA-1 fingerprint of the signign key.
769
    // TODO DIRMIRROR: Change this to RsaIdentity.
770
    pub kp_auth_sign_rsa_sha1: Sha1,
771

            
772
    /// The timestamp after which this certificate will be valid.
773
    pub dir_key_published: Timestamp,
774

            
775
    /// The timestamp until this certificate will be valid.
776
    pub dir_key_expires: Timestamp,
777
}
778

            
779
impl AuthCertMeta {
780
    /// Obtains the authority certificates from the database.
781
15
    pub(crate) fn query(tx: &Transaction) -> Result<Vec<Self>, DatabaseError> {
782
        // Obtain all certificates from the database.
783
        //
784
        // This is okay because the set is not very big.
785
        //
786
        // In the unlikely edge case of on identity-signing key pair having
787
        // multiple certificates, the most recently published certificate is
788
        // going to be used.
789
        //
790
        // TODO DIRMIRROR: Perhaps we should modify the auth_certs table to
791
        // add a UNIQUE constraint on that combination, while modifying the
792
        // insertion logic to replace with the newer one in the case of a
793
        // conflict.
794
15
        let mut stmt = tx.prepare_cached(sql!(
795
15
            "
796
15
            SELECT docid, kp_auth_id_rsa_sha1, kp_auth_sign_rsa_sha1,
797
15
              dir_key_published, dir_key_expires
798
15
            FROM authority_key_certificate
799
15
            GROUP BY kp_auth_id_rsa_sha1, kp_auth_sign_rsa_sha1
800
15
            ORDER BY MAX(dir_key_published)
801
15
            "
802
15
        ))?;
803

            
804
15
        let certs = stmt
805
52
            .query_map(params![], |row| {
806
                Ok(Self {
807
52
                    docid: row.get(0)?,
808
52
                    kp_auth_id_rsa_sha1: row.get(1)?,
809
52
                    kp_auth_sign_rsa_sha1: row.get(2)?,
810
52
                    dir_key_published: row.get(3)?,
811
52
                    dir_key_expires: row.get(4)?,
812
                })
813
52
            })?
814
            .collect::<Result<_, _>>()?;
815
15
        Ok(certs)
816
15
    }
817

            
818
    /// Queries the raw data of an [`AuthCertMeta`].
819
52
    pub(crate) fn data(&self, tx: &Transaction<'_>) -> Result<String, DatabaseError> {
820
52
        let mut stmt = tx.prepare_cached(sql!(
821
52
            "
822
52
            SELECT content
823
52
            FROM store
824
52
            WHERE docid = :docid
825
52
            "
826
52
        ))?;
827

            
828
52
        let raw = stmt.query_one(named_params! {":docid": self.docid}, |row| {
829
52
            row.get::<_, Vec<u8>>(0)
830
52
        })?;
831
52
        let raw = String::from_utf8(raw).map_err(into_internal!("utf-8 constraint violated?"))?;
832
52
        Ok(raw)
833
52
    }
834

            
835
    /// Inserts a new authority certificate into the database.
836
    ///
837
    /// Keep in mind that the data in the [`AuthCert`] should correspond to the
838
    /// data found in `data`, as this method performs no parsing.
839
52
    pub(crate) fn insert<I: Iterator<Item = ContentEncoding>>(
840
52
        tx: &Transaction<'_>,
841
52
        encodings: I,
842
52
        cert: &AuthCert,
843
52
        data: &str,
844
52
    ) -> Result<(), DatabaseError> {
845
        // Inserts a new certificate into the meta table.
846
        //
847
        // Parameters:
848
        // :docid - The document id.
849
        // :id_rsa - The identity key fingerprint.
850
        // :sign_rsa - The signing key fingerprint
851
        // :published - The published timestamp.
852
        // :expires - The expires timestamp.
853
52
        let mut stmt = tx.prepare_cached(sql!(
854
52
            "
855
52
            INSERT INTO authority_key_certificate
856
52
            (docid, kp_auth_id_rsa_sha1, kp_auth_sign_rsa_sha1, dir_key_published, dir_key_expires)
857
52
            VALUES
858
52
            (:docid, :id_rsa, :sign_rsa, :published, :expires)
859
52
            ON CONFLICT DO NOTHING
860
52
            "
861
52
        ))?;
862

            
863
52
        let docid = store_insert(tx, data.as_bytes(), encodings)?;
864
52
        stmt.execute(named_params! {
865
52
            ":docid": docid,
866
52
            ":id_rsa": cert.dir_identity_key.to_rsa_identity().as_hex_upper(),
867
52
            ":sign_rsa": cert.dir_signing_key.to_rsa_identity().as_hex_upper(),
868
52
            ":published": Timestamp::from(cert.dir_key_published.0),
869
52
            ":expires": Timestamp::from(cert.dir_key_expires.0),
870
52
        })?;
871

            
872
52
        Ok(())
873
52
    }
874
}
875

            
876
/// Representation of a descriptor from the database.
877
///
878
/// This is different from [`FlavoredDescriptor`] in the sense that it represents
879
/// a row in the `descriptor` table of the database, whereas [`FlavoredDescriptor`]
880
/// represents an agnostic wrapper around the [`tor_netdoc`] equivalent.
881
///
882
/// Yet, it still accepts a [`FlavoredDescriptor`] as a type parameter in order
883
/// to obtain the flavor from it.
884
// TODO DIRMIRROR: Is it possible to change this generic type somehow?
885
// Potentially a const ConsensusFlavor?  After all, this is not a wrapper
886
// type but rather a unit marker which we only use to call ::flavor().
887
// Similar logic probably also applies to ConsensusMeta.
888
#[derive(Educe)]
889
#[educe(Debug, Clone, Copy, PartialEq, Eq, Hash)]
890
pub(crate) struct DescriptorMeta<Flavor> {
891
    /// The document id uniquely identifying the document.
892
    pub docid: DocumentId,
893

            
894
    /// The SHA-1 as found in the signature.
895
    pub sha1: Sha1,
896

            
897
    /// The SHA-256 as found in the signature.
898
    pub sha2: Sha256,
899

            
900
    /// The RSA identity fingerprint, if present.
901
    pub kp_relay_id_rsa_sha1: Option<Sha1>,
902

            
903
    /// Use of the generic for determining the flavor.
904
    flavor: PhantomData<Flavor>,
905

            
906
    /// The SHA-1 of the extra-info document, if present.
907
    pub extra_sha1: Option<Sha1>,
908
}
909

            
910
impl<Flavor: FlavoredDescriptor> DescriptorMeta<Flavor> {
911
    /// Queries a [`DescriptorMeta`] by it's [`DocumentId`], mostly for internal
912
    /// use.
913
    fn query_docid(
914
        tx: &Transaction<'_>,
915
        docid: DocumentId,
916
    ) -> Result<Option<DescriptorMeta<Flavor>>, DatabaseError> {
917
        let mut stmt = tx.prepare_cached(sql!(
918
            "
919
            SELECT docid, sha1, sha2, kp_relay_id_rsa_sha1, extra_sha1
920
            FROM descriptor
921
            WHERE docid = :docid AND flavor = :flavor
922
            "
923
        ))?;
924

            
925
        stmt.query_one(
926
            named_params! {
927
                ":docid": docid,
928
                ":flavor": Flavor::flavor().name()
929
            },
930
            |row| {
931
                Ok(DescriptorMeta::<Flavor> {
932
                    docid: row.get(0)?,
933
                    sha1: row.get(1)?,
934
                    sha2: row.get(2)?,
935
                    kp_relay_id_rsa_sha1: row.get(3)?,
936
                    extra_sha1: row.get(4)?,
937
                    flavor: Default::default(),
938
                })
939
            },
940
        )
941
        .optional()
942
        .map_err(|e| e.into())
943
    }
944

            
945
    /// Inserts a [`FlavoredDescriptor`] into the database.
946
27
    pub(crate) fn insert<I>(
947
27
        tx: &Transaction<'_>,
948
27
        encodings: I,
949
27
        descriptor: &Flavor,
950
27
        data: &str,
951
27
    ) -> Result<(), DatabaseError>
952
27
    where
953
27
        I: Iterator<Item = ContentEncoding>,
954
    {
955
        // Insertion statement of a single descriptor.
956
        //
957
        // Parameters:
958
        // :docid - The document id.
959
        // :sha1 - The SHA-1 as found in the signature.
960
        // :sha256 - The SHA-256 as found in the signature.
961
        // :id_rsa - The RSA identity key fingerprint, if present.
962
        // :flavor - The ConsensusFlavor associated with it.
963
        // :extra_info - The extra-info SHA-1, if present.
964
27
        let mut stmt = tx.prepare_cached(sql!(
965
27
            "
966
27
            INSERT INTO descriptor
967
27
            (docid, sha1, sha2, kp_relay_id_rsa_sha1, flavor, extra_sha1)
968
27
            VALUES
969
27
            (:docid, :sha1, :sha256, :id_rsa, :flavor, :extra_info)
970
27
            "
971
27
        ))?;
972

            
973
27
        let docid = store_insert(tx, data.as_bytes(), encodings)?;
974
27
        stmt.execute(named_params! {
975
27
            ":docid": docid,
976
27
            ":sha1": descriptor.sha1()?,
977
27
            ":sha256": descriptor.sha256()?,
978
27
            ":id_rsa": descriptor.id_rsa().map(|rsa| Sha1(rsa.to_bytes())),
979
27
            ":flavor": Flavor::flavor().name(),
980
27
            ":extra_info": descriptor.extra_info_sha1().map(|extra| Sha1(extra.sha1.0)),
981
        })?;
982

            
983
27
        Ok(())
984
27
    }
985

            
986
    /// Queries the raw data of a [`DescriptorMeta`].
987
    pub(crate) fn data(&self, tx: &Transaction<'_>) -> Result<String, DatabaseError> {
988
        let mut stmt = tx.prepare_cached(sql!("SELECT content FROM store WHERE docid = :docid"))?;
989

            
990
        let raw = stmt.query_one(named_params! {":docid": self.docid}, |row| {
991
            row.get::<_, Vec<u8>>(0)
992
        })?;
993
        let raw = String::from_utf8(raw).map_err(into_internal!("utf-8 constraint violated?"))?;
994
        Ok(raw)
995
    }
996
}
997

            
998
/// A no-op macro just returning the supplied.
999
///
/// The purpose of this macro is to semantically mark [`str`] literals to be
/// SQL statement.
///
/// Keep in mind that the compiler will not notice if you forget this macro.
/// Unfortunately, you have to ensure it yourself.
macro_rules! sql {
    ($s:literal) => {
        $s
    };
}
pub(crate) use sql;
/// Opens a database from disk, creating a [`Pool`] for it.
///
/// This function should be the entry point for all things requiring a database
/// handle, as this function prepares all necessary steps required for operating
/// on the database correctly, such as:
/// * Schema initialization.
/// * Schema upgrade.
/// * Setting connection specific settings.
///
/// # `SQLITE_BUSY` Caveat
///
/// There is a problem with the handling of `SQLITE_BUSY` when opening an
/// SQLite database.  In WAL, opening a database might acquire an exclusive lock
/// for a very short amount of time, in order to perform clean-up from previous
/// connections alongside other tasks for maintaining database integrity?  This
/// means, that opening multiple SQLite databases simultaneously will result in
/// a busy error regardless of a busy handler, as setting a busy handler will
/// require an existing connection, something we are unable to obtain in the
/// first place.
///
/// In order to mitigate this issue, the recommended way in the SQLite community
/// is to simply ensure that database connections are opened sequentially,
/// by urging calling applications to just use a single [`Pool`] instance.
///
/// Testing this is hard unfortunately.
20
pub(crate) fn open<P: AsRef<Path>>(
20
    path: P,
20
) -> Result<Pool<SqliteConnectionManager>, DatabaseError> {
20
    let num_cores = std::thread::available_parallelism()
20
        .unwrap_or(NonZero::new(8).expect("8 == 0?"))
20
        .get() as u32;
20
    let manager = r2d2_sqlite::SqliteConnectionManager::file(&path)
1600
        .with_init(|c| rusqlite::vtab::array::load_module(c));
20
    let pool = Pool::builder().max_size(num_cores).build(manager)?;
20
    rw_tx(&pool, |tx| {
        // Prepare the database, doing the following steps:
        // 1. Checking the database schema.
        // 2. Upgrading (in future) or initializing the database schema (if empty).
20
        let has_arti_dirserver_schema_version = match tx.query_one(
            sql!(
20
                "
20
                SELECT name
20
                FROM sqlite_master
20
                  WHERE type = 'table'
20
                    AND name = 'arti_dirserver_schema_version'
20
                "
            ),
20
            params![],
1
            |_| Ok(()),
        ) {
1
            Ok(()) => true,
19
            Err(rusqlite::Error::QueryReturnedNoRows) => false,
            Err(e) => return Err(DatabaseError::LowLevel(e)),
        };
20
        if has_arti_dirserver_schema_version {
1
            let version = tx.query_one(
1
                sql!("SELECT version FROM arti_dirserver_schema_version WHERE rowid = 1"),
1
                params![],
1
                |row| row.get::<_, String>(0),
            )?;
1
            match version.as_ref() {
                "1" => {}
                unknown => {
1
                    return Err(DatabaseError::IncompatibleSchema {
1
                        version: unknown.into(),
1
                    });
                }
            }
        } else {
19
            tx.execute_batch(V1_SCHEMA)?;
        }
19
        Ok::<_, DatabaseError>(())
20
    })??;
19
    Ok(pool)
20
}
/// Executes a closure `op` with a given read-only [`Transaction`].
///
/// The [`Transaction`] always gets rolled back the moment `op` returns.
///
/// The [`Transaction`] gets initialized with the global pragma options set.
///
/// **The closure shall not perform write operations!**
/// Not only do they get rolled back anyways, but upgrading the [`Transaction`]
/// from a read to a write transaction will lead to other simultaneous write upgrades
/// to fail.  Unfortunately, there is no real programmatic way to ensure this.
38
pub(crate) fn read_tx<U, F>(pool: &Pool<SqliteConnectionManager>, op: F) -> Result<U, DatabaseError>
38
where
38
    F: FnOnce(&Transaction<'_>) -> U,
{
38
    let mut conn = pool.get()?;
38
    conn.execute_batch(GLOBAL_OPTIONS)?;
38
    let tx = conn.transaction_with_behavior(TransactionBehavior::Deferred)?;
38
    let res = op(&tx);
38
    tx.rollback()?;
38
    Ok(res)
38
}
/// Executes a closure `op` with a given read-write [`Transaction`].
///
/// The [`Transaction`] always gets committed the moment `op` returns.
///
/// The [`Transaction`] gets initialized with the global pragma options set.
///
/// The [`Transaction`] gets created with [`TransactionBehavior::Immediate`],
/// meaning it will immediately exist as a write connection, retrying in the
/// case of a [`rusqlite::ErrorCode::DatabaseBusy`] until it failed after 1s.
39
pub(crate) fn rw_tx<U, F>(pool: &Pool<SqliteConnectionManager>, op: F) -> Result<U, DatabaseError>
39
where
39
    F: FnOnce(&Transaction<'_>) -> U,
{
39
    let mut conn = pool.get()?;
39
    conn.execute_batch(GLOBAL_OPTIONS)?;
39
    let tx = conn.transaction_with_behavior(TransactionBehavior::Exclusive)?;
38
    let res = op(&tx);
38
    tx.commit()?;
38
    Ok(res)
39
}
/// Inserts `data` into store while also compressing it with given encodings.
///
/// Returns the [`DocumentId`] of `data`.
///
/// This function inserts `data` into store and also compresses it into all
/// given compression formats.
///
/// Duplicates get re-encoded and replaced in the database, including
/// [`ContentEncoding::Identity`].
864
pub(crate) fn store_insert<I: Iterator<Item = ContentEncoding>>(
864
    tx: &Transaction,
864
    data: &[u8],
864
    encodings: I,
864
) -> Result<DocumentId, DatabaseError> {
    // The statement to insert some data into the store.
    //
    // Parameters:
    // :docid - The docid.
    // :content - The binary data.
864
    let mut store_stmt = tx.prepare_cached(sql!(
864
        "
864
        INSERT INTO store (docid, content)
864
        VALUES
864
        (:docid, :content)
864
        ON CONFLICT DO NOTHING
864
        "
864
    ))?;
    // The statement to insert a compressed document into the metatable.
    //
    // Parameters:
    // :algorithm - The name of the encoding algorithm.
    // :identity_docid - The docid of the plain-text document in the store.
    // :compressed_docid - The docid of the encoded document in the store.
864
    let mut compressed_stmt = tx.prepare_cached(sql!(
864
        "
864
        INSERT INTO compressed_document (algorithm, identity_docid, compressed_docid)
864
        VALUES
864
        (:algorithm, :identity_docid, :compressed_docid)
864
        ON CONFLICT DO NOTHING
864
        "
864
    ))?;
    // Insert the plain document into the store.
864
    let identity_docid = DocumentId::digest(data);
864
    store_stmt.execute(named_params! {
864
        ":docid": identity_docid,
864
        ":content": data
864
    })?;
    // Compress it into all formats and insert it into store and compressed.
864
    for encoding in encodings {
1004
        if encoding == ContentEncoding::Identity {
            // Ignore identity because we inserted that above.
864
            continue;
140
        }
        // We map a compression error to a bug because there is no good reason
        // on why it should fail, given that we compress from memory data to
        // memory data.  Probably because it uses the std::io::Writer interface
        // which itself demands use of std::io::Result.
140
        let compressed = compress(data, encoding).map_err(into_internal!("{encoding} failed?"))?;
140
        let compressed_docid = DocumentId::digest(&compressed);
140
        store_stmt.execute(named_params! {
140
            ":docid": compressed_docid,
140
            ":content": compressed,
140
        })?;
140
        compressed_stmt.execute(named_params! {
140
            ":algorithm": encoding.to_string(),
140
            ":identity_docid": identity_docid,
140
            ":compressed_docid": compressed_docid,
140
        })?;
    }
864
    Ok(identity_docid)
864
}
/// Compresses `data` into a specified [`ContentEncoding`].
///
/// Returns a [`Vec`] containing the encoded data.
145
fn compress(data: &[u8], encoding: ContentEncoding) -> Result<Vec<u8>, std::io::Error> {
145
    match encoding {
1
        ContentEncoding::Identity => Ok(data.to_vec()),
        ContentEncoding::Deflate => {
36
            let mut w = DeflateEncoder::new(Vec::new(), Default::default());
36
            w.write_all(data)?;
36
            w.finish()
        }
        ContentEncoding::Gzip => {
36
            let mut w = GzEncoder::new(Vec::new(), Default::default());
36
            w.write_all(data)?;
36
            w.finish()
        }
36
        ContentEncoding::XZstd => zstd::encode_all(data, Default::default()),
        ContentEncoding::XTorLzma => {
36
            let mut res = Vec::new();
36
            lzma_rs::lzma_compress(&mut Cursor::new(data), &mut res)?;
36
            Ok(res)
        }
    }
145
}
#[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,
        io::Read,
        iter,
        sync::{Arc, Once},
    };
    use flate2::read::{DeflateDecoder, GzDecoder};
    use rusqlite::Connection;
    use strum::IntoEnumIterator;
    use tempfile::tempdir;
    use tor_basic_utils::test_rng::testing_rng;
    use tor_netdoc::doc::netstatus::{md, plain};
    use crate::testdata2::{self, current_consensus_ns};
    use super::*;
    type Plain = plain::NetworkStatusUnverified;
    type Md = md::NetworkStatusUnverified;
    #[test]
    fn open_test() {
        let db_dir = tempdir().unwrap();
        let db_path = db_dir.path().join("db");
        open(&db_path).unwrap();
        let conn = Connection::open(&db_path).unwrap();
        // Check if the version was initialized properly.
        let version = conn
            .query_one(
                "SELECT version FROM arti_dirserver_schema_version WHERE rowid = 1",
                params![],
                |row| row.get::<_, String>(0),
            )
            .unwrap();
        assert_eq!(version, "1");
        // Set the version to something unknown.
        conn.execute(
            "UPDATE arti_dirserver_schema_version SET version = 42",
            params![],
        )
        .unwrap();
        drop(conn);
        assert_eq!(
            open(&db_path).unwrap_err().to_string(),
            "incompatible schema version: 42"
        );
    }
    #[test]
    fn read_tx_test() {
        let db_dir = tempdir().unwrap();
        let db_path = db_dir.path().join("db");
        let pool = open(&db_path).unwrap();
        // Do a write transaction despite forbidden.
        read_tx(&pool, |tx| {
            tx.execute_batch("DELETE FROM arti_dirserver_schema_version")
                .unwrap();
            let e = tx
                .query_one(
                    sql!("SELECT version FROM arti_dirserver_schema_version"),
                    params![],
                    |row| row.get::<_, String>(0),
                )
                .unwrap_err();
            assert_eq!(e, rusqlite::Error::QueryReturnedNoRows);
        })
        .unwrap();
        // Normal check.
        let version: String = read_tx(&pool, |tx| {
            tx.query_one(
                sql!("SELECT version FROM arti_dirserver_schema_version"),
                params![],
                |row| row.get(0),
            )
            .unwrap()
        })
        .unwrap();
        assert_eq!(version, "1");
    }
    #[test]
    fn rw_tx_test() {
        let db_dir = tempdir().unwrap();
        let db_path = db_dir.path().join("db");
        let pool = open(&db_path).unwrap();
        // Do a write transaction.
        rw_tx(&pool, |tx| {
            tx.execute_batch("DELETE FROM arti_dirserver_schema_version")
                .unwrap();
        })
        .unwrap();
        // Check that it was deleted.
        read_tx(&pool, |tx| {
            let e = tx
                .query_one(
                    sql!("SELECT version FROM arti_dirserver_schema_version"),
                    params![],
                    |row| row.get::<_, String>(0),
                )
                .unwrap_err();
            assert_eq!(e, rusqlite::Error::QueryReturnedNoRows);
        })
        .unwrap();
    }
    /// Tests whether our SQLite busy error handling works in normal situations.
    ///
    /// A normal situations means a situation where a lock is never held for
    /// more than 1000ms.  In our case, we will work with two threads.
    /// t1 will acquire an exclusive lock and inform t2 about it.  t2 waits
    /// until t1 has acquired this lock and then immediately informs t1, that
    /// it will now wait for a lock too.  Now, t1 will immediately terminate,
    /// thereby releasing the lock and leading t2 to eventually acquire it.
    #[test]
    fn rw_tx_busy_timeout_working() {
        let db_dir = tempdir().unwrap();
        let db_path = db_dir.path().join("db");
        let pool = open(db_path).unwrap();
        // t2 will wait on this before it starts doing stuff.
        let t1_acquired_lock = Arc::new(Once::new());
        // t1 will wait on this in order to terminate properly.
        let t2_is_waiting = Arc::new(Once::new());
        let t1 = std::thread::spawn({
            let pool = pool.clone();
            let t1_acquired_lock = t1_acquired_lock.clone();
            let t2_is_waiting = t2_is_waiting.clone();
            move || {
                rw_tx(&pool, move |_tx| {
                    // Inform t2 we have write lock.
                    t1_acquired_lock.call_once(|| ());
                    println!("t1 acquired write lock");
                    // Wait for t2 to start waiting.
                    t2_is_waiting.wait();
                })
                .unwrap();
                println!("t2 released write lock");
            }
        });
        println!("t2 waits for t1 to acquire write lock");
        t1_acquired_lock.wait();
        t2_is_waiting.call_once(|| ());
        rw_tx(&pool, |_| ()).unwrap();
        println!("t2 acquired and released write lock");
        t1.join().unwrap();
    }
    /// Tests whether our SQLite busy error handlings fails as expected.
    ///
    /// We configure SQLite to fail after 1000ms.  This test works with two
    /// threads.  t1 will acquire an exclusive lock on the database and will
    /// inform t2 about it, which itself will wait until t1 has acquired the
    /// lock.  t2 will then immediately try to also obtain an exclusive lock,
    /// which should fail after about 1000ms.  After the failure, t2 informs
    /// t1 that it has failed, causing t1 to terminate.
    #[test]
    fn rw_tx_busy_timeout_busy() {
        let db_dir = tempdir().unwrap();
        let db_path = db_dir.path().join("db");
        let pool = open(db_path).unwrap();
        // t2 will wait on this before it starts doing stuff.
        let t1_acquired_lock = Arc::new(Once::new());
        // t1 will wait on this in order to terminate properly.
        let t2_gave_up = Arc::new(Once::new());
        let t1 = std::thread::spawn({
            let pool = pool.clone();
            let t1_acquired_lock = t1_acquired_lock.clone();
            let t2_gave_up = t2_gave_up.clone();
            move || {
                rw_tx(&pool, move |_tx| {
                    // Inform t2 we have the write lock.
                    t1_acquired_lock.call_once(|| ());
                    println!("t1 acquired write lock");
                    // Wait for t2 to give up before we release (how mean from us).
                    t2_gave_up.wait();
                })
                .unwrap();
                println!("t1 released write lock");
            }
        });
        println!("t2 waits for t1 to acquire write lock");
        t1_acquired_lock.wait();
        let e = rw_tx(&pool, |_| ()).unwrap_err();
        assert_eq!(
            e.to_string(),
            "low-level rusqlite error: database is locked"
        );
        println!("t2 gave up on acquiring write lock");
        t2_gave_up.call_once(|| ());
        t1.join().unwrap();
    }
    #[test]
    fn store_insert_test() {
        let db_dir = tempdir().unwrap();
        let db_path = db_dir.path().join("db");
        open(&db_path).unwrap();
        let mut conn = Connection::open(&db_path).unwrap();
        let tx = conn.transaction().unwrap();
        let docid = store_insert(&tx, "foobar".as_bytes(), ContentEncoding::iter()).unwrap();
        assert_eq!(
            docid,
            "C3AB8FF13720E8AD9047DD39466B3C8974E592C2FA383D4A3960714CAEF0C4F2"
        );
        let res = tx
            .query_one(
                sql!(
                    "
                    SELECT content
                    FROM store
                    WHERE docid = 'C3AB8FF13720E8AD9047DD39466B3C8974E592C2FA383D4A3960714CAEF0C4F2'
                    "
                ),
                params![],
                |row| row.get::<_, Vec<u8>>(0),
            )
            .unwrap();
        assert_eq!(res, "foobar".as_bytes());
        let mut stmt = tx.prepare_cached(sql!(
            "
            SELECT algorithm
            FROM compressed_document
            WHERE identity_docid = 'C3AB8FF13720E8AD9047DD39466B3C8974E592C2FA383D4A3960714CAEF0C4F2'
            "
        )).unwrap();
        let algorithms = stmt
            .query_map(params![], |row| row.get::<_, String>(0))
            .unwrap();
        let algorithms = algorithms.map(|x| x.unwrap()).collect::<HashSet<_>>();
        assert_eq!(
            algorithms,
            HashSet::from([
                "deflate".to_string(),
                "gzip".to_string(),
                "x-zstd".to_string(),
                "x-tor-lzma".to_string()
            ])
        );
        // Now insert the same thing a second time again and see whether the
        // ON CONFLICT magic works.
        let docid_second = store_insert(&tx, "foobar".as_bytes(), ContentEncoding::iter()).unwrap();
        assert_eq!(docid, docid_second);
        // Remove a few compressed entries and get them again.
        let n = tx
            .execute(
                sql!(
                    "
                    DELETE FROM
                    compressed_document
                    WHERE algorithm IN ('deflate', 'x-zstd')
                    "
                ),
                params![],
            )
            .unwrap();
        assert_eq!(n, 2);
        let docid_third = store_insert(&tx, "foobar".as_bytes(), ContentEncoding::iter()).unwrap();
        assert_eq!(docid, docid_third);
        let algorithms = stmt
            .query_map(params![], |row| row.get::<_, String>(0))
            .unwrap();
        let algorithms = algorithms.map(|x| x.unwrap()).collect::<HashSet<_>>();
        assert_eq!(
            algorithms,
            HashSet::from([
                "deflate".to_string(),
                "gzip".to_string(),
                "x-zstd".to_string(),
                "x-tor-lzma".to_string()
            ])
        );
    }
    #[test]
    fn compress_test() {
        /// Asserts that `res` contains `encoding`.
        fn contains(encoding: ContentEncoding, res: &[(ContentEncoding, Vec<u8>)]) {
            assert!(res.iter().any(|x| x.0 == encoding));
        }
        const INPUT: &[u8] = "foobar".as_bytes();
        // Check whether everything was encoded.
        let res = ContentEncoding::iter()
            .map(|encoding| (encoding, compress(INPUT, encoding).unwrap()))
            .collect::<Vec<_>>();
        assert_eq!(res.len(), 5);
        contains(ContentEncoding::Identity, &res);
        contains(ContentEncoding::Deflate, &res);
        contains(ContentEncoding::Gzip, &res);
        contains(ContentEncoding::XTorLzma, &res);
        contains(ContentEncoding::XZstd, &res);
        // Check if we can decode it.
        for (encoding, compressed) in res {
            let mut decompressed = Vec::new();
            match encoding {
                ContentEncoding::Identity => decompressed = compressed,
                ContentEncoding::Deflate => {
                    DeflateDecoder::new(Cursor::new(compressed))
                        .read_to_end(&mut decompressed)
                        .unwrap();
                }
                ContentEncoding::Gzip => {
                    GzDecoder::new(Cursor::new(compressed))
                        .read_to_end(&mut decompressed)
                        .unwrap();
                }
                ContentEncoding::XTorLzma => {
                    lzma_rs::lzma_decompress(&mut Cursor::new(compressed), &mut decompressed)
                        .unwrap();
                }
                ContentEncoding::XZstd => {
                    decompressed = zstd::decode_all(Cursor::new(compressed)).unwrap();
                }
            }
            assert_eq!(decompressed, INPUT);
        }
    }
    /// Verify that the insertion of a consensus works.
    ///
    /// For this, we do not use the test database but rather a fresh one and
    /// call ConsensusMeta::insert().  After, we verify that the consensus
    /// can be queried as well as that the missing descriptors are properly
    /// calculated.
    #[test]
    fn consensus_insert() {
        let pool = open("").unwrap();
        let mut conn = pool.get().unwrap();
        let tx = conn.transaction().unwrap();
        let (body, sigs, data) = current_consensus_ns();
        let meta = ConsensusMeta::<Plain>::insert(
            &tx,
            iter::once(ContentEncoding::Identity),
            (&body, &sigs),
            data,
        )
        .unwrap();
        assert_eq!(
            meta,
            ConsensusMeta::<Plain> {
                docid: Sha256::digest(data.as_bytes()),
                sha3_256: testdata2::consensus_sha3(data),
                valid_after: body.preamble.lifetime.valid_after.0.into(),
                fresh_until: body.preamble.lifetime.fresh_until.0.into(),
                valid_until: body.preamble.lifetime.valid_until.0.into(),
                flavor: Default::default()
            }
        );
        let meta2 = ConsensusMeta::<Plain>::query(&tx).unwrap();
        assert_eq!(meta2, vec![meta]);
        let missing_descs = meta.missing_routers(&tx, iter::empty(), None).unwrap();
        let missing_descs2 = body.routers.iter().map(|r| Sha1(*r.doc_digest())).collect();
        assert_eq!(missing_descs, missing_descs2);
    }
    /// Tests whether the timeout computation lies within the proper interval.
    ///
    /// Because this involves randomness, it performs the test several thousand
    /// times.  This should be okay performance wise, as it takes about ~250ms
    /// with a debug build on my machine.
    #[test]
    fn sync_timeout() {
        // We repeat the tests a few thousand times to go over many random values.
        let docid = Sha256::digest(testdata2::current_consensus_ns().2.as_bytes());
        let lifetime = testdata2::current_consensus_ns().0.preamble.lifetime;
        let sha3_256 = testdata2::consensus_sha3(testdata2::current_consensus_ns().2);
        let cons = ConsensusMeta::<Plain> {
            docid,
            sha3_256,
            valid_after: lifetime.valid_after.0.into(),
            fresh_until: lifetime.fresh_until.0.into(),
            valid_until: lifetime.valid_until.0.into(),
            flavor: Default::default(),
        };
        for _ in 0..10000 {
            let when = cons.ttl(&mut testing_rng());
            assert!(when >= lifetime.fresh_until.0.into());
            // Computes the half between fresh_until and valid_until.
            assert!(
                when <= (lifetime.fresh_until.0
                    + (lifetime
                        .valid_until
                        .0
                        .duration_since(lifetime.fresh_until.0)
                        .unwrap()
                        / 2))
                    .into()
            );
        }
    }
    /// Tests whether the missing router descriptor queue is computed properly.
    ///
    /// For this, we remove existing router descriptors from the database and
    /// see whether they are determined as missing properly.
    #[test]
    fn missing_descriptors() {
        let pool = testdata2::test_db();
        let meta = read_tx(&pool, ConsensusMeta::<Plain>::query)
            .unwrap()
            .unwrap()[0];
        // Ensure that the returned consensus matches the one from testdata2.
        assert_eq!(
            meta.docid,
            DocumentId::digest(testdata2::current_consensus_ns().2.as_bytes())
        );
        // Delete a single router descriptor, so we can determine a missing one
        // using it.
        let removed_descriptor = *testdata2::current_consensus_ns().0.routers[0].doc_digest();
        let removed_descriptor = Sha1::from(removed_descriptor);
        pool.get()
            .unwrap()
            .execute(
                sql!(
                    "
                    DELETE FROM descriptor
                    WHERE sha1 = ?1
                    "
                ),
                params![removed_descriptor],
            )
            .unwrap();
        // Only one should be returned.
        let missing_routers = read_tx(&pool, |tx| meta.missing_routers(tx, iter::empty(), None))
            .unwrap()
            .unwrap();
        assert_eq!(missing_routers, HashSet::from([removed_descriptor]));
        // None should be returned if we exclude the descriptor we just removed.
        let missing_routers = read_tx(&pool, |tx| {
            meta.missing_routers(tx, iter::once(removed_descriptor), None)
        })
        .unwrap()
        .unwrap();
        assert!(missing_routers.is_empty());
        // If we delete all router descriptors we have, we should get all.
        rw_tx(&pool, |tx| {
            tx.execute(sql!("DELETE FROM descriptor"), params![])
        })
        .unwrap()
        .unwrap();
        // Now all should be returned; we verify this by checking that the
        // result is present in all_descriptors, which is a superset.
        let missing_routers = read_tx(&pool, |tx| meta.missing_routers(tx, iter::empty(), None))
            .unwrap()
            .unwrap();
        // This is a superset of missing_routers because it includes router
        // descriptors that are not a part of the current consensus.
        let all_descriptors = testdata2::current_router_descs()
            .iter()
            .map(|x| Sha1::from(x.1.hashes.sha1.unwrap()))
            .collect::<HashSet<_>>();
        assert!(
            missing_routers
                .iter()
                .all(|sha1| all_descriptors.contains(sha1))
        );
        // If we exclude one random descriptor, only that one should be missing.
        let to_exclude = missing_routers.iter().copied().next().unwrap();
        let missing_routers2 = read_tx(&pool, |tx| {
            meta.missing_routers(tx, iter::once(to_exclude), None)
        })
        .unwrap()
        .unwrap();
        assert_eq!(
            missing_routers
                .difference(&missing_routers2)
                .collect::<HashSet<_>>(),
            [&to_exclude].into()
        );
        // If we exclude all descriptors, it should be empty too.
        let missing_routers = read_tx(&pool, |tx| {
            meta.missing_routers(tx, all_descriptors.iter().copied(), None)
        })
        .unwrap()
        .unwrap();
        assert!(missing_routers.is_empty());
    }
    /// Tests whether or not the missing descriptors are actually random.
    #[test]
    fn missing_descriptors_are_random() {
        let pool = testdata2::test_db();
        rw_tx(&pool, |tx| {
            tx.execute(sql!("DELETE FROM descriptor"), ()).unwrap();
            let meta = ConsensusMeta::<Plain>::query(tx).unwrap()[0];
            // Ensure there are more than 1 missing descriptors now.
            let n = meta.missing_routers(tx, iter::empty(), None).unwrap().len();
            assert!(n > 1);
            let mut prev = HashSet::new();
            let mut randomness_works = false;
            for _ in 0..100 {
                let cur = meta.missing_routers(tx, iter::empty(), Some(1)).unwrap();
                if prev != cur {
                    randomness_works = true;
                    break;
                }
                prev = cur;
            }
            assert!(randomness_works);
        })
        .unwrap();
    }
    /// Tests whether the RANDOM() calls are executed before the ordering so
    /// that we have stability.
    #[test]
    fn missing_routers_monotonically_increasing() {
        let pool = testdata2::test_db();
        rw_tx(&pool, |tx| {
            let meta = ConsensusMeta::<Plain>::query(tx).unwrap();
            tx.execute(sql!("DELETE FROM descriptor"), ()).unwrap();
            let mut stmt = tx
                .prepare_cached(ConsensusMeta::<Plain>::MISSING_ROUTERS_QUERY)
                .unwrap();
            let empty = Rc::new(Vec::<Value>::new());
            let res = stmt
                .query_map(params![meta[0].docid, empty, -1], |row| {
                    row.get::<_, i64>(1)
                })
                .unwrap()
                .collect::<Result<Vec<_>, _>>()
                .unwrap();
            // Ensure there is more than 1 missing descriptor because we can
            // only test ordering if n >= 2.
            assert!(res.len() > 1);
            // Verify that the calls are monotonically increasing.
            assert!(res.is_sorted());
        })
        .unwrap();
    }
    /// Tests whether the missing extra-info documents are computed properly.
    // TODO DIRMIRROR: Expand on this once we have proper extra-info support.
    #[test]
    fn missing_extra_infos() {
        let pool = testdata2::test_db();
        let meta = read_tx(&pool, ConsensusMeta::<Plain>::query)
            .unwrap()
            .unwrap()[0];
        // Ensure that the returned consensus matches the one from testdata2.
        assert_eq!(
            meta.docid,
            DocumentId::digest(testdata2::current_consensus_ns().2.as_bytes())
        );
        // We should have no missing extra-infos.
        let missing_extras = read_tx(&pool, |tx| meta.missing_extras(tx, iter::empty(), None))
            .unwrap()
            .unwrap();
        assert!(missing_extras.is_empty());
        // TODO DIRMIRROR: Once we have support for extra-info's, add a test
        // for this here.  Right now, testing this is pretty useless as we
        // cannot add it nicely to the testdata2 module if there isn't even
        // an ExtraInfo struct from tor-netdoc.
    }
    /// Tests whether the missing micro descriptor queue is computed properly.
    ///
    /// For this, we remove existing micro descriptors from the database and
    /// see whether they are determined as missing properly.
    #[test]
    fn missing_micro_descriptors() {
        let pool = testdata2::test_db();
        let meta = read_tx(&pool, ConsensusMeta::<Md>::query).unwrap().unwrap()[0];
        // Ensure that the returned consensus matches the one from testdata2.
        assert_eq!(
            meta.docid,
            DocumentId::digest(testdata2::current_consensus_md().2.as_bytes())
        );
        // Delete a single router descriptor, so we can determine a missing one
        // using it.
        let removed_descriptor = *testdata2::current_consensus_md().0.routers[0].doc_digest();
        let removed_descriptor = Sha256::from(removed_descriptor);
        pool.get()
            .unwrap()
            .execute(
                sql!(
                    "
                    DELETE FROM descriptor
                    WHERE sha2 = ?1
                    "
                ),
                params![removed_descriptor],
            )
            .unwrap();
        // Only one should be returned.
        let missing_micros = read_tx(&pool, |tx| meta.missing_micros(tx, iter::empty(), None))
            .unwrap()
            .unwrap();
        assert_eq!(missing_micros, HashSet::from([removed_descriptor]));
        // If we delete all micro descriptors we have, we should get all.
        rw_tx(&pool, |tx| {
            tx.execute(sql!("DELETE FROM descriptor"), params![])
        })
        .unwrap()
        .unwrap();
        // Now all should be returned; we verify this by checking that the
        // result is present in all_descriptors, which is a superset.
        let missing_micros = read_tx(&pool, |tx| meta.missing_micros(tx, iter::empty(), None))
            .unwrap()
            .unwrap();
        // This is a superset of missing_micros because it includes micro
        // descriptors that are not a part of the current consensus.
        let all_descriptors = testdata2::current_micro_descs()
            .iter()
            .map(|x| Sha256::digest(x.1.as_bytes()))
            .collect::<HashSet<_>>();
        assert!(
            missing_micros
                .iter()
                .all(|sha2| all_descriptors.contains(sha2))
        );
    }
}