Skip to content

Commit

Permalink
fixup: eyre -> anyhow
Browse files Browse the repository at this point in the history
  • Loading branch information
hulthe committed Dec 16, 2024
1 parent 901857a commit ba5a991
Show file tree
Hide file tree
Showing 13 changed files with 107 additions and 117 deletions.
18 changes: 1 addition & 17 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion leak-checker/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ rust-version.workspace = true

[dependencies]
log.workspace = true
eyre = "0.6.12"
anyhow = "1.0"
socket2 = { version = "0.5.7", features = ["all"] }
match_cfg = "0.1.0"
pnet_packet = "0.35.0"
Expand Down
2 changes: 1 addition & 1 deletion leak-checker/examples/leaker-cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub enum LeakMethod {
}

#[tokio::main]
async fn main() -> eyre::Result<()> {
async fn main() -> anyhow::Result<()> {
pretty_env_logger::formatted_builder()
.filter_level(log::LevelFilter::Debug)
.parse_default_env()
Expand Down
14 changes: 7 additions & 7 deletions leak-checker/src/am_i_mullvad.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use eyre::{eyre, Context};
use anyhow::{anyhow, Context};
use futures::TryFutureExt;
use match_cfg::match_cfg;
use reqwest::{Client, ClientBuilder};
Expand All @@ -24,7 +24,7 @@ pub async fn run_leak_test(opt: &AmIMullvadOpt) -> LeakStatus {
}

/// Check if connected to Mullvad and print the result to stdout
pub async fn try_run_leak_test(opt: &AmIMullvadOpt) -> eyre::Result<LeakStatus> {
pub async fn try_run_leak_test(opt: &AmIMullvadOpt) -> anyhow::Result<LeakStatus> {
#[derive(Debug, Deserialize)]
struct Response {
ip: String,
Expand All @@ -37,14 +37,14 @@ pub async fn try_run_leak_test(opt: &AmIMullvadOpt) -> eyre::Result<LeakStatus>
client = bind_client_to_interface(client, interface)?;
}

let client = client.build().wrap_err("Failed to create HTTP client")?;
let client = client.build().context("Failed to create HTTP client")?;
let response: Response = client
.get(AM_I_MULLVAD_URL)
//.timeout(Duration::from_secs(opt.timeout))
.send()
.and_then(|r| r.json())
.await
.wrap_err_with(|| eyre!("Failed to GET {AM_I_MULLVAD_URL}"))?;
.with_context(|| anyhow!("Failed to GET {AM_I_MULLVAD_URL}"))?;

if let Some(server) = &response.mullvad_exit_ip_hostname {
log::debug!(
Expand All @@ -59,7 +59,7 @@ pub async fn try_run_leak_test(opt: &AmIMullvadOpt) -> eyre::Result<LeakStatus>
response.ip
);
Ok(LeakStatus::LeakDetected(LeakInfo::AmIMullvad {
ip: response.ip.parse().wrap_err("Malformed IP")?,
ip: response.ip.parse().context("Malformed IP")?,
}))
}
}
Expand All @@ -69,7 +69,7 @@ match_cfg! {
fn bind_client_to_interface(
builder: ClientBuilder,
interface: &str
) -> eyre::Result<ClientBuilder> {
) -> anyhow::Result<ClientBuilder> {
log::debug!("Binding HTTP client to {interface}");
Ok(builder.interface(interface))
}
Expand All @@ -78,7 +78,7 @@ match_cfg! {
fn bind_client_to_interface(
builder: ClientBuilder,
interface: &str
) -> eyre::Result<ClientBuilder> {
) -> anyhow::Result<ClientBuilder> {
use crate::util::get_interface_ip;

let ip = get_interface_ip(interface)?;
Expand Down
55 changes: 29 additions & 26 deletions leak-checker/src/traceroute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::{
time::Duration,
};

use eyre::{bail, ensure, eyre, OptionExt, WrapErr};
use anyhow::{anyhow, bail, ensure, Context};
use futures::{future::pending, select, stream, FutureExt, StreamExt, TryFutureExt, TryStreamExt};
use pnet_packet::{
icmp::{
Expand Down Expand Up @@ -97,7 +97,7 @@ pub async fn run_leak_test(opt: &TracerouteOpt) -> LeakStatus {
///
/// This test needs a raw socket to be able to listen for the ICMP responses, therefore it requires
/// root/admin priviliges.
pub async fn try_run_leak_test(opt: &TracerouteOpt) -> eyre::Result<LeakStatus> {
pub async fn try_run_leak_test(opt: &TracerouteOpt) -> anyhow::Result<LeakStatus> {
// create the socket used for receiving the ICMP/TimeExceeded responses

// don't ask me why, but this is how it must be.
Expand All @@ -108,11 +108,11 @@ pub async fn try_run_leak_test(opt: &TracerouteOpt) -> eyre::Result<LeakStatus>
};

let icmp_socket = Socket::new(Domain::IPV4, icmp_socket_type, Some(Protocol::ICMPV4))
.wrap_err("Failed to open ICMP socket")?;
.context("Failed to open ICMP socket")?;

icmp_socket
.set_nonblocking(true)
.wrap_err("Failed to set icmp_socket to nonblocking")?;
.context("Failed to set icmp_socket to nonblocking")?;

Impl::bind_socket_to_interface(&icmp_socket, &opt.interface)?;
Impl::configure_icmp_socket(&icmp_socket, opt)?;
Expand All @@ -125,33 +125,33 @@ pub async fn try_run_leak_test(opt: &TracerouteOpt) -> eyre::Result<LeakStatus>
} else {
// create the socket used for sending the UDP probing packets
let udp_socket = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))
.wrap_err("Failed to open UDP socket")?;
.context("Failed to open UDP socket")?;

Impl::bind_socket_to_interface(&udp_socket, &opt.interface)
.wrap_err("Failed to bind UDP socket to interface")?;
.context("Failed to bind UDP socket to interface")?;

udp_socket
.set_nonblocking(true)
.wrap_err("Failed to set udp_socket to nonblocking")?;
.context("Failed to set udp_socket to nonblocking")?;

let mut udp_socket = AsyncUdpSocketImpl::from_socket2(udp_socket);

send_udp_probes(opt, &mut udp_socket).await?;
}

eyre::Ok(())
anyhow::Ok(())
};

// error if sending the probes takes longer than SEND_TIMEOUT
//let send_probes = timeout(SEND_TIMEOUT, send_probes)
// .map_err(|_timeout| eyre!("Timed out while trying to send probe packet"))
// .map_err(|_timeout| anyhow!("Timed out while trying to send probe packet"))
// .and_then(ready) // flatten the result
// .and_then(|_| pending::<Result<Infallible, _>>());

let send_probes = async {
timeout(SEND_TIMEOUT, send_probes)
.await
.map_err(|_timeout| eyre!("Timed out while trying to send probe packet"))??;
.map_err(|_timeout| anyhow!("Timed out while trying to send probe packet"))??;
Ok(pending::<Infallible>().await)
};

Expand All @@ -171,15 +171,18 @@ pub async fn try_run_leak_test(opt: &TracerouteOpt) -> eyre::Result<LeakStatus>
/// Send ICMP/Echo packets with a very low TTL to `opt.destination`.
///
/// Use [AsyncIcmpSocket::recv_ttl_responses] to receive replies.
async fn send_icmp_probes(opt: &TracerouteOpt, socket: &impl AsyncIcmpSocket) -> eyre::Result<()> {
async fn send_icmp_probes(
opt: &TracerouteOpt,
socket: &impl AsyncIcmpSocket,
) -> anyhow::Result<()> {
use pnet_packet::icmp::{echo_request::*, *};

for ttl in DEFAULT_TTL_RANGE {
log::debug!("sending probe packet (ttl={ttl})");

socket
.set_ttl(ttl.into())
.wrap_err("Failed to set TTL on socket")?;
.context("Failed to set TTL on socket")?;

// the first packet will sometimes get dropped on MacOS, thus we send two packets
let number_of_sends = if cfg!(target_os = "macos") { 2 } else { 1 };
Expand Down Expand Up @@ -210,7 +213,7 @@ async fn send_icmp_probes(opt: &TracerouteOpt, socket: &impl AsyncIcmpSocket) ->
// Linux returns this error if our packet was rejected by nftables.
log::debug!("send_to failed with 'permission denied'");
}
_ => return Err(e).wrap_err("Failed to send packet")?,
_ => return Err(e).context("Failed to send packet")?,
}
}

Expand All @@ -223,7 +226,7 @@ async fn send_icmp_probes(opt: &TracerouteOpt, socket: &impl AsyncIcmpSocket) ->
async fn send_udp_probes(
opt: &TracerouteOpt,
socket: &mut impl AsyncUdpSocket,
) -> eyre::Result<()> {
) -> anyhow::Result<()> {
// ensure we don't send anything to `opt.exclude_port`
let ports = DEFAULT_PORT_RANGE
// skip the excluded port
Expand All @@ -236,7 +239,7 @@ async fn send_udp_probes(

socket
.set_ttl(ttl.into())
.wrap_err("Failed to set TTL on socket")?;
.context("Failed to set TTL on socket")?;

// the first packet will sometimes get dropped on MacOS, thus we send two packets
let number_of_sends = if cfg!(target_os = "macos") { 2 } else { 1 };
Expand All @@ -254,7 +257,7 @@ async fn send_udp_probes(
// Linux returns this error if our packet was rejected by nftables.
log::debug!("send_to failed with 'permission denied'");
}
_ => return Err(e).wrap_err("Failed to send packet")?,
_ => return Err(e).context("Failed to send packet")?,
}
}

Expand All @@ -264,10 +267,10 @@ async fn send_udp_probes(
/// Try to parse the bytes as an IPv4 packet.
///
/// This only valdiates the IPv4 header, not the payload.
fn parse_ipv4(packet: &[u8]) -> eyre::Result<Ipv4Packet<'_>> {
fn parse_ipv4(packet: &[u8]) -> anyhow::Result<Ipv4Packet<'_>> {
let ip_packet = Ipv4Packet::new(packet).ok_or_else(too_small)?;
ensure!(ip_packet.get_version() == 4, "Not IPv4");
eyre::Ok(ip_packet)
anyhow::Ok(ip_packet)
}

/// Try to parse an [Ipv4Packet] as an ICMP/TimeExceeded response to a packet sent by
Expand All @@ -276,7 +279,7 @@ fn parse_ipv4(packet: &[u8]) -> eyre::Result<Ipv4Packet<'_>> {
///
/// If the packet fails to parse, or is not a reply to a packet sent by us, this function returns
/// an error.
fn parse_icmp_time_exceeded(ip_packet: &Ipv4Packet<'_>) -> eyre::Result<Ipv4Addr> {
fn parse_icmp_time_exceeded(ip_packet: &Ipv4Packet<'_>) -> anyhow::Result<Ipv4Addr> {
let ip_protocol = ip_packet.get_next_level_protocol();
ensure!(ip_protocol == IpProtocol::Icmp, "Not ICMP");
parse_icmp_time_exceeded_raw(ip_packet.payload())?;
Expand All @@ -288,8 +291,8 @@ fn parse_icmp_time_exceeded(ip_packet: &Ipv4Packet<'_>) -> eyre::Result<Ipv4Addr
///
/// If the packet fails to parse, or is not a reply to a packet sent by us, this function returns
/// an error.
fn parse_icmp_time_exceeded_raw(bytes: &[u8]) -> eyre::Result<()> {
let icmp_packet = IcmpPacket::new(bytes).ok_or(eyre!("Too small"))?;
fn parse_icmp_time_exceeded_raw(bytes: &[u8]) -> anyhow::Result<()> {
let icmp_packet = IcmpPacket::new(bytes).ok_or(anyhow!("Too small"))?;

let correct_type = icmp_packet.get_icmp_type() == IcmpTypes::TimeExceeded;
ensure!(correct_type, "Not ICMP/TimeExceeded");
Expand All @@ -312,7 +315,7 @@ fn parse_icmp_time_exceeded_raw(bytes: &[u8]) -> eyre::Result<()> {
let udp_payload = udp_len
.checked_sub(UdpPacket::minimum_packet_size())
.and_then(|len| original_udp_packet.payload().get(..len))
.ok_or_eyre("Invalid UDP length")?;
.ok_or(anyhow!("Invalid UDP length"))?;
if udp_payload != PROBE_PAYLOAD {
let udp_payload: String = udp_payload
.iter()
Expand Down Expand Up @@ -356,7 +359,7 @@ fn parse_icmp_time_exceeded_raw(bytes: &[u8]) -> eyre::Result<()> {
}
}

fn parse_icmp_echo(ip_packet: &Ipv4Packet<'_>) -> eyre::Result<()> {
fn parse_icmp_echo(ip_packet: &Ipv4Packet<'_>) -> anyhow::Result<()> {
let ip_protocol = ip_packet.get_next_level_protocol();

match ip_protocol {
Expand All @@ -365,7 +368,7 @@ fn parse_icmp_echo(ip_packet: &Ipv4Packet<'_>) -> eyre::Result<()> {
}
}

fn parse_icmp_echo_raw(icmp_bytes: &[u8]) -> eyre::Result<()> {
fn parse_icmp_echo_raw(icmp_bytes: &[u8]) -> anyhow::Result<()> {
let echo_packet = EchoRequestPacket::new(icmp_bytes).ok_or_else(too_small)?;

ensure!(
Expand All @@ -390,6 +393,6 @@ fn parse_icmp_echo_raw(icmp_bytes: &[u8]) -> eyre::Result<()> {
Ok(())
}

fn too_small() -> eyre::Report {
eyre!("Too small")
fn too_small() -> anyhow::Error {
anyhow!("Too small")
}
6 changes: 3 additions & 3 deletions leak-checker/src/traceroute/platform/android.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,16 @@ impl Traceroute for TracerouteAndroid {
type AsyncIcmpSocket = linux::AsyncIcmpSocketImpl;
type AsyncUdpSocket = unix::AsyncUdpSocketUnix;

fn bind_socket_to_interface(socket: &Socket, interface: &str) -> eyre::Result<()> {
fn bind_socket_to_interface(socket: &Socket, interface: &str) -> anyhow::Result<()> {
// can't use the same method as desktop-linux here beacuse reasons
super::common::bind_socket_to_interface(socket, interface)
}

fn get_interface_ip(interface: &str) -> eyre::Result<IpAddr> {
fn get_interface_ip(interface: &str) -> anyhow::Result<IpAddr> {
super::unix::get_interface_ip(interface)
}

fn configure_icmp_socket(socket: &socket2::Socket, opt: &TracerouteOpt) -> eyre::Result<()> {
fn configure_icmp_socket(socket: &socket2::Socket, opt: &TracerouteOpt) -> anyhow::Result<()> {
TracerouteLinux::configure_icmp_socket(socket, opt)
}
}
16 changes: 8 additions & 8 deletions leak-checker/src/traceroute/platform/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::{
net::{IpAddr, SocketAddr},
};

use eyre::{eyre, Context};
use anyhow::{anyhow, Context};
use socket2::Socket;
use tokio::{
select,
Expand All @@ -19,22 +19,22 @@ use crate::{

use super::{AsyncIcmpSocket, Impl, Traceroute};

pub fn bind_socket_to_interface(socket: &Socket, interface: &str) -> eyre::Result<()> {
pub fn bind_socket_to_interface(socket: &Socket, interface: &str) -> anyhow::Result<()> {
let interface_ip = Impl::get_interface_ip(interface)?;

log::info!("Binding socket to {interface_ip} ({interface:?})");

socket
.bind(&SocketAddr::new(interface_ip, 0).into())
.wrap_err("Failed to bind socket to interface address")?;
.context("Failed to bind socket to interface address")?;

Ok(())
}

pub async fn recv_ttl_responses(
socket: &impl AsyncIcmpSocket,
interface: &str,
) -> eyre::Result<LeakStatus> {
) -> anyhow::Result<LeakStatus> {
// the list of node IP addresses from which we received a response to our probe packets.
let mut reachable_nodes = vec![];

Expand All @@ -59,11 +59,11 @@ pub async fn recv_ttl_responses(

// let n = socket
// .recv(unsafe { &mut *(&mut read_buf[..] as *mut [u8] as *mut [MaybeUninit<u8>]) })
// .wrap_err("Failed to read from raw socket")?;
// .context("Failed to read from raw socket")?;

let (n, source) = select! {
result = socket.recv_from(&mut read_buf[..]) => result
.wrap_err("Failed to read from raw socket")?,
.context("Failed to read from raw socket")?,

_timeout = timer => {
return Ok(LeakStatus::LeakDetected(LeakInfo::NodeReachableOnInterface {
Expand All @@ -75,10 +75,10 @@ pub async fn recv_ttl_responses(

let packet = &read_buf[..n];
let result = parse_ipv4(packet)
.map_err(|e| eyre!("Ignoring packet: (len={n}, ip.src={source}) {e} ({packet:02x?})"))
.map_err(|e| anyhow!("Ignoring packet: (len={n}, ip.src={source}) {e} ({packet:02x?})"))
.and_then(|ip_packet| {
parse_icmp_time_exceeded(&ip_packet).map_err(|e| {
eyre!(
anyhow!(
"Ignoring packet (len={n}, ip.src={source}, ip.dest={}): {e}",
ip_packet.get_destination(),
)
Expand Down
Loading

0 comments on commit ba5a991

Please sign in to comment.