1
//! Declare an error type for the tor-dirmgr crate.
2

            
3
use std::error::Error as StdError;
4
use std::sync::Arc;
5

            
6
use crate::DocSource;
7
use fs_mistrust::anon_home::PathExt as _;
8
use futures::task::SpawnError;
9
use thiserror::Error;
10
use tor_error::{ErrorKind, HasKind};
11
use tor_persist::FsMistrustErrorExt as _;
12

            
13
/// An error originated by the directory manager code
14
#[derive(Error, Debug, Clone)]
15
#[non_exhaustive]
16
pub enum Error {
17
    /// We received a document we didn't want at all.
18
    #[error("Received an object we didn't ask for: {0}")]
19
    Unwanted(&'static str),
20
    /// The NetDir we downloaded is older than the one we already have.
21
    #[error("Downloaded netdir is older than the one we have")]
22
    NetDirOlder,
23
    /// This DirMgr doesn't support downloads.
24
    #[error("Tried to download information on a DirMgr with no download support")]
25
    NoDownloadSupport,
26
    /// We couldn't read something from disk that we should have been
27
    /// able to read.
28
    #[error("Corrupt cache: {0}")]
29
    CacheCorruption(&'static str),
30
    /// rusqlite gave us an error.
31
    #[error("Error from sqlite database")]
32
    SqliteError(#[source] Arc<rusqlite::Error>),
33
    /// Error while creating a read-only store.
34
    #[error("Failed to create read-only store")]
35
    ReadOnlyStorage(#[from] ReadOnlyStorageError),
36
    /// A schema version that says we can't read it.
37
    #[error("Unrecognized data storage schema v{schema}. (We support v{supported})")]
38
    UnrecognizedSchema {
39
        /// The schema version in the database
40
        schema: u32,
41
        /// The schema that we actually support.
42
        supported: u32,
43
    },
44
    /// User requested an operation that required a usable
45
    /// bootstrapped directory, but we didn't have one.
46
    #[error("Directory not present or not up-to-date")]
47
    DirectoryNotPresent,
48
    /// A consensus document is signed by an unrecognized authority set.
49
    #[error("Authorities on consensus are not the ones we expect")]
50
    UnrecognizedAuthorities,
51
    /// A directory manager has been dropped; background tasks can exit too.
52
    #[error("Dirmgr has been dropped; background tasks exiting")]
53
    ManagerDropped,
54
    /// We made a bunch of attempts, but weren't unable to advance the
55
    /// state of a download.
56
    #[error("Unable to finish bootstrapping a directory")]
57
    CantAdvanceState,
58
    /// Error while accessing a lockfile.
59
    #[error("Unable to access lock file")]
60
    LockFile(Arc<std::io::Error>),
61
    /// Error while accessing a file in the store.
62
    #[error("Error while {action} cache file {}", fname.anonymize_home())]
63
    CacheFile {
64
        /// What we were doing when we encountered the error.
65
        action: &'static str,
66
        /// The file that we were trying to access.
67
        fname: std::path::PathBuf,
68
        /// The underlying IO error.
69
        #[source]
70
        error: Arc<std::io::Error>,
71
    },
72
    /// An error given by the consensus diff crate.
73
    #[error("Problem applying consensus diff")]
74
    ConsensusDiffError(#[from] tor_consdiff::Error),
75
    /// Invalid UTF8 in directory response.
76
    #[error("Invalid utf-8 from directory server")]
77
    BadUtf8FromDirectory(#[source] std::string::FromUtf8Error),
78
    /// Invalid UTF8 from our cache.
79
    #[error("Invalid utf-8 in directory cache")]
80
    BadUtf8InCache(#[source] std::str::Utf8Error),
81
    /// Invalid hexadecimal value in the cache.
82
    #[error("Invalid hexadecimal id in directory cache")]
83
    BadHexInCache(#[source] hex::FromHexError),
84
    /// Invalid json value in the cache
85
    #[error("Invalid JSON in directory cache")]
86
    BadJsonInCache(#[source] Arc<serde_json::Error>),
87
    /// We were unable to parse a document.
88
    #[error("Parsing error in document")]
89
    ParseError {
90
        /// Where the document came from.
91
        ///
92
        /// (We keep this, rather than using the "file" part of
93
        /// [`ParseError`](tor_netdoc::parse2::ParseError),
94
        /// because we need to extract the actual mirror who gave us this document
95
        /// so we can blame them if it's invalid.)
96
        source: DocSource,
97
        /// What error we got.
98
        #[source]
99
        cause: tor_netdoc::parse2::ParseError,
100
    },
101
    /// We were unable to verify a parsed document.
102
    #[error("Invalid document from {source}")]
103
    VerifyError {
104
        /// Where the document came from.
105
        source: DocSource,
106
        /// What error we got.
107
        #[source]
108
        cause: tor_netdoc::parse2::VerifyFailed,
109
    },
110
    /// An error indicating that the consensus could not be validated.
111
    ///
112
    /// This kind of error is only returned during the certificate fetching
113
    /// state; it indicates that a consensus which previously seemed to be
114
    /// plausible has turned out to be wrong after we got the certificates.
115
    #[error("Could not validate consensus from {source}")]
116
    ConsensusInvalid {
117
        /// Where the document came from.
118
        source: DocSource,
119
        /// What error we got.
120
        #[source]
121
        cause: tor_netdoc::doc::netstatus::ConsensusVerifyFailed,
122
    },
123
    /// An error caused by an expired or not-yet-valid object.
124
    #[error("Directory object expired or not yet valid")]
125
    UntimelyObject(#[from] tor_checkable::TimeValidityError),
126
    /// An error given by dirclient
127
    #[error("Problem downloading directory object")]
128
    DirClientError(#[from] tor_dirclient::Error),
129
    /// An error given by the checkable crate.
130
    #[error("Invalid signatures")]
131
    SignatureError(#[source] Arc<signature::Error>),
132
    /// An attempt was made to bootstrap a `DirMgr` created in offline mode.
133
    #[error("Tried to bootstrap a DirMgr that was configured as offline-only")]
134
    OfflineMode,
135
    /// A problem accessing our cache directory (for example, no such directory)
136
    #[error("Problem accessing cache directory")]
137
    CacheAccess(#[from] fs_mistrust::Error),
138
    /// A problem accessing our cache directory (for example, no such directory)
139
    ///
140
    /// This variant name is misleading - see the docs for [`fs_mistrust::Error`].
141
    /// Please use [`Error::CacheAccess`] instead.
142
    #[error("Problem accessing cache directory")]
143
    #[deprecated = "use Error::CacheAccess instead"]
144
    CachePermissions(#[source] fs_mistrust::Error),
145
    /// Unable to spawn task
146
    #[error("Unable to spawn {spawning}")]
147
    Spawn {
148
        /// What we were trying to spawn
149
        spawning: &'static str,
150
        /// What happened when we tried to spawn it
151
        #[source]
152
        cause: Arc<SpawnError>,
153
    },
154

            
155
    /// Other error from an external directory provider
156
    #[error("Error from external directory provider")]
157
    ExternalDirProvider {
158
        /// What happened
159
        #[source]
160
        cause: Arc<dyn std::error::Error + Send + Sync + 'static>,
161

            
162
        /// The kind
163
        kind: ErrorKind,
164
    },
165

            
166
    /// A programming problem, either in our code or the code calling it.
167
    #[error("Internal programming issue")]
168
    Bug(#[from] tor_error::Bug),
169
}
170

            
171
impl From<signature::Error> for Error {
172
    fn from(err: signature::Error) -> Self {
173
        Self::SignatureError(Arc::new(err))
174
    }
175
}
176

            
177
impl From<tor_rtcompat::scheduler::SleepError> for Error {
178
    fn from(err: tor_rtcompat::scheduler::SleepError) -> Self {
179
        use tor_rtcompat::scheduler::SleepError::*;
180
        match err {
181
            ScheduleDropped => Error::ManagerDropped,
182
            e => tor_error::into_internal!("Unexpected sleep error")(e).into(),
183
        }
184
    }
185
}
186

            
187
impl AsRef<dyn StdError + 'static> for Error {
188
    fn as_ref(&self) -> &(dyn StdError + 'static) {
189
        self
190
    }
191
}
192

            
193
/// The effect that a given error has on our bootstrapping process
194
#[derive(Copy, Clone, Debug)]
195
pub(crate) enum BootstrapAction {
196
    /// The error isn't fatal.  We should blame it on its source (if any), and
197
    /// continue bootstrapping.
198
    Nonfatal,
199
    /// The error requires that we restart bootstrapping from scratch.  
200
    ///
201
    /// This kind of error typically means that we've downloaded a consensus
202
    /// that turned out to be useless at a later stage, and so we need to
203
    /// restart the downloading process from the beginning, by downloading a
204
    /// fresh one.
205
    Reset,
206
    /// The error indicates that we cannot bootstrap, and should stop trying.
207
    ///
208
    /// These are typically internal programming errors, filesystem access
209
    /// problems, directory manager shutdown, and the like.
210
    Fatal,
211
}
212

            
213
impl Error {
214
    /// Construct a new `Error` from a `SpawnError`.
215
    pub(crate) fn from_spawn(spawning: &'static str, err: SpawnError) -> Error {
216
        Error::Spawn {
217
            spawning,
218
            cause: Arc::new(err),
219
        }
220
    }
221

            
222
    /// Construct a new `Error` from `ParseError`.
223
    ///
224
    /// Also takes a source so that we can keep track of where the document came from.
225
1
    pub(crate) fn from_parse(source: DocSource, cause: tor_netdoc::parse2::ParseError) -> Error {
226
1
        Error::ParseError { source, cause }
227
1
    }
228

            
229
    /// Construct a new `Error` from `std::io::Error` for an error that occurred
230
    /// while locking a file.
231
    pub(crate) fn from_lockfile(err: std::io::Error) -> Error {
232
        Error::LockFile(Arc::new(err))
233
    }
234

            
235
    /// Return true if this error is serious enough that we should mark this
236
    /// cache as having failed.
237
    pub(crate) fn indicates_cache_failure(&self) -> bool {
238
        #[allow(deprecated)]
239
        match self {
240
            // These indicate a problem from the cache.
241
            Error::Unwanted(_)
242
            | Error::UnrecognizedAuthorities
243
            | Error::BadUtf8FromDirectory(_)
244
            | Error::ConsensusDiffError(_)
245
            | Error::SignatureError(_)
246
            | Error::ConsensusInvalid { .. }
247
            | Error::UntimelyObject(_) => true,
248

            
249
            // These errors cannot come from a directory cache.
250
            Error::NoDownloadSupport
251
            | Error::CacheCorruption(_)
252
            | Error::CachePermissions(_)
253
            | Error::CacheAccess(_)
254
            | Error::SqliteError(_)
255
            | Error::ReadOnlyStorage(_)
256
            | Error::UnrecognizedSchema { .. }
257
            | Error::DirectoryNotPresent
258
            | Error::ManagerDropped
259
            | Error::CantAdvanceState
260
            | Error::LockFile { .. }
261
            | Error::CacheFile { .. }
262
            | Error::BadUtf8InCache(_)
263
            | Error::BadHexInCache(_)
264
            | Error::OfflineMode
265
            | Error::Spawn { .. }
266
            | Error::NetDirOlder
267
            | Error::BadJsonInCache(_)
268
            | Error::Bug(_) => false,
269

            
270
            // For this one, we delegate.
271
            Error::DirClientError(e) => e.should_retire_circ(),
272

            
273
            // TODO: This one is special.  It could mean that the directory
274
            // cache is serving us bad unparsable stuff, or it could mean that
275
            // for some reason we're unable to parse a real legit document.
276
            //
277
            // If the cache is serving us something unparsable, it might be
278
            // because the cache doesn't know all the same parsing rules for the
279
            // object that we know.  That case might need special handling to
280
            // avoid erroneously avoiding a good cache... especially if the document
281
            // is one that the cache could be tricked into serving us.
282
            Error::ParseError { .. } | Error::VerifyError { .. } => true,
283

            
284
            // We can never see this kind of error from within the crate.
285
            Error::ExternalDirProvider { .. } => false,
286
        }
287
    }
288

            
289
    /// If this operation is associated with a particular directory cache server,
290
    /// return a [`tor_dirclient::SourceInfo`] describing which one.
291
    pub(crate) fn cache_info(&self) -> Option<&tor_dirclient::SourceInfo> {
292
        #[allow(deprecated)]
293
        match self {
294
            Error::Unwanted(_)
295
            | Error::NetDirOlder
296
            | Error::NoDownloadSupport
297
            | Error::CacheCorruption(_)
298
            | Error::SqliteError(_)
299
            | Error::ReadOnlyStorage(_)
300
            | Error::UnrecognizedSchema { .. }
301
            | Error::DirectoryNotPresent
302
            | Error::UnrecognizedAuthorities
303
            | Error::ManagerDropped
304
            | Error::CantAdvanceState
305
            | Error::LockFile(_)
306
            | Error::CacheFile { .. }
307
            | Error::ConsensusDiffError(_)
308
            | Error::BadUtf8FromDirectory(_)
309
            | Error::BadUtf8InCache(_)
310
            | Error::BadHexInCache(_)
311
            | Error::BadJsonInCache(_)
312
            | Error::UntimelyObject(_)
313
            | Error::SignatureError(_)
314
            | Error::OfflineMode
315
            | Error::CacheAccess(_)
316
            | Error::CachePermissions(_)
317
            | Error::Spawn { .. }
318
            | Error::ExternalDirProvider { .. }
319
            | Error::Bug(_) => None,
320

            
321
            Error::DirClientError(tor_dirclient::Error::RequestFailed(e)) => e.source.as_ref(),
322
            Error::DirClientError(_) => None,
323

            
324
            Error::ConsensusInvalid { source, .. }
325
            | Error::ParseError { source, .. }
326
            | Error::VerifyError { source, .. } => match source {
327
                DocSource::LocalCache => None,
328
                DocSource::DirServer { source } => source.as_ref(),
329
            },
330
        }
331
    }
332

            
333
    /// Return information about which directory cache caused this error, if
334
    /// this error contains one.
335
    pub(crate) fn responsible_cache(&self) -> Option<&tor_dirclient::SourceInfo> {
336
        match self {
337
            Error::ConsensusInvalid {
338
                source: DocSource::DirServer { source },
339
                ..
340
            } => source.as_ref(),
341
            _ => None,
342
        }
343
    }
344

            
345
    /// Return information about what to do if this error occurs during the
346
    /// bootstrapping process.
347
    #[allow(dead_code)]
348
    pub(crate) fn bootstrap_action(&self) -> BootstrapAction {
349
        #[allow(deprecated)]
350
        match self {
351
            Error::Unwanted(_)
352
            | Error::NetDirOlder
353
            | Error::UnrecognizedAuthorities
354
            | Error::ConsensusDiffError(_)
355
            | Error::BadUtf8FromDirectory(_)
356
            | Error::UntimelyObject(_)
357
            | Error::DirClientError(_)
358
            | Error::SignatureError(_)
359
            | Error::ParseError { .. }
360
            | Error::VerifyError { .. } => BootstrapAction::Nonfatal,
361

            
362
            Error::ConsensusInvalid { .. } | Error::CantAdvanceState => BootstrapAction::Reset,
363

            
364
            Error::NoDownloadSupport
365
            | Error::OfflineMode
366
            | Error::CacheCorruption(_)
367
            | Error::SqliteError(_)
368
            | Error::ReadOnlyStorage(_)
369
            | Error::UnrecognizedSchema { .. }
370
            | Error::ManagerDropped
371
            | Error::LockFile { .. }
372
            | Error::CacheFile { .. }
373
            | Error::BadUtf8InCache(_)
374
            | Error::BadHexInCache(_)
375
            | Error::CachePermissions(_)
376
            | Error::CacheAccess(_)
377
            | Error::Spawn { .. }
378
            | Error::BadJsonInCache(_)
379
            | Error::ExternalDirProvider { .. } => BootstrapAction::Fatal,
380

            
381
            // These should actually be impossible during the bootstrap process.
382
            Error::DirectoryNotPresent | Error::Bug(_) => BootstrapAction::Fatal,
383
        }
384
    }
385
}
386

            
387
impl From<rusqlite::Error> for Error {
388
    fn from(err: rusqlite::Error) -> Self {
389
        use ErrorKind as EK;
390
        let kind = sqlite_error_kind(&err);
391
        match kind {
392
            EK::Internal | EK::BadApiUsage => {
393
                // TODO: should this be a .is_bug() on EK ?
394
                tor_error::Bug::from_error(kind, err, "sqlite detected bug").into()
395
            }
396
            _ => Self::SqliteError(Arc::new(err)),
397
        }
398
    }
399
}
400

            
401
impl HasKind for Error {
402
    fn kind(&self) -> ErrorKind {
403
        use Error as E;
404
        use ErrorKind as EK;
405
        #[allow(deprecated)]
406
        match self {
407
            E::Unwanted(_) => EK::TorProtocolViolation,
408
            E::NoDownloadSupport => EK::NotImplemented,
409
            E::CacheCorruption(_) => EK::CacheCorrupted,
410
            E::CachePermissions(e) => e.cache_error_kind(),
411
            E::CacheAccess(e) => e.cache_error_kind(),
412
            E::SqliteError(e) => sqlite_error_kind(e),
413
            E::ReadOnlyStorage(_) => EK::LocalResourceAlreadyInUse,
414
            E::UnrecognizedSchema { .. } => EK::CacheCorrupted,
415
            E::BadJsonInCache(_) => EK::CacheCorrupted,
416
            E::DirectoryNotPresent => EK::DirectoryExpired,
417
            E::NetDirOlder => EK::TorDirectoryError,
418
            E::BadUtf8FromDirectory(_) => EK::TorProtocolViolation,
419
            E::BadUtf8InCache(_) => EK::CacheCorrupted,
420
            E::BadHexInCache(_) => EK::CacheCorrupted,
421
            E::UnrecognizedAuthorities => EK::TorProtocolViolation,
422
            E::ManagerDropped => EK::ArtiShuttingDown,
423
            E::CantAdvanceState => EK::TorAccessFailed,
424
            E::LockFile { .. } => EK::CacheAccessFailed,
425
            E::CacheFile { .. } => EK::CacheAccessFailed,
426
            E::ConsensusDiffError(_) => EK::TorProtocolViolation,
427
            E::ParseError { source, .. } | E::VerifyError { source, .. } => match source {
428
                DocSource::LocalCache => EK::CacheCorrupted,
429
                DocSource::DirServer { .. } => EK::TorProtocolViolation,
430
            },
431
            E::ConsensusInvalid { source, .. } => match source {
432
                DocSource::LocalCache => EK::CacheCorrupted,
433
                DocSource::DirServer { .. } => EK::TorProtocolViolation,
434
            },
435
            E::UntimelyObject(_) => EK::TorProtocolViolation,
436
            E::DirClientError(e) => e.kind(),
437
            E::SignatureError(_) => EK::TorProtocolViolation,
438
            E::OfflineMode => EK::BadApiUsage,
439
            E::Spawn { cause, .. } => cause.kind(),
440
            E::ExternalDirProvider { kind, .. } => *kind,
441
            E::Bug(e) => e.kind(),
442
        }
443
    }
444
}
445

            
446
/// Convert a sqlite error code into a real ErrorKind.
447
fn sqlite_error_kind(e: &rusqlite::Error) -> ErrorKind {
448
    use ErrorKind as EK;
449
    use rusqlite::ErrorCode as RE;
450

            
451
    match e {
452
        rusqlite::Error::SqliteFailure(code, _) => match code.code {
453
            RE::DatabaseCorrupt => EK::CacheCorrupted,
454
            RE::SchemaChanged
455
            | RE::TooBig
456
            | RE::ConstraintViolation
457
            | RE::TypeMismatch
458
            | RE::ApiMisuse
459
            | RE::NoLargeFileSupport
460
            | RE::ParameterOutOfRange
461
            | RE::OperationInterrupted
462
            | RE::ReadOnly
463
            | RE::OperationAborted
464
            | RE::DatabaseBusy
465
            | RE::DatabaseLocked
466
            | RE::OutOfMemory
467
            | RE::InternalMalfunction => EK::Internal,
468

            
469
            RE::FileLockingProtocolFailed
470
            | RE::AuthorizationForStatementDenied
471
            | RE::NotFound
472
            | RE::DiskFull
473
            | RE::CannotOpen
474
            | RE::SystemIoFailure
475
            | RE::PermissionDenied => EK::CacheAccessFailed,
476
            RE::NotADatabase => EK::InvalidConfig,
477
            _ => EK::Internal,
478
        },
479

            
480
        // TODO: Some of the other sqlite error types can sometimes represent
481
        // possible database corruption (like UTF8Error.)  But I haven't
482
        // found a way to distinguish when.
483
        _ => EK::Internal,
484
    }
485
}
486

            
487
/// An error coming from a read-only store.
488
#[derive(Error, Debug, Clone)]
489
#[non_exhaustive]
490
pub enum ReadOnlyStorageError {
491
    /// We couldn't find the database.
492
    #[error("The database could not be found.")]
493
    NoDatabase,
494

            
495
    /// A schema version that is not current.
496
    #[error("Incompatible data storage schema v{schema}. (We expected v{supported})")]
497
    IncompatibleSchema {
498
        /// The schema version in the database
499
        schema: u32,
500
        /// The schema that we actually support.
501
        supported: u32,
502
    },
503
}