1
#![cfg_attr(docsrs, feature(doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6
#![warn(missing_docs)]
7
#![warn(noop_method_call)]
8
#![warn(unreachable_pub)]
9
#![warn(clippy::all)]
10
#![deny(clippy::await_holding_lock)]
11
#![deny(clippy::cargo_common_metadata)]
12
#![deny(clippy::cast_lossless)]
13
#![deny(clippy::checked_conversions)]
14
#![allow(clippy::cognitive_complexity)] // See arti#2556
15
#![deny(clippy::debug_assert_with_mut_call)]
16
#![deny(clippy::exhaustive_enums)]
17
#![deny(clippy::exhaustive_structs)]
18
#![deny(clippy::expl_impl_clone_on_copy)]
19
#![deny(clippy::fallible_impl_from)]
20
#![deny(clippy::implicit_clone)]
21
#![deny(clippy::large_stack_arrays)]
22
#![warn(clippy::manual_ok_or)]
23
#![deny(clippy::missing_docs_in_private_items)]
24
#![warn(clippy::needless_borrow)]
25
#![warn(clippy::needless_pass_by_value)]
26
#![warn(clippy::option_option)]
27
#![deny(clippy::print_stderr)]
28
#![deny(clippy::print_stdout)]
29
#![warn(clippy::rc_buffer)]
30
#![deny(clippy::ref_option_ref)]
31
#![warn(clippy::semicolon_if_nothing_returned)]
32
#![warn(clippy::trait_duplication_in_bounds)]
33
#![deny(clippy::unchecked_time_subtraction)]
34
#![deny(clippy::unnecessary_wraps)]
35
#![warn(clippy::unseparated_literal_suffix)]
36
#![deny(clippy::unwrap_used)]
37
#![deny(clippy::mod_module_files)]
38
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39
#![allow(clippy::uninlined_format_args)]
40
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43
#![allow(clippy::needless_lifetimes)] // See arti#1765
44
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45
#![allow(clippy::collapsible_if)] // See arti#2342
46
#![deny(clippy::unused_async)]
47
#![deny(clippy::string_slice)] // See arti#2571
48
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
49
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
50

            
51
use derive_more::Display;
52

            
53
mod internal;
54
pub use internal::*;
55

            
56
mod report;
57
pub use report::*;
58

            
59
mod retriable;
60
pub use retriable::*;
61

            
62
mod misc;
63
pub use misc::*;
64

            
65
#[cfg(feature = "tracing")]
66
pub mod tracing;
67

            
68
#[cfg(feature = "http")]
69
mod http;
70

            
71
/// Classification of an error arising from Arti's Tor operations
72
///
73
/// This `ErrorKind` should suffice for programmatic handling by most applications embedding Arti:
74
/// get the kind via [`HasKind::kind`] and compare it to the expected value(s) with equality
75
/// or by matching.
76
///
77
/// When forwarding or reporting errors, use the whole error (e.g., `TorError`), not just the kind:
78
/// the error itself will contain more detail and context which is useful to humans.
79
//
80
// Splitting vs lumping guidelines:
81
//
82
// # Split on the place which caused the error
83
//
84
// Every ErrorKind should generally have an associated "location" in
85
// which it occurred.  If a problem can happen in two different
86
// "locations", it should have two different ErrorKinds.  (This goal
87
// may be frustrated sometimes by difficulty in determining where exactly
88
// a given error occurred.)
89
//
90
// The location of an ErrorKind should always be clear from its name.  If is not
91
// clear, add a location-related word to the name of the ErrorKind.
92
//
93
// For the purposes of this discussion, the following locations exist:
94
//   - Process:  Our code, or the application code using it.  These errors don't
95
//     usually need a special prefix.
96
//   - Host: A problem with our local computing  environment.  These errors
97
//     usually reflect trying to run under impossible circumstances (no file
98
//     system, no permissions, etc).
99
//   - Local: Another process on the same machine, or on the network between us
100
//     and the Tor network.  Errors in this location often indicate an outage,
101
//     misconfiguration, or a censorship event.
102
//   - Tor: Anywhere within the Tor network, or connections between Tor relays.
103
//     The words "Exit" and "Relay" also indicate this location.
104
//   - Remote: Anywhere _beyond_ the Tor exit. Can be a problem in the Tor
105
//     exit's connection to the real internet,  or with the remote host that the
106
//     exit is talking to.  (This kind of error can also indicate that the exit
107
//     is lying.)
108
//
109
// ## Lump any locations more fine-grained than that.
110
//
111
// We do not split locations more finely unless there's a good reason to do so.
112
// For example, we don't typically split errors within the "Tor" location based
113
// on whether they happened at a guard, a directory, or an exit.  (Errors with
114
// "Exit" or "Guard" in their names are okay, so long as that kind of error can
115
// _only_ occur at an Exit or Guard.)
116
//
117
// # Split based on reasonable response and semantics
118
//
119
// We also should split ErrorKinds based on what it's reasonable for the
120
// receiver to do with them.  Users may find more applications for our errors
121
// than we do, so we shouldn't assume that we can predict every reasonable use
122
// in advance.
123
//
124
// ErrorKinds should be more specific than just the locations in which they
125
// happen: for example, there shouldn't be a `TorNetworkError` or
126
// a `RemoteFailure`.
127
//
128
// # Avoid exposing implementation details
129
//
130
// ErrorKinds should not relate to particular code paths in the Arti codebase.
131

            
132
#[derive(Debug, Clone, Copy, PartialEq, Eq, Display, Hash)]
133
#[non_exhaustive]
134
pub enum ErrorKind {
135
    /// Error connecting to the Tor network
136
    ///
137
    /// Perhaps the local network is not working,
138
    /// or perhaps the chosen relay or bridge is not working properly.
139
    /// Not used for errors that occur within the Tor network, or accessing the public
140
    /// internet on the far side of Tor.
141
    #[display("error connecting to Tor")]
142
    TorAccessFailed,
143

            
144
    /// An attempt was made to use a Tor client for something without bootstrapping it first.
145
    #[display("attempted to use unbootstrapped client")]
146
    BootstrapRequired,
147

            
148
    /// Our network directory has expired before we were able to replace it.
149
    ///
150
    /// This kind of error can indicate one of several possible problems:
151
    /// * It can occur if the client used to be on the network, but has been
152
    ///   unable to make directory connections for a while.
153
    /// * It can occur if the client has been suspended or sleeping for a long
154
    ///   time, and has suddenly woken up without having a chance to replace its
155
    ///   network directory.
156
    /// * It can happen if the client has a sudden clock jump.
157
    ///
158
    /// Often, retrying after a minute or so will resolve this issue.
159
    ///
160
    // TODO this is pretty shonky.  "try again after a minute or so", seriously?
161
    //
162
    /// Future versions of Arti may resolve this situation automatically without caller
163
    /// intervention, possibly depending on preferences and API usage, in which case this kind of
164
    /// error will never occur.
165
    //
166
    // TODO: We should distinguish among the actual issues here, and report a
167
    // real bootstrapping problem when it exists.
168
    #[display("network directory is expired.")]
169
    DirectoryExpired,
170

            
171
    /// IO error accessing local persistent state
172
    ///
173
    /// For example, the disk might be full, or there may be a permissions problem.
174
    /// Usually the source will be [`std::io::Error`].
175
    ///
176
    /// Note that this kind of error only applies to problems in your `state_dir`:
177
    /// problems with your cache are another kind.
178
    #[display("could not read/write persistent state")]
179
    PersistentStateAccessFailed,
180

            
181
    /// We could not start up because a local resource is already being used by someone else
182
    ///
183
    /// Local resources include things like listening ports and state lockfiles.
184
    /// (We don't use this error for "out of disk space" and the like.)
185
    ///
186
    /// This can occur when another process
187
    /// (or another caller of Arti APIs)
188
    /// is already running a facility that overlaps with the one being requested.
189
    ///
190
    /// For example,
191
    /// running multiple processes each containing instances of the same hidden service,
192
    /// using the same state directories etc., is not supported.
193
    ///
194
    /// Another example:
195
    /// if Arti is configured to listen on a particular port,
196
    /// but another process on the system is already listening there,
197
    /// the resulting error has kind `LocalResourceAlreadyInUse`.
198
    // Actually, we only currently listen on ports in `arti` so we don't return
199
    // any Rust errors for this situation at all, at the time of writing.
200
    #[display("local resource (port, lockfile, etc.) already in use")]
201
    LocalResourceAlreadyInUse,
202

            
203
    /// We encountered a problem with filesystem permissions.
204
    ///
205
    /// This is likeliest to be caused by permissions on a file or directory
206
    /// being too permissive; the next likeliest cause is that we were unable to
207
    /// check the permissions on the file or directory, or on one of its
208
    /// ancestors.
209
    #[display("problem with filesystem permissions")]
210
    FsPermissions,
211

            
212
    /// Tor client's persistent state has been corrupted
213
    ///
214
    /// This could be because of a bug in the Tor code, or because something
215
    /// else has been messing with the data.
216
    ///
217
    /// This might also occur if the Tor code was upgraded and the new Tor is
218
    /// not compatible.
219
    ///
220
    /// Note that this kind of error only applies to problems in your
221
    /// `state_dir`: problems with your cache are another kind.
222
    #[display("corrupted data in persistent state")]
223
    PersistentStateCorrupted,
224

            
225
    /// Tor client's cache has been corrupted.
226
    ///
227
    /// This could be because of a bug in the Tor code, or because something else has been messing
228
    /// with the data.
229
    ///
230
    /// This might also occur if the Tor code was upgraded and the new Tor is not compatible.
231
    ///
232
    /// Note that this kind of error only applies to problems in your `cache_dir`:
233
    /// problems with your persistent state are another kind.
234
    #[display("corrupted data in cache")]
235
    CacheCorrupted,
236

            
237
    /// We had a problem reading or writing to our data cache.
238
    ///
239
    /// This may be a disk error, a file permission error, or similar.
240
    ///
241
    /// Note that this kind of error only applies to problems in your `cache_dir`:
242
    /// problems with your persistent state are another kind.
243
    #[display("cache access problem")]
244
    CacheAccessFailed,
245

            
246
    /// The keystore has been corrupted
247
    ///
248
    /// This could be because of a bug in the Tor code, or because something else has been messing
249
    /// with the data.
250
    ///
251
    /// Note that this kind of error only applies to problems in your `keystore_dir`:
252
    /// problems with your cache or persistent state are another kind.
253
    #[display("corrupted data in keystore")]
254
    KeystoreCorrupted,
255

            
256
    /// IO error accessing keystore
257
    ///
258
    /// For example, the disk might be full, or there may be a permissions problem.
259
    /// The source is typically an [`std::io::Error`].
260
    ///
261
    /// Note that this kind of error only applies to problems in your `keystore_dir`:
262
    /// problems with your cache or persistent state are another kind.
263
    #[display("could not access keystore")]
264
    KeystoreAccessFailed,
265

            
266
    /// Tor client's Rust async reactor is shutting down.
267
    ///
268
    /// This likely indicates that the reactor has encountered a fatal error, or
269
    /// has been told to do a clean shutdown, and it isn't possible to spawn new
270
    /// tasks.
271
    #[display("reactor is shutting down")]
272
    ReactorShuttingDown,
273

            
274
    /// Tor client is shutting down.
275
    ///
276
    /// This likely indicates that the last handle to the `TorClient` has been
277
    /// dropped, and is preventing other operations from completing.
278
    #[display("Tor client is shutting down.")]
279
    ArtiShuttingDown,
280

            
281
    /// This Tor client software is missing some feature that is recommended
282
    /// (or required) for operation on the network.
283
    ///
284
    /// This occurs when the directory authorities tell us that we ought to have
285
    /// a particular protocol feature that we do not support.
286
    /// The correct solution is likely to upgrade to a more recent version of Arti.
287
    #[display("Software version is deprecated")]
288
    SoftwareDeprecated,
289

            
290
    /// An operation failed because we waited too long for an exit to do
291
    /// something.
292
    ///
293
    /// This error can happen if the host you're trying to connect to isn't
294
    /// responding to traffic.
295
    /// It can also happen if an exit, or hidden service, is overloaded, and
296
    /// unable to answer your replies in a timely manner.
297
    ///
298
    /// And it might simply mean that the Tor network itself
299
    /// (including possibly relays, or hidden service introduction or rendezvous points)
300
    /// is not working properly
301
    ///
302
    /// In either case, trying later, or on a different circuit, might help.
303
    //
304
    // TODO: Say that this is distinct from the case where the exit _tells you_
305
    // that there is a timeout.
306
    #[display("operation timed out at exit")]
307
    RemoteNetworkTimeout,
308

            
309
    /// One or more configuration values were invalid or incompatible.
310
    ///
311
    /// This kind of error can happen if the user provides an invalid or badly
312
    /// formatted configuration file, if some of the options in that file are
313
    /// out of their ranges or unparsable, or if the options are not all
314
    /// compatible with one another. It can also happen if configuration options
315
    /// provided via APIs are out of range.
316
    ///
317
    /// If this occurs because of user configuration, it's probably best to tell
318
    /// the user about the error. If it occurs because of API usage, it's
319
    /// probably best to fix the code that causes the error.
320
    #[display("invalid configuration")]
321
    InvalidConfig,
322

            
323
    /// Tried to change the configuration of a running Arti service in a way
324
    /// that isn't supported.
325
    ///
326
    /// This kind of error can happen when you call a `reconfigure()` method on
327
    /// a service (or part of a service) and the new configuration is not
328
    /// compatible with the previous configuration.
329
    ///
330
    /// The only available remedy is to tear down the service and make a fresh
331
    /// one (for example, by making a new `TorClient`).
332
    #[display("invalid configuration transition")]
333
    InvalidConfigTransition,
334

            
335
    /// Tried to look up a directory depending on the user's home directory, but
336
    /// the user's home directory isn't set or can't be found.
337
    ///
338
    /// This kind of error can also occur if we're running in an environment
339
    /// where users don't have home directories.
340
    ///
341
    /// To resolve this kind of error, either move to an OS with home
342
    /// directories, or make sure that all paths in the configuration are set
343
    /// explicitly, and do not depend on any path variables.
344
    #[display("could not find a home directory")]
345
    NoHomeDirectory,
346

            
347
    /// A requested operation was not implemented by Arti.
348
    ///
349
    /// This kind of error can happen when requesting a piece of protocol
350
    /// functionality that has not (yet) been implemented in the Arti project.
351
    ///
352
    /// If it happens as a result of a user activity, it's fine to ignore, log,
353
    /// or report the error. If it happens as a result of direct API usage, it
354
    /// may indicate that you're using something that isn't implemented yet.
355
    ///
356
    /// This kind can relate both to operations which we plan to implement, and
357
    /// to operations which we do not.  It does not relate to facilities which
358
    /// are disabled (e.g. at build time) or harmful.
359
    ///
360
    /// It can refer to facilities which were once implemented in Tor or Arti
361
    /// but for which support has been removed.
362
    #[display("operation not implemented")]
363
    NotImplemented,
364

            
365
    /// A feature was requested which has been disabled in this build of Arti.
366
    ///
367
    /// This kind of error happens when the running Arti was built without the
368
    /// appropriate feature (usually, cargo feature) enabled.
369
    ///
370
    /// This might indicate that the overall running system has been
371
    /// mis-configured at build-time.  Alternatively, it can occur if the
372
    /// running system is deliberately stripped down, in which case it might be
373
    /// reasonable to simply report this error to a user.
374
    #[display("operation not supported because Arti feature disabled")]
375
    FeatureDisabled,
376

            
377
    /// Someone or something local violated a network protocol.
378
    ///
379
    /// This kind of error can happen when a local program accessing us over some
380
    /// other protocol violates the protocol's requirements.
381
    ///
382
    /// This usually indicates a programming error: either in that program's
383
    /// implementation of the protocol, or in ours.  In any case, the problem
384
    /// is with software on the local system (or otherwise sharing a Tor client).
385
    ///
386
    /// It might also occur if the local system has an incompatible combination
387
    /// of tools that we can't talk with.
388
    ///
389
    /// This error kind does *not* include situations that are better explained
390
    /// by a local program simply crashing or terminating unexpectedly.
391
    #[display("local protocol violation (local bug or incompatibility)")]
392
    LocalProtocolViolation,
393

            
394
    /// Someone or something on the Tor network violated the Tor protocols.
395
    ///
396
    /// This kind of error can happen when a remote Tor instance behaves in a
397
    /// way we don't expect.
398
    ///
399
    /// It usually indicates a programming error: either in their implementation
400
    /// of the protocol, or in ours.  It can also indicate an attempted attack,
401
    /// though that can be hard to diagnose.
402
    #[display("Tor network protocol violation (bug, incompatibility, or attack)")]
403
    TorProtocolViolation,
404

            
405
    /// Something went wrong with a network connection or the local network.
406
    ///
407
    /// This kind of error is usually safe to retry, and shouldn't typically be
408
    /// seen.  By the time it reaches the caller, a more specific error type
409
    /// should typically be available.
410
    #[display("problem with network or connection")]
411
    LocalNetworkError,
412

            
413
    /// More of a local resource was needed, than is available (or than we are allowed)
414
    ///
415
    /// For example, we tried to use more memory than permitted by our memory quota.
416
    #[display("local resource exhausted")]
417
    LocalResourceExhausted,
418

            
419
    /// A problem occurred when launching or communicating with an external
420
    /// process running on this computer.
421
    #[display("an externally launched plug-in tool failed")]
422
    ExternalToolFailed,
423

            
424
    /// A relay had an identity other than the one we expected.
425
    ///
426
    /// This could indicate a MITM attack, but more likely indicates that the
427
    /// relay has changed its identity but the new identity hasn't propagated
428
    /// through the directory system yet.
429
    #[display("identity mismatch")]
430
    RelayIdMismatch,
431

            
432
    /// An attempt to do something remotely through the Tor network failed
433
    /// because the circuit it was using shut down before the operation could
434
    /// finish.
435
    #[display("circuit collapsed")]
436
    CircuitCollapse,
437

            
438
    /// An operation timed out on the tor network.
439
    ///
440
    /// This may indicate a network problem, either with the local network
441
    /// environment's ability to contact the Tor network, or with the Tor
442
    /// network itself.
443
    #[display("tor operation timed out")]
444
    TorNetworkTimeout,
445

            
446
    /// We tried but failed to download or upload a piece of directory information.
447
    ///
448
    /// This is a lower-level kind of error; in general it should be retried
449
    /// before the user can see it.   In the future it is likely to be split
450
    /// into several other kinds.
451
    // TODO ^
452
    #[display("directory fetch or upload attempt failed")]
453
    TorDirectoryError,
454

            
455
    /// An operation finished because a remote stream was closed successfully.
456
    ///
457
    /// This can indicate that the target server closed the TCP connection,
458
    /// or that the exit told us that it closed the TCP connection.
459
    /// Callers should generally treat this like a closed TCP connection.
460
    #[display("remote stream closed")]
461
    RemoteStreamClosed,
462

            
463
    /// An operation finished because the remote stream was closed abruptly.
464
    ///
465
    /// This kind of error is analogous to an ECONNRESET error; it indicates
466
    /// that the exit reported that the stream was terminated without a clean
467
    /// TCP shutdown.
468
    ///
469
    /// For most purposes, it's fine to treat this kind of error the same as
470
    /// regular unexpected close.
471
    #[display("remote stream reset")]
472
    RemoteStreamReset,
473

            
474
    /// An operation finished because a remote stream was closed unsuccessfully.
475
    ///
476
    /// This indicates that the exit reported some error message for the stream.
477
    ///
478
    /// We only provide this error kind when no more specific kind is available.
479
    #[display("remote stream error")]
480
    RemoteStreamError,
481

            
482
    /// A stream failed, and the exit reports that the remote host refused
483
    /// the connection.
484
    ///
485
    /// This is analogous to an ECONNREFUSED error.
486
    #[display("remote host refused connection")]
487
    RemoteConnectionRefused,
488

            
489
    /// A stream was rejected by the exit relay because of that relay's exit
490
    /// policy.
491
    ///
492
    /// (In Tor, exits have a set of policies declaring which addresses and
493
    /// ports they're willing to connect to.  Clients download only _summaries_
494
    /// of these policies, so it's possible to be surprised by an exit's refusal
495
    /// to connect somewhere.)
496
    #[display("rejected by exit policy")]
497
    ExitPolicyRejected,
498

            
499
    /// An operation failed, and the exit reported that it waited too long for
500
    /// the operation to finish.
501
    ///
502
    /// This kind of error is distinct from `RemoteNetworkTimeout`, which means
503
    /// that _our own_ timeout threshold was violated.
504
    #[display("timeout at exit relay")]
505
    ExitTimeout,
506

            
507
    /// An operation failed, and the exit reported a network failure of some
508
    /// kind.
509
    ///
510
    /// This kind of error can occur for a number of reasons.  If it happens
511
    /// when trying to open a stream, it usually indicates a problem connecting,
512
    /// such as an ENOROUTE error.
513
    #[display("network failure at exit")]
514
    RemoteNetworkFailed,
515

            
516
    /// An operation finished because an exit failed to look up a hostname.
517
    ///
518
    /// Unfortunately, the Tor protocol does not distinguish failure of DNS
519
    /// services ("we couldn't find out if this host exists and what its name is")
520
    /// from confirmed denials ("this is not a hostname").  So this kind
521
    /// conflates both those sorts of error.
522
    ///
523
    /// Trying at another exit might succeed, or the address might truly be
524
    /// unresolvable.
525
    #[display("remote hostname not found")]
526
    RemoteHostNotFound,
527

            
528
    /// The target hidden service (`.onion` service) was not found in the directory
529
    ///
530
    /// We successfully connected to at least one directory server,
531
    /// but it didn't have a record of the hidden service.
532
    ///
533
    /// This probably means that the hidden service is not running, or does not exist.
534
    /// (It might mean that the directory servers are faulty,
535
    /// and that the hidden service was unable to publish its descriptor.)
536
    #[display("Onion Service not found")]
537
    OnionServiceNotFound,
538

            
539
    /// The target hidden service (`.onion` service) seems to be down
540
    ///
541
    /// We successfully obtained a hidden service descriptor for the service,
542
    /// so we know it is supposed to exist,
543
    /// but we weren't able to communicate with it via any of its
544
    /// introduction points.
545
    ///
546
    /// This probably means that the hidden service is not running.
547
    /// (It might mean that the introduction point relays are faulty.)
548
    #[display("Onion Service not running")]
549
    OnionServiceNotRunning,
550

            
551
    /// Protocol trouble involving the target hidden service (`.onion` service)
552
    ///
553
    /// Something unexpected happened when trying to connect to the selected hidden service.
554
    /// It seems to have been due to the hidden service violating the Tor protocols somehow.
555
    #[display("Onion Service protocol failed (apparently due to service behaviour)")]
556
    OnionServiceProtocolViolation,
557

            
558
    /// The target hidden service (`.onion` service) is running but we couldn't connect to it,
559
    /// and we aren't sure whose fault that is
560
    ///
561
    /// This might be due to malfunction on the part of the service,
562
    /// or a relay being used as an introduction point or relay,
563
    /// or failure of the underlying Tor network.
564
    #[display("Onion Service not reachable (due to service, or Tor network, behaviour)")]
565
    OnionServiceConnectionFailed,
566

            
567
    /// We tried to connect to an onion service without authentication,
568
    /// but it apparently requires authentication.
569
    #[display("Onion service required authentication, but none was provided.")]
570
    OnionServiceMissingClientAuth,
571

            
572
    /// We tried to connect to an onion service that requires authentication, and
573
    /// ours is wrong.
574
    ///
575
    /// This likely means that we need to use a different key for talking to
576
    /// this onion service, or that it has revoked our permissions to reach it.
577
    #[display("Onion service required authentication, but provided authentication was incorrect.")]
578
    OnionServiceWrongClientAuth,
579

            
580
    /// We tried to parse a `.onion` address, and found that it was not valid.
581
    ///
582
    /// This likely means that it was corrupted somewhere along its way from its
583
    /// origin to our API surface.  It may be the wrong length, have invalid
584
    /// characters, have an invalid version number, or have an invalid checksum.
585
    #[display(".onion address was invalid.")]
586
    OnionServiceAddressInvalid,
587

            
588
    /// An resolve operation finished with an error.
589
    ///
590
    /// Contrary to [`RemoteHostNotFound`](ErrorKind::RemoteHostNotFound),
591
    /// this can't mean "this is not a hostname".
592
    /// This error should be retried.
593
    #[display("remote hostname lookup failure")]
594
    RemoteHostResolutionFailed,
595

            
596
    /// Trouble involving a protocol we're using with a peer on the far side of the Tor network
597
    ///
598
    /// We were using a higher-layer protocol over a Tor connection,
599
    /// and something went wrong.
600
    /// This might be an error reported by the remote host within that higher protocol,
601
    /// or a problem detected locally but relating to that higher protocol.
602
    ///
603
    /// The nature of the problem can vary:
604
    /// examples could include:
605
    /// failure to agree suitable parameters (incompatibility);
606
    /// authentication problems (eg, TLS certificate trouble);
607
    /// protocol violation by the peer;
608
    /// peer refusing to provide service;
609
    /// etc.
610
    #[display("remote protocol violation")]
611
    RemoteProtocolViolation,
612

            
613
    /// An operation failed, and the relay in question reported that it's too
614
    /// busy to answer our request.
615
    #[display("relay too busy")]
616
    RelayTooBusy,
617

            
618
    /// We were asked to make an anonymous connection to a malformed address.
619
    ///
620
    /// This is probably because of a bad input from a user.
621
    #[display("target address was invalid")]
622
    InvalidStreamTarget,
623

            
624
    /// We were asked to make an anonymous connection to a _locally_ disabled
625
    /// address.
626
    ///
627
    /// For example, this kind of error can happen when try to connect to (e.g.)
628
    /// `127.0.0.1` using a client that isn't configured with allow_local_addrs.
629
    ///
630
    /// Usually this means that you intended to reject the request as
631
    /// nonsensical; but if you didn't, it probably means you should change your
632
    /// configuration to allow what you want.
633
    #[display("target address disabled locally")]
634
    ForbiddenStreamTarget,
635

            
636
    /// An operation failed in a transient way.
637
    ///
638
    /// This kind of error indicates that some kind of operation failed in a way
639
    /// where retrying it again could likely have made it work.
640
    ///
641
    /// You should not generally see this kind of error returned directly to you
642
    /// for high-level functions.  It should only be returned from lower-level
643
    /// crates that do not automatically retry these failures.
644
    // Errors with this kind should generally not return a `HasRetryTime::retry_time()` of `Never`.
645
    #[display("un-retried transient failure")]
646
    TransientFailure,
647

            
648
    /// Bug, for example calling a function with an invalid argument.
649
    ///
650
    /// This kind of error is usually a programming mistake on the caller's part.
651
    /// This is usually a bug in code calling Arti, but it might be a bug in Arti itself.
652
    //
653
    // Usually, use `bad_api_usage!` and `into_bad_api_usage!` and thereby `InternalError`,
654
    // rather than inventing a new type with this kind.
655
    //
656
    // Errors with this kind should generally include a stack trace.  They are
657
    // very like InternalError, in that they represent a bug in the program.
658
    // The difference is that an InternalError, with kind `Internal`, represents
659
    // a bug in arti, whereas errors with kind BadArgument represent bugs which
660
    // could be (often, are likely to be) outside arti.
661
    #[display("bad API usage (bug)")]
662
    BadApiUsage,
663

            
664
    /// We asked a relay to create or extend a circuit, and it declined.
665
    ///
666
    /// Either it gave an error message indicating that it refused to perform
667
    /// the request, or the protocol gives it no room to explain what happened.
668
    ///
669
    /// This error is returned by higher-level functions only if it is the most informative
670
    /// error after appropriate retries etc.
671
    #[display("remote host refused our request")]
672
    CircuitRefused,
673

            
674
    /// We were unable to construct a path through the Tor network.
675
    ///
676
    /// Usually this indicates that there are too many user-supplied
677
    /// restrictions for us to comply with.
678
    ///
679
    /// On test networks, it likely indicates that there aren't enough relays,
680
    /// or that there aren't enough relays in distinct families.
681
    //
682
    // TODO: in the future, errors of this type should distinguish between
683
    // cases where this happens because of a user restriction and cases where it
684
    // happens because of a severely broken directory.
685
    //
686
    // The latter should be classified as TorDirectoryBroken.
687
    #[display("could not construct a path")]
688
    NoPath,
689

            
690
    /// We were unable to find an exit relay with a certain set of desired
691
    /// properties.
692
    ///
693
    /// Usually this indicates that there were too many user-supplied
694
    /// restrictions on the exit for us to comply with, or that there was no
695
    /// exit on the network supporting all of the ports that the user asked for.
696
    //
697
    // TODO: same as for NoPath.
698
    #[display("no exit available for path")]
699
    NoExit,
700

            
701
    /// The Tor consensus directory is broken or unsuitable
702
    ///
703
    /// This could occur when running very old software
704
    /// against the current Tor network,
705
    /// so that the newer network is incompatible.
706
    ///
707
    /// It might also mean a catastrophic failure of the Tor network,
708
    /// or that a deficient test network is in use.
709
    ///
710
    /// Currently some instances of this kind of problem
711
    /// are reported as `NoPath` or `NoExit`.
712
    #[display("Tor network consensus directory is not usable")]
713
    TorDirectoryUnusable,
714

            
715
    /// An operation failed because of _possible_ clock skew.
716
    ///
717
    /// The broken clock may be ours, or it may belong to another party on the
718
    /// network. It's also possible that somebody else is lying about the time,
719
    /// caching documents for far too long, or something like that.
720
    #[display("possible clock skew detected")]
721
    ClockSkew,
722

            
723
    /// A directory told us that some document we were trying to upload
724
    /// is not acceptable.
725
    ///
726
    /// This could be our fault (if we have a bug, if we're misconfigured,
727
    /// if we are running very old software, etc),
728
    /// or it could be the fault of the remote host
729
    /// (if it is running very old software).
730
    ///
731
    /// In the case of an upload over unencrypted HTTP, this error
732
    /// could also be the result of a MITM attacker impersonating the directory.
733
    TorDocumentRejected,
734

            
735
    /// Internal error (bug) in Arti.
736
    ///
737
    /// A supposedly impossible problem has arisen.  This indicates a bug in
738
    /// Arti; if the Arti version is relatively recent, please report the bug on
739
    /// our [bug tracker](https://gitlab.torproject.org/tpo/core/arti/-/issues).
740
    #[display("internal error (bug)")]
741
    Internal,
742

            
743
    /// Unclassified error
744
    ///
745
    /// Some other error occurred, which does not fit into any of the other kinds.
746
    ///
747
    /// This kind is provided for use by external code
748
    /// hooking into or replacing parts of Arti.
749
    /// It is never returned by the code in Arti (`arti-*` and `tor-*` crates).
750
    #[display("unclassified error")]
751
    Other,
752
}
753

            
754
/// Errors that can be categorized as belonging to an [`ErrorKind`]
755
///
756
/// The most important implementation of this trait is
757
/// `arti_client::TorError`; however, other internal errors throughout Arti
758
/// also implement it.
759
pub trait HasKind {
760
    /// Return the kind of this error.
761
    fn kind(&self) -> ErrorKind;
762
}
763

            
764
#[cfg(feature = "futures")]
765
impl HasKind for futures::task::SpawnError {
766
62
    fn kind(&self) -> ErrorKind {
767
        use ErrorKind as EK;
768
62
        if self.is_shutdown() {
769
62
            EK::ReactorShuttingDown
770
        } else {
771
            EK::Internal
772
        }
773
62
    }
774
}
775

            
776
impl HasKind for void::Void {
777
    fn kind(&self) -> ErrorKind {
778
        void::unreachable(*self)
779
    }
780
}
781

            
782
impl HasKind for std::convert::Infallible {
783
    fn kind(&self) -> ErrorKind {
784
        unreachable!()
785
    }
786
}
787

            
788
/// Sealed
789
mod sealed {
790
    /// Sealed
791
    pub trait Sealed {}
792
}