[go: up one dir, main page]

Tor

Struct Tor 

Source
pub struct Tor {
    pub client: TorClient,
}
Expand description

Connection to the Tor network

Fields§

§client: TorClient

Arti Tor client

Implementations§

Source§

impl Tor

Source

pub async fn new(config: TorConfig) -> Result<Self, Error>

Create a new connection to the Tor network using the provided configuration options

Examples found in repository?
examples/client.rs (line 6)
4async fn main() -> Result<()> {
5    println!("Connecting to tor network");
6    let tor = Tor::new(TorConfig::default()).await?;
7    println!("Connected!");
8    let client = HttpClient::builder().build()?;
9    let argv: Vec<String> = std::env::args().skip(1).collect();
10    let res = client.get(&tor, &argv[0]).await?;
11    println!("{:?}", res);
12    Ok(())
13}
More examples
Hide additional examples
examples/server.rs (line 14)
12async fn main() -> Result<(), Whatever> {
13    println!("Connecting to tor network");
14    let tor = Tor::new(TorConfig::default())
15        .await
16        .whatever_context("unable to connect to tor network")?;
17    println!("Connected!");
18    let service = tor
19        .service("hello")
20        .whatever_context("unable to create service")?;
21
22    println!(
23        "Onion address: {}",
24        service.onion_address().unwrap().display_unredacted()
25    );
26
27    let app = Route::new().at("/hello/:name", get(hello)).with(Tracing);
28    Server::new(service)
29        .name("hello-world")
30        .run(app)
31        .await
32        .expect("server error");
33    Ok(())
34}
Source

pub async fn new_custom<T: Future<Output = Result<TorClient, Error>>, F: FnOnce(TorClientBuilder) -> T>( callback: F, ) -> Result<Self, Error>

Create a new connection to the Tor network using a callback to edit a TorClientBuilder instance

Source

pub fn service(&self, name: &str) -> Result<HiddenService>

Start a new Tor Hidden Service with the given identifier, this identifier is used to associate the service and its keys

Examples found in repository?
examples/server.rs (line 19)
12async fn main() -> Result<(), Whatever> {
13    println!("Connecting to tor network");
14    let tor = Tor::new(TorConfig::default())
15        .await
16        .whatever_context("unable to connect to tor network")?;
17    println!("Connected!");
18    let service = tor
19        .service("hello")
20        .whatever_context("unable to create service")?;
21
22    println!(
23        "Onion address: {}",
24        service.onion_address().unwrap().display_unredacted()
25    );
26
27    let app = Route::new().at("/hello/:name", get(hello)).with(Tracing);
28    Server::new(service)
29        .name("hello-world")
30        .run(app)
31        .await
32        .expect("server error");
33    Ok(())
34}

Methods from Deref<Target = TorClient>§

Source

pub async fn bootstrap(&self) -> Result<(), Error>

Bootstrap a connection to the Tor network, with a client created by create_unbootstrapped.

Since cloned copies of a TorClient share internal state, you can bootstrap a client by cloning it and running this function in a background task (or similar). This function only needs to be called on one client in order to bootstrap all of its clones.

Returns once there is enough directory material to connect safely over the Tor network. If the client or one of its clones has already been bootstrapped, returns immediately with success. If a bootstrap is in progress, waits for it to finish, then retries it if it failed (returning success if it succeeded).

Bootstrap progress can be tracked by listening to the event receiver returned by bootstrap_events.

§Failures

If the bootstrapping process fails, returns an error. This function can safely be called again later to attempt to bootstrap another time.

Source

pub fn reconfigure( &self, new_config: &TorClientConfig, how: Reconfigure, ) -> Result<(), Error>

Change the configuration of this TorClient to new_config.

The how describes whether to perform an all-or-nothing reconfiguration: either all of the configuration changes will be applied, or none will. If you have disabled all-or-nothing changes, then only fatal errors will be reported in this function’s return value.

This function applies its changes to all TorClient instances derived from the same call to TorClient::create_*: even ones whose circuits are isolated from this handle.

§Limitations

Although most options are reconfigurable, there are some whose values can’t be changed on an a running TorClient. Those options (or their sections) are explicitly documented not to be changeable. NOTE: Currently, not all of these non-reconfigurable options are documented. See arti#1721.

Changing some options do not take effect immediately on all open streams and circuits, but rather affect only future streams and circuits. Those are also explicitly documented.

Source

pub fn isolated_client(&self) -> TorClient<R>

Return a new isolated TorClient handle.

The two TorClients will share internal state and configuration, but their streams will never share circuits with one another.

Use this function when you want separate parts of your program to each have a TorClient handle, but where you don’t want their activities to be linkable to one another over the Tor network.

Calling this function is usually preferable to creating a completely separate TorClient instance, since it can share its internals with the existing TorClient.

(Connections made with clones of the returned TorClient may share circuits with each other.)

Source

pub async fn connect<A>(&self, target: A) -> Result<DataStream, Error>
where A: IntoTorAddr,

Launch an anonymized connection to the provided address and port over the Tor network.

Note that because Tor prefers to do DNS resolution on the remote side of the network, this function takes its address as a string:

// The most usual way to connect is via an address-port tuple.
let socket = tor_client.connect(("www.example.com", 443)).await?;

// You can also specify an address and port as a colon-separated string.
let socket = tor_client.connect("www.example.com:443").await?;

Hostnames are strongly preferred here: if this function allowed the caller here to provide an IPAddr or IpAddr or SocketAddr address, then

// BAD: We're about to leak our target address to the local resolver!
let address = "www.example.com:443".to_socket_addrs().unwrap().next().unwrap();
// 🤯 Oh no! Now any eavesdropper can tell where we're about to connect! 🤯

// Fortunately, this won't compile, since SocketAddr doesn't implement IntoTorAddr.
// let socket = tor_client.connect(address).await?;
//                                 ^^^^^^^ the trait `IntoTorAddr` is not implemented for `std::net::SocketAddr`

If you really do need to connect to an IP address rather than a hostname, and if you’re sure that the IP address came from a safe location, there are a few ways to do so.

// ⚠️This is risky code!⚠️
// (Make sure your addresses came from somewhere safe...)

// If we have a fixed address, we can just provide it as a string.
let socket = tor_client.connect("192.0.2.22:443").await?;
let socket = tor_client.connect(("192.0.2.22", 443)).await?;

// If we have a SocketAddr or an IpAddr, we can use the
// DangerouslyIntoTorAddr trait.
use arti_client::DangerouslyIntoTorAddr;
let sockaddr = SocketAddr::from(([192, 0, 2, 22], 443));
let ipaddr = IpAddr::from([192, 0, 2, 22]);
let socket = tor_client.connect(sockaddr.into_tor_addr_dangerously().unwrap()).await?;
let socket = tor_client.connect((ipaddr, 443).into_tor_addr_dangerously().unwrap()).await?;
Source

pub async fn connect_with_prefs<A>( &self, target: A, prefs: &StreamPrefs, ) -> Result<DataStream, Error>
where A: IntoTorAddr,

Launch an anonymized connection to the provided address and port over the Tor network, with explicit connection preferences.

Note that because Tor prefers to do DNS resolution on the remote side of the network, this function takes its address as a string. (See TorClient::connect() for more information.)

Source

pub fn set_stream_prefs(&mut self, connect_prefs: StreamPrefs)

Sets the default preferences for future connections made with this client.

The preferences set with this function will be inherited by clones of this client, but updates to the preferences in those clones will not propagate back to the original. I.e., the preferences are copied by clone.

Connection preferences always override configuration, even configuration set later (eg, by a config reload).

Source

pub fn clone_with_prefs(&self, connect_prefs: StreamPrefs) -> TorClient<R>

Provides a new handle on this client, but with adjusted default preferences.

Connections made with e.g. connect on the returned handle will use connect_prefs. This is a convenience wrapper for clone and set_connect_prefs.

Source

pub async fn resolve(&self, hostname: &str) -> Result<Vec<IpAddr>, Error>

On success, return a list of IP addresses.

Source

pub async fn resolve_with_prefs( &self, hostname: &str, prefs: &StreamPrefs, ) -> Result<Vec<IpAddr>, Error>

On success, return a list of IP addresses, but use prefs.

Source

pub async fn resolve_ptr(&self, addr: IpAddr) -> Result<Vec<String>, Error>

Perform a remote DNS reverse lookup with the provided IP address.

On success, return a list of hostnames.

Source

pub async fn resolve_ptr_with_prefs( &self, addr: IpAddr, prefs: &StreamPrefs, ) -> Result<Vec<String>, Error>

Perform a remote DNS reverse lookup with the provided IP address.

On success, return a list of hostnames.

Source

pub fn runtime(&self) -> &R

Return a reference to the runtime being used by this client.

Source

pub fn launch_onion_service( &self, config: OnionServiceConfig, ) -> Result<Option<(Arc<RunningOnionService>, impl Stream<Item = RendRequest> + use<R>)>, Error>

Try to launch an onion service with a given configuration.

Returns Ok(None) if the service specified is disabled in the config.

This onion service will not actually handle any requests on its own: you will need to pull RendRequest objects from the returned stream, accept the ones that you want to answer, and then wait for them to give you StreamRequests.

You may find the tor_hsservice::handle_rend_requests API helpful for translating RendRequests into StreamRequests.

If you want to forward all the requests from an onion service to a set of local ports, you may want to use the tor-hsrproxy crate.

Source

pub fn bootstrap_status(&self) -> BootstrapStatus

Return a current status::BootstrapStatus describing how close this client is to being ready for user traffic.

Source

pub fn bootstrap_events(&self) -> BootstrapEvents

Return a stream of status::BootstrapStatus events that will be updated whenever the client’s status changes.

The receiver might not receive every update sent to this stream, though when it does poll the stream it should get the most recent one.

Source

pub fn set_dormant(&self, mode: DormantMode)

Change the client’s current dormant mode, putting background tasks to sleep or waking them up as appropriate.

This can be used to conserve CPU usage if you aren’t planning on using the client for a while, especially on mobile platforms.

See the DormantMode documentation for more details.

Trait Implementations§

Source§

impl Clone for Tor

Source§

fn clone(&self) -> Tor

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Deref for Tor

Source§

type Target = TorClient<PreferredRuntime>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl DerefMut for Tor

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.

Auto Trait Implementations§

§

impl !Freeze for Tor

§

impl !RefUnwindSafe for Tor

§

impl Send for Tor

§

impl Sync for Tor

§

impl Unpin for Tor

§

impl !UnwindSafe for Tor

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Sync + Send>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> FmtForward for T

Source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
Source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
Source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
Source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
Source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
Source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
Source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
Source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
Source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pipe for T
where T: ?Sized,

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
Source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
Source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more