Merge remote-tracking branch 'origin/main' into refactor-hickory

This commit is contained in:
Frando
2026-06-16 15:32:27 +02:00
56 changed files with 1107 additions and 588 deletions
+13 -2
View File
@@ -1,9 +1,11 @@
---
name: Bug report
about: Create a report to help us improve
title: 'bug: [description]'
title: '[description]'
labels: bug
projects: ["n0-computer/1"]
assignees: ''
type: bug
---
@@ -11,7 +13,7 @@ assignees: ''
<!-- A clear and concise description of what the bug is. -->
**Relevant Logs**
<!-- Setup `tracing_subscriber` in your application and use the `RUST_LOG = debug` env variable to turn on debug logs. Please see: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/fmt/fn.init.html -->
<!-- Setup `tracing_subscriber` in your application and use the `RUST_LOG = trace` env variable to turn on debug logs. Please see: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/fmt/fn.init.html -->
**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
@@ -44,3 +46,12 @@ Smartphone<!-- (please complete the following information) -->:
**Additional Context / Screenshots / GIFs**
<!-- Add any other context about the problem here. -->
**lolwut**
<!-- You made it to the bottom! Nice, now just prove you're human: -->
- [ ] This issue was created by a human that thought critically about
the issue being reported and wrote this as concisely and clearly
as they could. Taking full responsibility for the issue being
accurate.
- [ ] This issue isn't slop.
-10
View File
@@ -1,10 +0,0 @@
---
name: Default
about: No issue template
title: ''
labels: ''
assignees: ''
---
+9 -11
View File
@@ -289,12 +289,11 @@ jobs:
- name: Add wasm target
run: rustup target add wasm32-unknown-unknown
- name: Install cargo-binstall
uses: cargo-bins/cargo-binstall@v1.18.1
- name: Install wasm-bindgen-test-runner
# Match the version of wasm-bindgen used in Cargo.lock
run: cargo binstall wasm-bindgen-cli@0.2.122 --locked --no-confirm
uses: taiki-e/install-action@v2
with:
# Match the version of wasm-bindgen used in Cargo.lock
tool: wasm-bindgen-cli@0.2.122
- name: Install wasm-tools
uses: bytecodealliance/actions/wasm-tools/setup@v1
@@ -382,13 +381,12 @@ jobs:
- name: Install sccache
uses: mozilla-actions/sccache-action@v0.0.9
- name: Install cargo-binstall
uses: cargo-bins/cargo-binstall@v1.18.1
- uses: taiki-e/install-action@cargo-make
- name: Install cargo-check-external-types
run: cargo binstall cargo-check-external-types@${{ env.CARGO_CHECK_EXTERNAL_TYPES_VERSION }} --locked --no-confirm
uses: taiki-e/install-action@v2
with:
tool: |
cargo-make
cargo-check-external-types@${{ env.CARGO_CHECK_EXTERNAL_TYPES_VERSION }}
- name: Check external types
run: cargo make check-external-types
+49
View File
@@ -2,6 +2,55 @@
All notable changes to iroh will be documented in this file.
## [1.0.0](https://github.com/n0-computer/iroh/compare/v1.0.0-rc.1..1.0.0) - 2026-06-15
### ⛰️ Features
- *(iroh-relay)* [**breaking**] Allow setting a custom ServerCertVerifier and rename CaRootsConfig to CaTlsConfig ([#4300](https://github.com/n0-computer/iroh/issues/4300)) - ([b1e91e3](https://github.com/n0-computer/iroh/commit/b1e91e3d3939c06fd7ee1331e86527f525ff5a34))
- *(iroh-relay)* Add Bearer token access control without an external service ([#4326](https://github.com/n0-computer/iroh/issues/4326)) - ([400264e](https://github.com/n0-computer/iroh/commit/400264e31904673a755faa77b92833dfb60d7d8a))
- *(iroh-relay)* Allow multiple hostnames with Let's encrypt TLS ([#4337](https://github.com/n0-computer/iroh/issues/4337)) - ([9afd2bc](https://github.com/n0-computer/iroh/commit/9afd2bc1985d80b9afea9900ac26290c84f1f6a6))
- Allow configuring NetReport ([#4020](https://github.com/n0-computer/iroh/issues/4020)) - ([6406e07](https://github.com/n0-computer/iroh/commit/6406e077a998f048dbb124ef22126e75394e928b))
- Update relay urls to 1.0 stable ([#4341](https://github.com/n0-computer/iroh/issues/4341)) - ([8e25ecb](https://github.com/n0-computer/iroh/commit/8e25ecb30f3833e4a4a7dda7b17e95b655bd9f63))
- [**breaking**] Update to 1.0 dependencies ([#4343](https://github.com/n0-computer/iroh/issues/4343)) - ([b193191](https://github.com/n0-computer/iroh/commit/b193191c928835e46935d2d7e5418f6c31dc62fa))
### 🐛 Bug Fixes
- *(iroh)* Correctly abandon paths when new are opened with worse RTT ([#4296](https://github.com/n0-computer/iroh/issues/4296)) - ([295a715](https://github.com/n0-computer/iroh/commit/295a7158abf6e8dd44242fdfcbf2895fb29cbdaf))
- *(iroh)* Don't kill noq endpoint on first transport recv error ([#4314](https://github.com/n0-computer/iroh/issues/4314)) - ([0a5ce75](https://github.com/n0-computer/iroh/commit/0a5ce758a710d827dc71b8bff1487f9dd399d230))
- *(iroh)* Add global address validation token store ([#4317](https://github.com/n0-computer/iroh/issues/4317)) - ([ba81a72](https://github.com/n0-computer/iroh/commit/ba81a72535af1e093e670ea0fa76a380a7015dfc))
- *(iroh)* Add missing export for `unstable-custom-transport` and improve docs ([#4335](https://github.com/n0-computer/iroh/issues/4335)) - ([5791244](https://github.com/n0-computer/iroh/commit/5791244385b31d8be334e7cb144aacbf3e6952bc))
- *(iroh-dns)* Use portable_atomic::AtomicU64 for 32-bit targets ([#4320](https://github.com/n0-computer/iroh/issues/4320)) - ([1903740](https://github.com/n0-computer/iroh/commit/190374094f70eb08b417bf5114d0b2e2fca18912))
- *(iroh-relay)* Connect IPv4 and IPv6 concurrently (happy eyeballs) ([#4299](https://github.com/n0-computer/iroh/issues/4299)) - ([bab6a43](https://github.com/n0-computer/iroh/commit/bab6a43a2a1c4d3e98d76f15235dca2ea6edc7c4))
- Fix condition for retry warning. ([#4307](https://github.com/n0-computer/iroh/issues/4307)) - ([64b9316](https://github.com/n0-computer/iroh/commit/64b9316bf33d332e9e908ecf5785f7dc393a6e58))
### 🚜 Refactor
- *(iroh)* Use n0_future::MaybeFuture instead of own version ([#4310](https://github.com/n0-computer/iroh/issues/4310)) - ([07f1d1a](https://github.com/n0-computer/iroh/commit/07f1d1ae4a1da38d5965d558f88d340b07bef1b1))
- *(iroh)* Minor cleanups to reqwest setup ([#4311](https://github.com/n0-computer/iroh/issues/4311)) - ([3cbc1a6](https://github.com/n0-computer/iroh/commit/3cbc1a69cdf4b3b19acce2b8fb994cc9c5ec186f))
- *(iroh)* Improve tracing logs ([#4313](https://github.com/n0-computer/iroh/issues/4313)) - ([9a79782](https://github.com/n0-computer/iroh/commit/9a79782eec54273b34cf0a04c4d627a27a9a2df3))
- *(iroh)* Don't log at warn level if the address lookup isn't configured. ([#4318](https://github.com/n0-computer/iroh/issues/4318)) - ([94f4b2f](https://github.com/n0-computer/iroh/commit/94f4b2f68c9731059194c9af19b2d57b4187cc94))
- *(iroh)* Gate net_report API behind unstable-net-report feature ([#4338](https://github.com/n0-computer/iroh/issues/4338)) - ([7e95ae7](https://github.com/n0-computer/iroh/commit/7e95ae751f62f42fc6a312245b2b3ac548bbed0d))
### 📚 Documentation
- *(iroh)* Improve readme ([#4329](https://github.com/n0-computer/iroh/issues/4329)) - ([710d03a](https://github.com/n0-computer/iroh/commit/710d03a634c9b220811cddb3c300e70290d754cc))
- General cleanup and fixes ([#4328](https://github.com/n0-computer/iroh/issues/4328)) - ([01e74bc](https://github.com/n0-computer/iroh/commit/01e74bc1ec78a8a96ae507b4a3ecca99f166599f))
### 🧪 Testing
- Mark a patchbay test as flaky ([#4322](https://github.com/n0-computer/iroh/issues/4322)) - ([a24e6a7](https://github.com/n0-computer/iroh/commit/a24e6a7fbcab92a70c2d1bc58de891bebee16ed1))
### ⚙️ Miscellaneous Tasks
- *(iroh)* Update to latest noq main ([#4333](https://github.com/n0-computer/iroh/issues/4333)) - ([2f41f40](https://github.com/n0-computer/iroh/commit/2f41f406e89b9f5f6f93935dee549fbb453bae31))
- Update check-external-types ([#4323](https://github.com/n0-computer/iroh/issues/4323)) - ([95111f0](https://github.com/n0-computer/iroh/commit/95111f0c8887e5e5bae6d4c5383dcf6edd9feeb9))
- Update the issue templates a little ([#4340](https://github.com/n0-computer/iroh/issues/4340)) - ([a134dd8](https://github.com/n0-computer/iroh/commit/a134dd8e4766c622c9ab42db4d64cb19fae216ee))
- Use install-action instead of binstall directly ([#4342](https://github.com/n0-computer/iroh/issues/4342)) - ([0e7e976](https://github.com/n0-computer/iroh/commit/0e7e976e033b209841912ea6e1709b1215d16abc))
### Deps
- Update ed25519-dalek and curve25519-dalek ([#4324](https://github.com/n0-computer/iroh/issues/4324)) - ([33a92f1](https://github.com/n0-computer/iroh/commit/33a92f13cff3967d54a58d3a4515969b0f2daed0))
## [1.0.0-rc.1](https://github.com/n0-computer/iroh/compare/v1.0.0-rc.0..1.0.0-rc.1) - 2026-05-27
### ⛰️ Features
Generated
+262 -217
View File
File diff suppressed because it is too large Load Diff
+4 -7
View File
@@ -48,7 +48,6 @@ Use pre-existing protocols built on iroh instead of writing your own:
- [iroh-blobs] for [BLAKE3]-based content-addressed blob transfer scaling from kilobytes to terabytes
- [iroh-gossip] for establishing publish-subscribe overlay networks that scale, requiring only resources that your average phone can handle
- [iroh-docs] for an eventually-consistent key-value store of [iroh-blobs] blobs
- [iroh-willow] for an (in-construction) implementation of the [willow protocol]
## Getting Started
@@ -130,10 +129,9 @@ If you want to use iroh from other languages, make sure to check out [iroh-ffi],
This repository contains a workspace of crates:
- `iroh`: The core library for hole-punching & communicating with relays.
- `iroh-relay`: The relay server implementation. This is the code we run in production (and you can, too!).
- `iroh-base`: Common types like `Hash`, key types or `RelayUrl`.
- `iroh-dns-server`: DNS server implementation powering the `n0_discovery` for EndpointIds, running at dns.iroh.link.
- `iroh-net-report`: Analyzes your host's networking ability & NAT.
- `iroh-relay`: The relay client and server implementation. This is the code we run in production for the public relays (and you can, too!).
- `iroh-base`: Common types like `EndpointId` or `RelayUrl`.
- `iroh-dns-server`: DNS server implementation powering the DNS/Pkarr address lookup for EndpointIds, running at dns.iroh.link.
## License
@@ -158,7 +156,6 @@ Unless you explicitly state otherwise, any contribution intentionally submitted
[iroh-blobs]: https://github.com/n0-computer/iroh-blobs
[iroh-gossip]: https://github.com/n0-computer/iroh-gossip
[iroh-docs]: https://github.com/n0-computer/iroh-docs
[iroh-willow]: https://github.com/n0-computer/iroh-willow
[iroh-doctor]: https://github.com/n0-computer/iroh-doctor
[willow protocol]: https://willowprotocol.org
[iroh-ffi]: https://github.com/n0-computer/iroh-ffi
@@ -167,4 +164,4 @@ Unless you explicitly state otherwise, any contribution intentionally submitted
[Iroh Experiments]: https://github.com/n0-computer/iroh-experiments
[echo-rs]: /iroh/examples/echo.rs
[iroh-perf]: https://perf.iroh.computer
[docs]: https://iroh.computer/docs
[docs]: https://docs.iroh.computer
+3 -11
View File
@@ -1,6 +1,6 @@
[package]
name = "iroh-base"
version = "1.0.0-rc.1"
version = "1.0.0"
edition = "2024"
readme = "README.md"
description = "base type and utilities for Iroh"
@@ -18,18 +18,13 @@ workspace = true
curve25519-dalek = { version = "=5.0.0-rc.0", features = ["serde", "rand_core", "zeroize"], optional = true }
data-encoding = { version = "2.6.0", optional = true }
data-encoding-macro = { version = "0.1.19", optional = true }
digest = { version = "0.11", optional = true }
# Pin sha2 & sha1 to fix version incompatibility
sha2 = { version = "0.11.0", optional = true }
sha1 = { version = "0.11.0", optional = true }
ed25519-dalek = { version = "=3.0.0-rc.0", features = ["serde", "rand_core", "zeroize"], optional = true }
derive_more = { version = "2.0.1", features = ["debug", "display"], optional = true }
url = { version = "2.5.3", features = ["serde"], optional = true }
rand = { version = "0.10", optional = true }
serde = { version = "1", features = ["derive", "rc"] }
n0-error = "=1.0.0-rc.0"
zeroize = { version = "1.8.2", optional = true, features = ["derive"] }
zeroize_derive = { version = "1.4.2", optional = true } # needed for minimal versions
n0-error = "1.0.0"
zeroize = { version = "1.9", optional = true, features = ["derive"] }
# wasm-in-browser dependencies
[target.'cfg(all(target_family = "wasm", target_os = "unknown"))'.dependencies]
@@ -47,9 +42,7 @@ serde_test = "1"
default = ["relay"]
key = [
"dep:curve25519-dalek",
"dep:digest",
"dep:ed25519-dalek",
"dep:sha2",
"dep:url",
"dep:derive_more",
"dep:data-encoding",
@@ -57,7 +50,6 @@ key = [
"dep:rand",
"dep:getrandom",
"dep:zeroize",
"dep:zeroize_derive",
"relay",
]
relay = [
+7 -7
View File
@@ -20,7 +20,7 @@ use crate::{EndpointId, PublicKey, RelayUrl};
/// contact the endpoint.
///
/// To establish a network connection to an endpoint both the [`EndpointId`] and one or more network
/// paths are needed. The network paths can come from various sources, current sources can come from
/// paths are needed. The network paths can come from various sources:
///
/// - An [Address Lookup] service which can provide routing information for a given [`EndpointId`].
///
@@ -42,7 +42,7 @@ use crate::{EndpointId, PublicKey, RelayUrl};
pub struct EndpointAddr {
/// The endpoint's identifier.
pub id: EndpointId,
/// The endpoint's addresses
/// The endpoint's addresses.
pub addrs: BTreeSet<TransportAddr>,
}
@@ -52,10 +52,10 @@ pub struct EndpointAddr {
)]
#[non_exhaustive]
pub enum TransportAddr {
/// Relays
/// A relay server address.
#[debug("Relay({_0})")]
Relay(RelayUrl),
/// IP based addresses
/// An IP based address.
Ip(SocketAddr),
/// Custom transport address
Custom(CustomAddr),
@@ -128,12 +128,12 @@ impl EndpointAddr {
self
}
/// Returns true, if only a [`EndpointId`] is present.
/// Returns true if only an [`EndpointId`] is present.
pub fn is_empty(&self) -> bool {
self.addrs.is_empty()
}
/// Returns a list of IP addresses of this peer.
/// Returns an iterator over the IP addresses of this endpoint address.
pub fn ip_addrs(&self) -> impl Iterator<Item = &SocketAddr> {
self.addrs.iter().filter_map(|addr| match addr {
TransportAddr::Ip(addr) => Some(addr),
@@ -141,7 +141,7 @@ impl EndpointAddr {
})
}
/// Returns a list of relay urls of this peer.
/// Returns an iterator over the relay URLs of this endpoint address.
///
/// In practice this is expected to be zero or one home relay for all known cases currently.
pub fn relay_urls(&self) -> impl Iterator<Item = &RelayUrl> {
+6 -6
View File
@@ -23,7 +23,7 @@ const Z_BASE_32: Encoding = new_encoding! {
/// A public key.
///
/// The key itself is stored as the `CompressedEdwards` y coordinate of the public key
/// The key itself is stored as the `CompressedEdwards` y-coordinate of the public key.
/// It is verified to decompress into a valid key when created.
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
@@ -126,7 +126,7 @@ impl PublicKey {
Ok(Self(y))
}
/// Verify a signature on a message with this secret key's public key.
/// Verify a signature on a message with this public key.
///
/// # Return
///
@@ -224,7 +224,7 @@ impl Display for PublicKey {
}
}
/// Error when deserialising a [`PublicKey`] or a [`SecretKey`].
/// Error returned when parsing a [`PublicKey`] or a [`SecretKey`].
#[stack_error(derive, add_meta, from_sources, std_sources)]
#[allow(missing_docs)]
#[non_exhaustive]
@@ -238,14 +238,14 @@ pub enum KeyParsingError {
/// The input has invalid length.
#[error("invalid length")]
InvalidLength,
/// The decoded data is not a valid Ed25591 public key.
/// The decoded data is not a valid Ed25519 public key.
#[error("data is not a valid public key")]
InvalidKeyData,
}
/// Deserialises the [`PublicKey`] from it's base32 encoding.
/// Parses a [`PublicKey`] from its hex or base32 encoding.
///
/// [`Display`] is capable of serialising this format.
/// [`Display`] produces the hex encoding.
impl FromStr for PublicKey {
type Err = KeyParsingError;
+7 -9
View File
@@ -1,6 +1,6 @@
[package]
name = "iroh-dns-server"
version = "1.0.0-rc.1"
version = "1.0.0"
edition = "2024"
description = "A pkarr relay and DNS server"
license = "MIT OR Apache-2.0"
@@ -28,20 +28,18 @@ hickory-server = { version = "0.26.0", features = ["https-ring"] }
http = "1.0.0"
humantime = "2.2.0"
humantime-serde = "1.1.1"
iroh-base = { version = "1.0.0-rc.1", path = "../iroh-base", features = ["key"] }
iroh-metrics = { version = "=1.0.0-rc.0", features = ["service"] }
iroh-dns = { version = "1.0.0-rc.1", path = "../iroh-dns" }
iroh-base = { version = "1.0.0", path = "../iroh-base", features = ["key"] }
iroh-metrics = { version = "1.0.1", features = ["service"] }
iroh-dns = { version = "1.0.0", path = "../iroh-dns" }
lru = "0.18.0"
mainline = "6"
mainline = "7"
n0-future = "0.3"
rcgen = "0.14"
redb = "4.1.0"
regex = "1.10.3"
rustls = { version = "0.23.33", default-features = false }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
struct_iterable = "0.1.1"
n0-error = "=1.0.0-rc.0"
n0-error = "1.0.0"
strum = { version = "0.28", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
tokio-rustls = { version = "0.26", default-features = false, features = ["logging"] }
@@ -60,7 +58,7 @@ url = "2.5.3"
criterion = "0.8.0"
data-encoding = "2.3.3"
hickory-resolver = { version = "0.26.0", features = ["tls-ring", "https-ring"] }
iroh = { version = "1.0.0-rc.1", path = "../iroh" }
iroh = { version = "1.0.0", path = "../iroh" }
n0-tracing-test = "0.3"
rand = "0.10"
simple-dns = "0.11"
+3 -1
View File
@@ -13,7 +13,7 @@ pub struct Metrics {
pub pkarr_publish_noop: Counter,
/// Total number of DNS requests across all transports.
pub dns_requests: Counter,
/// Number of DNS requests received over UDP or TCP.
/// Number of DNS requests received over UDP.
pub dns_requests_udp: Counter,
/// Number of DNS requests received over HTTPS (DoH).
pub dns_requests_https: Counter,
@@ -34,6 +34,8 @@ pub struct Metrics {
/// Number of signed packets newly inserted into the store.
pub store_packets_inserted: Counter,
/// Number of signed packets removed from the store.
///
/// Currently always at 0 because the removal API is not used.
pub store_packets_removed: Counter,
/// Number of times an existing signed packet was replaced by a newer one.
pub store_packets_updated: Counter,
+3 -3
View File
@@ -1,6 +1,6 @@
[package]
name = "iroh-dns"
version = "1.0.0-rc.1"
version = "1.0.0"
edition = "2024"
description = "DNS-based endpoint discovery for iroh"
license = "MIT OR Apache-2.0"
@@ -15,9 +15,9 @@ workspace = true
[dependencies]
arc-swap = "1.9.1"
derive_more = { version = "2.0.1", features = ["debug"] }
iroh-base = { version = "1.0.0-rc.1", path = "../iroh-base", default-features = false, features = ["key", "relay"] }
iroh-base = { version = "1.0.0", path = "../iroh-base", default-features = false, features = ["key", "relay"] }
lru = "0.18.0"
n0-error = "=1.0.0-rc.0"
n0-error = "1.0.0"
n0-future = "0.3"
portable-atomic = "1"
rand = "0.10"
+1 -1
View File
@@ -394,7 +394,7 @@ impl DnsResolver {
///
/// We first try to read the system's resolver from `/etc/resolv.conf`.
/// This does not work at least on some Androids, therefore we fallback
/// to the default `ResolverConfig` which uses eg. to google's `8.8.8.8` or `8.8.4.4`.
/// to the default `ResolverConfig` which uses e.g. Google's `8.8.8.8` or `8.8.4.4`.
pub fn new() -> Self {
Builder::default().with_system_defaults().build()
}
+9 -9
View File
@@ -3,12 +3,12 @@
//! Dialing by [`EndpointId`] is supported by iroh endpoints publishing [Pkarr] records to DNS
//! servers or the Mainline DHT. This module supports creating and parsing these records.
//!
//! [`EndpointInfo`] combines an [`iroh_base::EndpointId`] with [`EndpointData`] —
//! [`EndpointInfo`] combines an [`iroh_base::EndpointId`] with [`EndpointData`]:
//! the addressing and metadata that discovery services publish and resolve.
//! Discovery services use [`AddrFilter`] to control which addresses are published.
//!
//! This module also provides serialization to and from pkarr signed packets and
//! DNS TXT records. See the [`crate::attrs`] module for the on-the-wire format.
//! DNS TXT records.
//!
//! DNS records are published under the following names:
//!
@@ -120,7 +120,7 @@ impl EndpointData {
self.add_addrs(addresses.into_iter().map(TransportAddr::Ip))
}
/// Adds addresses to the endpoint data in the given ordered, but with duplicates filtered.
/// Adds addresses to the endpoint data in the given order, but with duplicates filtered.
pub fn add_addrs(&mut self, addrs: impl IntoIterator<Item = TransportAddr>) {
let mut addr_set = dedup(&mut self.addrs);
for addr in addrs.into_iter() {
@@ -131,7 +131,7 @@ impl EndpointData {
}
}
/// Sets the user-defined data and returns the updated endpoint data.
/// Sets the user-defined data.
pub fn set_user_data(&mut self, user_data: Option<UserData>) {
self.user_data = user_data;
}
@@ -142,7 +142,7 @@ impl EndpointData {
.retain(|addr| !matches!(addr, TransportAddr::Ip(_)));
}
/// Removes all direct addresses from the endpoint data.
/// Removes all relay URLs from the endpoint data.
pub fn clear_relay_urls(&mut self) {
self.addrs
.retain(|addr| !matches!(addr, TransportAddr::Relay(_)));
@@ -169,12 +169,12 @@ impl EndpointData {
})
}
/// Returns the full list of all known addresses
/// Returns the full list of all known addresses.
pub fn addrs(&self) -> impl Iterator<Item = &TransportAddr> {
self.addrs.iter()
}
/// Does this have any addresses?
/// Returns whether this has any addresses.
pub fn has_addrs(&self) -> bool {
!self.addrs.is_empty()
}
@@ -294,9 +294,9 @@ impl From<EndpointAddr> for EndpointData {
}
}
// User-defined data that can be published and resolved through endpoint discovery.
/// User-defined data that can be published and resolved through endpoint discovery.
///
/// Under the hood this is a UTF-8 String is no longer than [`UserData::MAX_LENGTH`] bytes.
/// Under the hood this is a UTF-8 string no longer than [`UserData::MAX_LENGTH`] bytes.
///
/// Iroh does not keep track of or examine the user-defined data.
///
+7 -9
View File
@@ -1,6 +1,6 @@
[package]
name = "iroh-relay"
version = "1.0.0-rc.1"
version = "1.0.0"
edition = "2024"
readme = "README.md"
description = "Iroh's relay server and client"
@@ -33,11 +33,11 @@ http = "1"
http-body-util = "0.1.0"
hyper = { version = "1", features = ["server", "client", "http1"] }
hyper-util = "0.1.1"
iroh-base = { version = "1.0.0-rc.1", path = "../iroh-base", default-features = false, features = ["key", "relay"] }
iroh-dns = { version = "1.0.0-rc.1", path = "../iroh-dns" }
iroh-metrics = { version = "=1.0.0-rc.0", default-features = false }
iroh-base = { version = "1.0.0", path = "../iroh-base", default-features = false, features = ["key", "relay"] }
iroh-dns = { version = "1.0.0", path = "../iroh-dns" }
iroh-metrics = { version = "1.0.1", default-features = false }
lru = "0.18.0"
n0-error = "=1.0.0-rc.0"
n0-error = "1.0.0"
n0-future = "0.3"
num_enum = "0.7"
pin-project = "1"
@@ -46,8 +46,8 @@ postcard = { version = "1", default-features = false, features = [
"use-std",
"experimental-derive",
] }
noq = { version = "=1.0.0-rc.1", default-features = false, features = ["rustls"] }
noq-proto = { version = "=1.0.0-rc.1", default-features = false }
noq = { version = "1.0.0", default-features = false, features = ["rustls"] }
noq-proto = { version = "1.0.0", default-features = false }
rand = "0.10"
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider"] }
rustls = { version = "0.23.33", default-features = false }
@@ -71,7 +71,6 @@ webpki_types = { package = "rustls-pki-types", version = "1.12" }
# server feature
clap = { version = "4", features = ["derive"], optional = true }
dashmap = { version = "6.1.0", optional = true }
ahash = { version = "0.8.11", optional = true } # minimal version fix
rcgen = { version = "0.14", optional = true }
reloadable-state = { version = "0.1", optional = true }
rustls-cert-reloadable-resolver = { version = "0.7.1", optional = true }
@@ -141,7 +140,6 @@ server = [
"tokio/rt-multi-thread",
"dep:clap",
"dep:dashmap",
"dep:ahash",
"dep:rcgen",
"dep:reloadable-state",
"dep:rustls-cert-file-reader",
+1 -1
View File
@@ -77,7 +77,7 @@ impl ProtocolVersion {
Self::all().collect::<Vec<_>>().join(", ")
}
/// Returns all supported protocol versions in a comma-seperated string as an HTTP header value.
/// Returns all supported protocol versions in a comma-separated string as an HTTP header value.
pub fn all_as_header_value() -> HeaderValue {
HeaderValue::from_bytes(Self::all_joined().as_bytes()).expect("valid header name")
}
+5 -7
View File
@@ -51,15 +51,13 @@ pub use crate::{
relay_map::{RelayConfig, RelayMap, RelayQuicConfig},
};
/// This trait allows anything that ends up potentially
/// wrapping a TLS stream use the underlying [`export_keying_material`]
/// function.
///
/// [`export_keying_material`]: rustls::ConnectionCommon::export_keying_material
/// Trait for extracting keying material from a TLS connection.
///
/// This is used during the relay handshake to establish a shared secret
/// between the client and server for authentication purposes.
/// This allows anything that ends up potentially wrapping a TLS stream to use the
/// underlying [`export_keying_material`] function. It is used during the relay handshake
/// to establish a shared secret between the client and server for authentication purposes.
///
/// [`export_keying_material`]: rustls::ConnectionCommon::export_keying_material
pub trait ExportKeyingMaterial {
/// If this type ends up wrapping a TLS stream, then this tries
/// to export keying material by calling the underlying [`export_keying_material`]
+46 -7
View File
@@ -21,6 +21,7 @@ use iroh_relay::{
self as relay, Access, AccessControl, AcmeConfig, ClientRateLimit, ClientRequest,
DEFAULT_CERT_RELOAD_INTERVAL, QuicConfig, reloading_resolver,
},
tls::CaTlsConfig,
};
use n0_error::{AnyError, Result, StdResultExt, bail_any};
use serde::{Deserialize, Serialize};
@@ -37,6 +38,10 @@ const X_IROH_ENDPOINT_ID: &str = "X-Iroh-NodeId";
const ENV_HTTP_BEARER_TOKEN: &str = "IROH_RELAY_HTTP_BEARER_TOKEN";
/// Environment variable to verify relay access (without an external auth service)
const ENV_RELAY_ACCESS_TOKEN: &str = "IROH_RELAY_ACCESS_TOKEN";
/// Environment variable to override the ACME directory URL.
const ENV_ACME_URL: &str = "IROH_RELAY_ACME_URL";
/// Environment variable to trust an additional CA for the ACME server's TLS certificate.
const ENV_ACME_CA: &str = "IROH_RELAY_ACME_CA";
/// A relay server for iroh.
#[derive(Parser, Debug, Clone)]
@@ -400,7 +405,8 @@ struct TlsConfig {
/// port set to [`iroh_relay::defaults::DEFAULT_RELAY_QUIC_PORT`]
quic_bind_addr: Option<SocketAddr>,
/// Certificate hostname when using LetsEncrypt.
hostname: Option<String>,
#[serde(default, deserialize_with = "string_or_seq")]
hostname: Vec<String>,
/// Mode for getting a cert.
///
/// Possible options: 'Manual', 'LetsEncrypt'.
@@ -479,6 +485,23 @@ impl TlsConfig {
}
}
fn string_or_seq<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum StringOrVec {
One(String),
Many(Vec<String>),
}
Ok(match StringOrVec::deserialize(deserializer)? {
StringOrVec::One(s) => vec![s],
StringOrVec::Many(v) => v,
})
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct Limits {
/// Rate limit for accepting new connection. Unlimited if not set.
@@ -614,18 +637,34 @@ async fn load_cert_config(tls: &TlsConfig) -> Result<relay::CertConfig> {
relay::CertConfig::Manual { server_config }
}
CertMode::LetsEncrypt => {
let hostname = tls
.hostname
.clone()
.std_context("LetsEncrypt needs a hostname")?;
let domains = tls.hostname.clone();
if domains.is_empty() {
bail_any!("LetsEncrypt needs at least one hostname");
}
let contact = tls
.contact
.clone()
.std_context("LetsEncrypt needs a contact email")?;
let acme_config = AcmeConfig::letsencrypt(tls.prod_tls)
.domains(vec![hostname])
let acme_config = if let Ok(url) = std::env::var(ENV_ACME_URL) {
AcmeConfig::new(url)
} else {
AcmeConfig::letsencrypt(tls.prod_tls)
};
let mut acme_config = acme_config
.domains(domains)
.contact(vec![format!("mailto:{contact}")])
.cache_path(tls.cert_dir());
// Trust an additional CA for the ACME server's TLS certificate. Useful for testing
// against a local ACME server such as pebble, whose certificate is not signed by a
// publicly trusted CA.
if let Ok(ca_path) = std::env::var(ENV_ACME_CA) {
let extra_roots = CertificateDer::pem_file_iter(&ca_path)
.std_context("failed to read IROH_RELAY_ACME_CA")?
.collect::<Result<Vec<_>, _>>()
.std_context("failed to parse IROH_RELAY_ACME_CA")?;
acme_config =
acme_config.tls_config(CaTlsConfig::default().with_extra_roots(extra_roots));
}
relay::CertConfig::LetsEncrypt {
acme_config,
server_config_builder: server_config,
+1 -2
View File
@@ -39,8 +39,7 @@ pub enum FrameType {
///
/// 32B pub key of peer that's gone
EndpointGone = 8,
/// Messages with these frames will be ignored.
/// 8 byte ping payload, to be echoed back in FrameType::Pong
/// 8 byte ping payload, to be echoed back in a [`FrameType::Pong`].
Ping = 9,
/// 8 byte payload, the contents of ping being replied to
Pong = 10,
+1 -5
View File
@@ -377,16 +377,12 @@ pub(crate) async fn clientside(
}
}
/// This represents successful authentication for the client with the `client_key` public key
/// via the authentication [`Mechanism`] `mechanism`.
///
/// You must call [`SuccessfulAuthentication::authorize_if`] to finish the protocol.
#[cfg(feature = "server")]
/// Result of a successful authentication handshake.
///
/// This struct represents a client that has successfully authenticated itself to the relay
/// server. The authorization must still be confirmed by calling [`Self::authorize_if`] to
/// complete the protocol and notify the client of success or failure.
#[cfg(feature = "server")]
#[derive(Debug)]
#[must_use = "the protocol is not finished unless `authorize_if` is called"]
pub struct SuccessfulAuthentication {
+40 -9
View File
@@ -58,6 +58,7 @@ use crate::{
defaults::DEFAULT_KEY_CACHE_CAPACITY,
http::{AUTH_TOKEN_URL_QUERY_PARAM, ProtocolVersion, RELAY_PROBE_PATH},
quic::server::{QuicServer, QuicSpawnError, ServerHandle as QuicServerHandle},
tls::CaTlsConfig,
};
pub mod client;
@@ -465,7 +466,7 @@ pub struct TlsConfig {
/// the main relay server this has to be on a different port. When TLS is not enabled
/// this is served on the [`RelayConfig::http_bind_addr`] socket address.
///
/// Normally you'd choose port `80`.
/// Normally you'd choose port `443`.
pub https_bind_addr: SocketAddr,
/// Mode for getting a cert.
pub cert: CertConfig,
@@ -486,12 +487,16 @@ impl TlsConfig {
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct Limits {
/// Rate limit for accepting new connection. Unlimited if not set.
pub accept_conn_limit: Option<f64>,
/// Burst limit for accepting new connection. Unlimited if not set.
pub accept_conn_burst: Option<usize>,
/// Rate limits for incoming traffic from a client connection.
pub client_rx: Option<ClientRateLimit>,
/// Rate limit for accepting new connections. Unlimited if not set.
///
/// Not currently implemented, setting this has no effect.
pub accept_conn_limit: Option<f64>,
/// Burst limit for accepting new connections. Unlimited if not set.
///
/// Not currently implemented, setting this has no effect.
pub accept_conn_burst: Option<usize>,
}
/// Per-client rate limit configuration.
@@ -545,6 +550,7 @@ pub struct AcmeConfig {
pub(crate) domains: Vec<String>,
pub(crate) contact: Vec<String>,
pub(crate) cache_path: Option<PathBuf>,
pub(crate) tls_config: CaTlsConfig,
}
impl AcmeConfig {
@@ -555,6 +561,7 @@ impl AcmeConfig {
domains: Vec::new(),
contact: Vec::new(),
cache_path: None,
tls_config: CaTlsConfig::default(),
}
}
@@ -589,6 +596,16 @@ impl AcmeConfig {
self.cache_path = Some(path);
self
}
/// Sets the [`CaTlsConfig`] used to verify the ACME server's TLS certificate.
///
/// Defaults to [`CaTlsConfig::embedded`]. Set a config with extra roots when targeting
/// an ACME server whose certificate is not signed by a publicly trusted CA, such as a
/// local test server.
pub fn tls_config(mut self, tls_config: CaTlsConfig) -> Self {
self.tls_config = tls_config;
self
}
}
/// A running Relay + QAD server.
@@ -632,6 +649,11 @@ pub enum SpawnError {
TlsHeaderParse { source: InvalidHeaderValue },
#[error("Failed to bind TcpListener")]
BindTlsListener { source: std::io::Error },
#[error("Failed to build ACME client TLS config")]
AcmeClientTlsConfig {
#[error(std_err)]
source: std::io::Error,
},
#[error("No local address")]
NoLocalAddr { source: std::io::Error },
#[error("Failed to bind server socket to {addr}")]
@@ -727,11 +749,20 @@ impl Server {
server_config_builder,
} => {
let cache = acme_config.cache_path.map(DirCache::new);
let crypto_provider =
server_config_builder.crypto_provider().clone();
let client_tls_config = acme_config
.tls_config
.client_config(crypto_provider)
.map_err(|err| e!(SpawnError::AcmeClientTlsConfig, err))?;
let config =
tokio_rustls_acme::AcmeConfig::new(acme_config.domains)
.contact(acme_config.contact)
.directory(acme_config.directory_url)
.cache_option(cache);
tokio_rustls_acme::AcmeConfig::new_with_client_tls_config(
acme_config.domains,
Arc::new(client_tls_config),
)
.contact(acme_config.contact)
.directory(acme_config.directory_url)
.cache_option(cache);
let mut state = config.state();
let resolver = state.resolver().clone();
let server_config =
+1 -1
View File
@@ -42,7 +42,7 @@ pub(super) struct Packet {
data: Datagrams,
}
/// Configuration for a [`Client`].
/// Configuration for a client connection.
///
/// Generic over the stream type to support different WebSocket implementations.
#[derive(Debug)]
+1 -2
View File
@@ -21,12 +21,11 @@ use crate::{
server::{client::SendError, metrics::Metrics},
};
/// Manages the connections to all currently connected clients.
#[derive(Debug, Clone, Default)]
/// Registry of connected relay clients.
///
/// This type manages the collection of active client connections and
/// handles routing messages between them.
#[derive(Debug, Clone, Default)]
pub struct Clients(Arc<Inner>);
#[derive(Debug, Default)]
+34 -12
View File
@@ -10,40 +10,60 @@ pub struct Metrics {
/*
* Metrics about packets
*/
/// Bytes sent from a `FrameType::SendPacket`
/// Bytes sent to a client in [`RelayToClientDatagram`] or [`RelayToClientDatagramBatch`] frames.
///
/// [`RelayToClientDatagram`]: crate::protos::common::FrameType::RelayToClientDatagram
/// [`RelayToClientDatagramBatch`]: crate::protos::common::FrameType::RelayToClientDatagramBatch
#[metrics(help = "Number of bytes sent.")]
pub bytes_sent: Counter,
/// Bytes received from a `FrameType::SendPacket`
/// Bytes received from a client in [`ClientToRelayDatagram`] or [`ClientToRelayDatagramBatch`] frames.
///
/// [`ClientToRelayDatagram`]: crate::protos::common::FrameType::ClientToRelayDatagram
/// [`ClientToRelayDatagramBatch`]: crate::protos::common::FrameType::ClientToRelayDatagramBatch
#[metrics(help = "Number of bytes received.")]
pub bytes_recv: Counter,
/// `FrameType::SendPacket` sent
/// [`RelayToClientDatagram`] or [`RelayToClientDatagramBatch`] frames sent to a client.
///
/// [`RelayToClientDatagram`]: crate::protos::common::FrameType::RelayToClientDatagram
/// [`RelayToClientDatagramBatch`]: crate::protos::common::FrameType::RelayToClientDatagramBatch
#[metrics(help = "Number of 'send' packets relayed.")]
pub send_packets_sent: Counter,
/// `FrameType::SendPacket` received
/// [`ClientToRelayDatagram`] or [`ClientToRelayDatagramBatch`] frames received from a client.
///
/// [`ClientToRelayDatagram`]: crate::protos::common::FrameType::ClientToRelayDatagram
/// [`ClientToRelayDatagramBatch`]: crate::protos::common::FrameType::ClientToRelayDatagramBatch
#[metrics(help = "Number of 'send' packets received.")]
pub send_packets_recv: Counter,
/// `FrameType::SendPacket` dropped
/// [`RelayToClientDatagram`] or [`RelayToClientDatagramBatch`] frames dropped instead of being
/// delivered to a client, because the recipient is not connected or writing to its stream failed.
///
/// Note that frames dropped because the recipient's send queue is full or closed are not counted
/// here.
///
/// [`RelayToClientDatagram`]: crate::protos::common::FrameType::RelayToClientDatagram
/// [`RelayToClientDatagramBatch`]: crate::protos::common::FrameType::RelayToClientDatagramBatch
#[metrics(help = "Number of 'send' packets dropped.")]
pub send_packets_dropped: Counter,
/// Packets of other `FrameType`s sent
/// Intended to count sent frames other than datagrams, but currently unused (never incremented).
#[metrics(help = "Number of packets sent that were not 'send' packets")]
pub other_packets_sent: Counter,
/// Packets of other `FrameType`s received
/// Intended to count received frames other than datagrams, but currently unused (never incremented).
#[metrics(help = "Number of packets received that were not 'send' packets")]
pub other_packets_recv: Counter,
/// Packets of other `FrameType`s dropped
/// Intended to count dropped frames other than datagrams, but currently unused (never incremented).
#[metrics(help = "Number of times, non-send packet was dropped.")]
pub other_packets_dropped: Counter,
/// Number of `FrameType::Ping`s received
/// Number of [`FrameType::Ping`](crate::protos::common::FrameType::Ping) frames received from a client.
#[metrics(help = "Number of times the server has received a Ping from a client.")]
pub got_ping: Counter,
/// Number of `FrameType::Pong`s sent
/// Number of [`FrameType::Pong`](crate::protos::common::FrameType::Pong) frames sent to a client.
#[metrics(help = "Number of times the server has sent a Pong to a client.")]
pub sent_pong: Counter,
/// Number of `FrameType::Unknown` received
/// Intended to count received frames with an unrecognized [`FrameType`](crate::protos::common::FrameType),
/// but currently unused (never incremented).
#[metrics(help = "Number of unknown frames sent to this server.")]
pub unknown_frames: Counter,
@@ -57,7 +77,9 @@ pub struct Metrics {
*/
/// Number of times this server has accepted a connection.
pub accepts: Counter,
/// Number of connections we have removed because of an error
/// Number of times a client connection was disconnected.
///
/// Incremented once per connection, paired with [`Self::accepts`].
#[metrics(help = "Number of clients that have then disconnected.")]
pub disconnects: Counter,
+2 -2
View File
@@ -324,8 +324,8 @@ impl AsyncWrite for MaybeTlsStream {
///
/// The writes to the sink are not rate limited.
///
/// This potentially buffers one frame if the rate limiter does not allows this frame.
/// While the frame is buffered the undernlying stream is no longer polled.
/// This potentially buffers one frame if the rate limiter does not allow this frame.
/// While the frame is buffered the underlying stream is no longer polled.
#[derive(Debug)]
pub(crate) struct RateLimited<S> {
inner: S,
+1 -1
View File
@@ -217,7 +217,7 @@ impl CaTlsConfig {
/// Function to build a [`ServerCertVerifier`] from a [`CryptoProvider`].
///
/// See [`CaTlsConfig::custom_server_cert_verifier].
/// See [`CaTlsConfig::custom_server_cert_verifier`].
pub type ServerCertVerifierBuilder = Arc<
dyn Fn(Arc<CryptoProvider>) -> io::Result<Arc<dyn ServerCertVerifier>> + Send + Sync + 'static,
>;
+164
View File
@@ -0,0 +1,164 @@
#!/usr/bin/env bash
#
# End-to-end test for iroh-relay multi-hostname ACME support against a local
# pebble ACME server, exercising real TLS-ALPN-01 challenge validation.
#
# Starts pebble, then iroh-relay in LetsEncrypt cert mode pointed at pebble via
# IROH_RELAY_ACME_URL / IROH_RELAY_ACME_CA, and checks with curl that:
# - every configured hostname is served a cert signed by pebble's CA,
# - an unconfigured hostname is refused at the TLS handshake, and
# - pebble actually completed a challenge (no PEBBLE_VA_ALWAYS_VALID).
#
# pebble's validation authority resolves each hostname and connects back to the
# relay's TLS-ALPN-01 responder. Two things make that callback reach the relay:
# pebble's validation TLS port is set to the relay's HTTPS port, and an
# /etc/hosts mounted into the pebble container maps each hostname to 127.0.0.1
# (pebble reads it through its system resolver, so no separate DNS server is
# needed). Host networking lets pebble's loopback reach the relay's listener.
#
# Exits 0 if all checks pass, 1 otherwise.
#
# Requirements: docker (Linux host networking), curl, jq, the iroh-relay sources.
set -euo pipefail
PEBBLE_IMAGE="${PEBBLE_IMAGE:-ghcr.io/letsencrypt/pebble:latest}"
RELAY_HTTP_PORT="${RELAY_HTTP_PORT:-8080}"
RELAY_HTTPS_PORT="${RELAY_HTTPS_PORT:-8443}"
# The workdir is always a fresh mktemp directory, never taken from the
# environment. This is what keeps cleanup safe: nothing here can ever delete a
# path the user supplied, no matter how the environment is set. The pebble
# container name is derived from it, so a run never force-removes a container it
# did not create.
WORK="$(mktemp -d "${TMPDIR:-/tmp}/iroh-relay-pebble.XXXXXXXX")"
PEBBLE_NAME="${PEBBLE_NAME:-$(basename "$WORK")}"
# Reject non-numeric ports so a bad value cannot leak into the generated config
# or the jq program further down.
case "${RELAY_HTTP_PORT}:${RELAY_HTTPS_PORT}" in
*[!0-9:]*) echo "RELAY_HTTP_PORT and RELAY_HTTPS_PORT must be numeric" >&2; exit 1 ;;
esac
# Hostnames the relay is configured to serve, plus one it is not.
HOSTS=(relay-a.localhost relay-b.localhost)
HOST_BAD=relay-evil.localhost
PEBBLE_DIR_URL="https://localhost:14000/dir"
PEBBLE_MGMT_URL="https://localhost:15000"
log() { printf '\n=== %s ===\n' "$*"; }
ok() { printf ' [ ok ] %s\n' "$*"; }
fail() {
printf '\n [FAIL] %s\n' "$*" >&2
[ -f "$WORK/relay.log" ] && { echo "--- relay.log (tail) ---" >&2; tail -n 30 "$WORK/relay.log" >&2; }
docker logs "$PEBBLE_NAME" >/dev/null 2>&1 && { echo "--- pebble.log (tail) ---" >&2; docker logs "$PEBBLE_NAME" 2>&1 | tail -20 >&2; }
exit 1
}
RELAY_PID=""
cleanup() {
set +e
[ -n "$RELAY_PID" ] && kill "$RELAY_PID" 2>/dev/null
docker rm -f "$PEBBLE_NAME" >/dev/null 2>&1
}
trap cleanup EXIT
# curl the relay over HTTPS for a given hostname. --fail turns a non-2xx or TLS
# error into a non-zero exit; --resolve pins the SNI hostname to loopback.
curl_relay() {
curl -s --fail --max-time 5 -o /dev/null \
--cacert "$WORK/pebble-issuer-root.pem" \
--resolve "$1:${RELAY_HTTPS_PORT}:127.0.0.1" \
"https://$1:${RELAY_HTTPS_PORT}/healthz"
}
# --- start pebble ------------------------------------------------------------
mkdir -p "$WORK/certs"
{ echo "127.0.0.1 localhost"; echo "::1 localhost"
for host in "${HOSTS[@]}"; do echo "127.0.0.1 $host"; done; } > "$WORK/hosts"
log "starting pebble ($PEBBLE_IMAGE)"
# Derive pebble's config from the image default, setting its TLS-ALPN-01
# validation port to the relay's HTTPS port so the callback lands on the relay.
cid=$(docker create "$PEBBLE_IMAGE")
docker cp "$cid:/test/config/pebble-config.json" "$WORK/pebble-config.in.json" >/dev/null
docker rm "$cid" >/dev/null
jq ".pebble.tlsPort = ${RELAY_HTTPS_PORT}" "$WORK/pebble-config.in.json" > "$WORK/pebble-config.json"
docker run -d --rm --name "$PEBBLE_NAME" --network host \
-e PEBBLE_VA_NOSLEEP=1 -e PEBBLE_WFE_NONCEREJECT=0 \
-v "$WORK/pebble-config.json:/pebble-config.json:ro" \
-v "$WORK/hosts:/etc/hosts:ro" \
"$PEBBLE_IMAGE" -config /pebble-config.json >/dev/null
for i in $(seq 1 30); do
curl -sk -o /dev/null "$PEBBLE_DIR_URL" && break
[ "$i" = 30 ] && fail "pebble did not come up"
sleep 0.5
done
ok "pebble up (validation port = ${RELAY_HTTPS_PORT})"
# pebble.minica.pem signs pebble's own ACME/management TLS, so the relay must
# trust it (IROH_RELAY_ACME_CA). The certs pebble *issues* chain to a separate
# root served by the management interface, which curl needs to verify the relay.
docker cp "$PEBBLE_NAME:/test/certs/pebble.minica.pem" "$WORK/pebble.minica.pem" >/dev/null
curl -s --cacert "$WORK/pebble.minica.pem" "$PEBBLE_MGMT_URL/roots/0" -o "$WORK/pebble-issuer-root.pem"
ok "fetched pebble CAs"
# --- start relay -------------------------------------------------------------
hostnames=$(printf '"%s", ' "${HOSTS[@]}")
cat > "$WORK/relay.toml" <<EOF
enable_relay = true
enable_quic_addr_discovery = false
enable_metrics = false
http_bind_addr = "0.0.0.0:${RELAY_HTTP_PORT}"
[tls]
https_bind_addr = "0.0.0.0:${RELAY_HTTPS_PORT}"
hostname = [ ${hostnames%, } ]
cert_mode = "LetsEncrypt"
contact = "test@iroh.test"
cert_dir = "${WORK}/certs"
EOF
log "starting iroh-relay (hostnames: ${HOSTS[*]})"
IROH_RELAY_ACME_URL="$PEBBLE_DIR_URL" \
IROH_RELAY_ACME_CA="$WORK/pebble.minica.pem" \
RUST_LOG="${RUST_LOG:-iroh_relay=debug,rustls_acme=info,warn}" \
cargo run --quiet --bin iroh-relay --features server -- \
--config-path "$WORK/relay.toml" > "$WORK/relay.log" 2>&1 &
RELAY_PID=$!
# --- checks ------------------------------------------------------------------
log "waiting for the relay to pass validation and provision a cert"
for i in $(seq 1 90); do
kill -0 "$RELAY_PID" 2>/dev/null || fail "relay exited early"
curl_relay "${HOSTS[0]}" 2>/dev/null && break
[ "$i" = 90 ] && fail "relay did not provision a cert in time"
sleep 1
done
ok "relay provisioned a cert"
log "every configured hostname serves a pebble-signed cert"
for host in "${HOSTS[@]}"; do
curl_relay "$host" || fail "$host: expected a valid pebble-signed cert"
ok "$host: served a pebble-signed cert, verified by curl"
done
log "an unconfigured hostname is refused"
curl_relay "$HOST_BAD" 2>/dev/null && fail "$HOST_BAD: handshake unexpectedly succeeded"
ok "$HOST_BAD: TLS handshake refused, as expected"
log "pebble ran a real challenge validation"
docker logs "$PEBBLE_NAME" 2>&1 | grep -q "set VALID by completed challenge" \
|| fail "pebble recorded no completed challenge (was validation skipped?)"
docker logs "$PEBBLE_NAME" 2>&1 | grep -E "set VALID by completed challenge|Issued certificate" | tail -4
ok "pebble validated the TLS-ALPN-01 challenge and issued the cert"
log "ALL CHECKS PASSED"
echo "artifacts (logs, certs, config) left in $WORK"
+21 -21
View File
@@ -1,6 +1,6 @@
[package]
name = "iroh"
version = "1.0.0-rc.1"
version = "1.0.0"
edition = "2024"
readme = "README.md"
description = "p2p quic connections dialed by public key"
@@ -31,19 +31,19 @@ derive_more = { version = "2.0.1", features = ["debug", "display", "from", "try_
ed25519-dalek = { version = "=3.0.0-rc.0", features = ["serde", "rand_core", "zeroize", "pkcs8", "pem"] }
http = "1"
ipnet = "2"
iroh-base = { version = "1.0.0-rc.1", default-features = false, features = ["key", "relay"], path = "../iroh-base" }
iroh-dns = { version = "1.0.0-rc.1", path = "../iroh-dns" }
iroh-relay = { version = "1.0.0-rc.1", path = "../iroh-relay", default-features = false }
iroh-base = { version = "1.0.0", default-features = false, features = ["key", "relay"], path = "../iroh-base" }
iroh-dns = { version = "1.0.0", path = "../iroh-dns" }
iroh-relay = { version = "1.0.0", path = "../iroh-relay", default-features = false }
n0-future = "0.3"
n0-error = "=1.0.0-rc.0"
n0-watcher = "=1.0.0-rc.0"
netwatch = "0.18"
n0-error = "1.0.0"
n0-watcher = "1.0.0"
netwatch = "0.19"
papaya = { version = "0.2.3", default-features = false }
pin-project = "1"
portable-atomic = "1"
noq = { version = "=1.0.0-rc.1", default-features = false, features = ["rustls"] }
noq-proto = { version = "=1.0.0-rc.1", default-features = false }
noq-udp = { version = "=1.0.0-rc.1", default-features = false }
noq = { version = "1.0.0", default-features = false, features = ["rustls"] }
noq-proto = { version = "1.0.0", default-features = false }
noq-udp = { version = "1.0.0", default-features = false }
rand = "0.10"
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "stream"] }
rustc-hash = "2"
@@ -61,12 +61,10 @@ tokio-stream = { version = "0.1.15", features = ["sync"] }
tokio-util = { version = "0.7", features = ["io-util", "io", "rt"] }
tracing = "0.1"
url = { version = "2.5", features = ["serde"] }
webpki = { package = "rustls-webpki", version = "0.103.7", default-features = false, features = ["std"] }
webpki_types = { package = "rustls-pki-types", version = "1.12" }
webpki-roots = "1.0.3"
# metrics
iroh-metrics = { version = "=1.0.0-rc.0", default-features = false }
iroh-metrics = { version = "1.0.1", default-features = false }
futures-util = "0.3"
@@ -75,8 +73,8 @@ axum = { version = "0.8", optional = true }
# non-wasm-in-browser dependencies
[target.'cfg(not(all(target_family = "wasm", target_os = "unknown")))'.dependencies]
portmapper = { version = "0.18", optional = true, default-features = false }
noq = { version = "=1.0.0-rc.1", default-features = false, features = ["runtime-tokio", "rustls"] }
portmapper = { version = "0.19", optional = true, default-features = false }
noq = { version = "1.0.0", default-features = false, features = ["runtime-tokio", "rustls"] }
tokio = { version = "1", features = [
"io-util",
"macros",
@@ -98,7 +96,7 @@ getrandom = { version = "0.4", features = ["wasm_js"] }
# target-common test/dev dependencies
[dev-dependencies]
console_error_panic_hook = "0.1"
n0-error = { version = "=1.0.0-rc.0", features = ["anyhow"] }
n0-error = { version = "1.0.0", features = ["anyhow"] }
postcard = { version = "1.1.1", features = ["use-std"] }
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
rand_chacha = "0.10"
@@ -121,7 +119,7 @@ tokio = { version = "1", features = [
"test-util",
] }
serde_json = "1"
iroh-relay = { version = "1.0.0-rc.1", path = "../iroh-relay", default-features = false, features = ["test-utils", "server"] }
iroh-relay = { version = "1.0.0", path = "../iroh-relay", default-features = false, features = ["test-utils", "server"] }
n0-tracing-test = "0.3"
clap = { version = "4", features = ["derive"] }
tracing-subscriber = { version = "0.3", features = [
@@ -129,7 +127,7 @@ tracing-subscriber = { version = "0.3", features = [
] }
indicatif = { version = "0.18", features = ["tokio"] }
parse-size = { version = "1.1.0", features = ['std'] }
iroh-base = { version = "1.0.0-rc.1", default-features = false, features = ["key", "relay"], path = "../iroh-base" }
iroh-base = { version = "1.0.0", default-features = false, features = ["key", "relay"], path = "../iroh-base" }
console = { version = "0.16" }
# wasm-in-browser test/dev dependencies
@@ -140,7 +138,7 @@ wasm-bindgen-test = "0.3.62"
# patchbay netsim test dependencies (linux only)
[target.'cfg(target_os = "linux")'.dev-dependencies]
ctor = "1.0"
patchbay = { version = "0.5", features = ["iroh-metrics"] }
patchbay = { version = "0.6", features = ["iroh-metrics"] }
testdir = "0.10"
[build-dependencies]
@@ -157,11 +155,13 @@ qlog = ["noq/qlog"]
# Use private Apple APIs to send multiple packets in a single syscall.
fast-apple-datapath = ["noq/fast-apple-datapath"]
# Use ring as the crypto backend.
tls-ring = ["noq/ring", "iroh-relay/tls-ring", "iroh-dns/tls-ring", "webpki/ring"]
tls-ring = ["noq/ring", "iroh-relay/tls-ring", "iroh-dns/tls-ring"]
# Use aws-lc-rs as the crypto backend, unless `ring` is also enabled.
tls-aws-lc-rs = ["noq/aws-lc-rs", "iroh-relay/tls-aws-lc-rs", "iroh-dns/tls-aws-lc-rs", "webpki/aws-lc-rs"]
tls-aws-lc-rs = ["noq/aws-lc-rs", "iroh-relay/tls-aws-lc-rs", "iroh-dns/tls-aws-lc-rs"]
# Unstable: Custom transport API (may change without notice)
unstable-custom-transports = []
# Unstable: API to access an endpoint's NetReport (may change without notice)
unstable-net-report = []
[package.metadata.docs.rs]
all-features = true
+49
View File
@@ -0,0 +1,49 @@
# Developing iroh
## Structured events
The library uses [tracing] both for logging and for *structured events*.
Events differ from normal logging by convention:
- The [target] is prefixed with `iroh::_events::`, with `::`-separated names.
- There is **no message**; the unique target indicates the meaning.
- The [fields] carry exclusively structured data.
- The [Level] is always `DEBUG`.
This lets automated tooling process events through custom subscribers while
still producing distinct output under the default tracing formatters, and makes
them unlikely to conflict with real modules.
An application can subscribe to the `iroh::_events` target separately. With the
default file logging it is also easy to grep for all events:
```sh
rg 'events::[a-z_\-:]+' path/to/iroh/logs/iroh.YYYY-MM-DD-NN.log
```
When adding events, aim for a high signal-to-noise ratio and design them to be
extracted automatically. To keep them distinct from normal logging, write them
with the `event!()` macro:
```rust,ignore
event!(
target: "iroh::_events::subject",
Level::DEBUG,
field = value,
);
```
## Building documentation
Building the documentation is only supported with `--all-features`. To also
document the cargo features required for certain APIs, pass the `iroh_docsrs`
cfg to rustdoc, which requires nightly Rust:
```sh
RUSTDOCFLAGS="--cfg iroh_docsrs" cargo +nightly doc --workspace --no-deps --all-features
```
[target]: https://docs.rs/tracing/latest/tracing/struct.Metadata.html#method.target
[fields]: https://docs.rs/tracing/latest/tracing/#recording-fields
[Level]: https://docs.rs/tracing/latest/tracing/struct.Level.html
[tracing]: https://docs.rs/tracing
+144 -66
View File
@@ -1,91 +1,153 @@
# iroh
<h1 align="center">
<a href="https://iroh.computer">
<img alt="iroh" src="https://raw.githubusercontent.com/n0-computer/iroh/main/.img/iroh_wordmark.svg" width="100" />
</a>
</h1>
Iroh is a library to establish direct connectivity between peers.
It's built on peer-to-peer [QUIC](https://en.wikipedia.org/wiki/QUIC) using both relays and holepunching.
The main structure for connection is the `Endpoint` entrypoint.
<h3 align="center">
less net work for networks
</h3>
Peer to peer connectivity is established with the help of a _relay server_. The relay server provides [QUIC Address Discovery](https://www.ietf.org/archive/id/draft-ietf-quic-address-discovery-00.html) (QAD) and hole-punching assistance for the peers. If no direct connection can be established, the connection is relayed via the server.
[![Documentation](https://img.shields.io/badge/docs-latest-blue.svg?style=flat-square)](https://docs.rs/iroh/)
[![Crates.io](https://img.shields.io/crates/v/iroh.svg?style=flat-square)](https://crates.io/crates/iroh)
[![Chat](https://img.shields.io/discord/1161119546170687619?logo=discord&style=flat-square)](https://discord.com/invite/DpmJgtU7cW)
[![Youtube](https://img.shields.io/badge/YouTube-red?logo=youtube&logoColor=white&style=flat-square)](https://www.youtube.com/@n0computer)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](LICENSE-MIT)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg?style=flat-square)](LICENSE-APACHE)
Peers must know and do verify the PeerID of each other before they can connect. When using a relay server to aid the connection establishment they will register with a home relay server using their PublicKey. Other peers which can not establish a direct connection can then establish connection via this relay server. This will try to assist establishing a direct connection using QAD and holepunching but continue relaying if not possible.
<div align="center">
<h3>
<a href="https://iroh.computer/docs">
Docs Site
</a>
<span> | </span>
<a href="https://docs.rs/iroh">
Rust Docs
</a>
</h3>
</div>
<br/>
Peers can also connect directly without using a relay server. For this, however the listening peer must be directly reachable by the connecting peer via one of it's addresses.
Iroh is a Rust library to establish direct connections between endpoints.
It gives you an API for dialing by public key. You say "connect to that
endpoint", and iroh finds and maintains the best connection for you.
## Examples
Under the hood iroh establishes peer-to-peer [QUIC] connections between
endpoints. The fastest route is a direct connection, so iroh tries to
[hole-punch] one whenever it can. If that fails it falls back to using
relay servers.
Examples for `iroh` are in `iroh/examples`, run them with `cargo run --example $NAME`. Details for each example are in the file/directory itself.
Because iroh is built on [QUIC], all connections are end-to-end encrypted and may
carry any number of concurrent streams. Dialing by public key also makes them mutually
authenticated, because each endpoint's public key is its TLS identity.
## Structured Events
## Overview
The library uses [tracing](https://docs.rs/tracing) to for logging as
well as for **structured events**. Events are different from normal
logging by convention:
An iroh endpoint is created and controlled by the [`Endpoint`]. Each endpoint
has a unique [`SecretKey`], whose public key is the endpoint's identity, the
[`EndpointId`]. Connections are authenticated against this key, which means an
[`EndpointId`] can't be impersonated.
- The [target] has a prefix of `$crate_name::_events` and target names
are `::` separated.
A connection is usually established with the help of a *relay server*. When an
endpoint is created it connects to the closest relay and designates it as its
*home relay*. Other endpoints reach it first through this relay, then both
sides use QUIC NAT traversal to establish a direct connection. In the rare
cases where a direct connection is not possible, traffic keeps flowing over the
relay.
For this library the target will always start with `iroh::_events::`.
Relay servers only forward encrypted packets addressed to Endpoint IDs, they
cannot read any traffic between endpoints.
- There is **no message**.
Endpoints can also connect directly without a relay, as long as the accepting
endpoint is directly reachable at one of its addresses.
Each event has a unique [target] which indicates the meaning.
To discover addressing information for an endpoint, iroh uses
[address lookup services]. With address lookup, you can connect to other
endpoints with only their [`EndpointId`]. Addressing information will then
be resolved on-demand.
- The event [fields] are exclusively used for structured data.
The [`N0` preset] installs the DNS/Pkarr address lookup service, which uses
servers hosted by [n0] to provide global lookup for endpoints.
- The [Level] is always `DEBUG`.
## Example
This is a compromise between being able to process events using
automated tooling using custom subscribers and them still producing
distinguishing output in logs when using the default tracing
subscriber formatters. While still being unlikely to conflict with
real modules.
[target]: https://docs.rs/tracing/latest/tracing/struct.Metadata.html#method.target
[fields]: https://docs.rs/tracing/latest/tracing/#recording-fields
[Level]: https://docs.rs/tracing/latest/tracing/struct.Level.html
### Using events
If desired an application can use the `$crate_name::_events` target to
handle events by a different subscriber. However with the default
file logging it is already easy to search for all events, e.g. using
ripgrep:
`rg 'events::[a-z_\-:]+' path/to/iroh/logs/iroh.YYYY-MM-DD-NN.log`
Which will also highlight the full target name by default on a colour
supporting terminal.
### Development
Be cautious about adding new events. Events aim for a high
signal-to-noise ratio. Events should be designed to be able to
extract in an automated way. If multiple events need to be related,
fields with special values can be used.
To make events distinct from normal logging in the code it is
recommended to write them using the `event!()` macro:
This is an echo protocol: the accepting side copies back whatever it receives.
The full, commented version is in [`echo.rs`](examples/echo.rs).
```rust
event!(
target: "iroh::_event::subject",
Level::DEBUG,
field = value,
);
use iroh::{
Endpoint,
endpoint::{Connection, presets},
protocol::{AcceptError, ProtocolHandler, Router},
};
/// Each protocol is identified by its ALPN, exchanged during the handshake.
const ALPN: &[u8] = b"iroh-example/echo/0";
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// The accepting side: bind an endpoint and route the ALPN to a handler.
let endpoint = Endpoint::bind(presets::N0).await?;
let router = Router::builder(endpoint.clone()).accept(ALPN, Echo).spawn();
endpoint.online().await;
// Get the endpoint's address so that we can connect to it.
let addr = endpoint.addr();
// The connecting side: dial the accepting endpoint by its address.
{
let other_endpoint = Endpoint::bind(presets::N0).await?;
let conn = other_endpoint.connect(addr, ALPN).await?;
let (mut send, mut recv) = conn.open_bi().await?;
send.write_all(b"Hello, world!").await?;
send.finish()?;
let response = recv.read_to_end(1000).await?;
assert_eq!(&response, b"Hello, world!");
conn.close(0u32.into(), b"bye!");
other_endpoint.close().await;
}
router.shutdown().await?;
Ok(())
}
#[derive(Debug, Clone)]
struct Echo;
impl ProtocolHandler for Echo {
async fn accept(&self, connection: Connection) -> Result<(), AcceptError> {
let (mut send, mut recv) = connection.accept_bi().await?;
// Echo bytes back until the sender signals the end of data.
tokio::io::copy(&mut recv, &mut send).await?;
send.finish()?;
// Wait until the other endpoint closes the connection.
connection.closed().await;
Ok(())
}
}
```
## Building documentation
More examples live in [`iroh/examples`](examples). Run them with
`cargo run --example NAME`. Details for each are in the file itself.
Building the documentation is only supported when using
`--all-features`.
## Compose protocols
Additionally you might want to enable documenting the cargo features
required for certain APIs, which is done by also passing the `--cfg
iroh_docsrs` flag to rustdoc when building the documentation. This
also requires using nightly rust, e.g.:
Instead of writing your own, you can build on protocols that already exist on
top of iroh:
```sh
RUSTDOCFLAGS="--cfg iroh_docsrs" cargo +nightly doc --workspace --no-deps --all-features
```
- [iroh-blobs] for [BLAKE3]-based content-addressed blob transfer, scaling from
kilobytes to terabytes.
- [iroh-gossip] for publish-subscribe overlay networks that scale down to what
an average phone can handle.
- and many more.
To use iroh from other languages, see [iroh-ffi].
## Development
For notes on iroh's structured events and how to build the documentation, see
[DEVELOPMENT.md](DEVELOPMENT.md).
# License
@@ -100,6 +162,22 @@ at your option.
### Contribution
See [CONTRIBUTING.md](https://github.com/n0-computer/iroh/blob/main/CONTRIBUTING.md)
for how to get involved.
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in this project by you, as defined in the Apache-2.0 license,
shall be dual licensed as above, without any additional terms or conditions.
[QUIC]: https://en.wikipedia.org/wiki/QUIC
[hole-punch]: https://en.wikipedia.org/wiki/Hole_punching_(networking)
[BLAKE3]: https://github.com/BLAKE3-team/BLAKE3
[`Endpoint`]: https://docs.rs/iroh/latest/iroh/struct.Endpoint.html
[`SecretKey`]: https://docs.rs/iroh/latest/iroh/struct.SecretKey.html
[`EndpointId`]: https://docs.rs/iroh/latest/iroh/struct.EndpointId.html
[address lookup services]: https://docs.rs/iroh/latest/iroh/address_lookup/index.html
[`N0` preset]: https://docs.rs/iroh/latest/iroh/endpoint/presets/struct.N0.html
[iroh-blobs]: https://github.com/n0-computer/iroh-blobs
[iroh-gossip]: https://github.com/n0-computer/iroh-gossip
[iroh-ffi]: https://github.com/n0-computer/iroh-ffi
[n0]: https://n0.computer
+5 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "iroh-bench"
version = "1.0.0-rc.1"
version = "1.0.0"
edition = "2024"
license = "MIT OR Apache-2.0"
publish = false
@@ -8,12 +8,11 @@ publish = false
[dependencies]
bytes = "1.11"
hdrhistogram = { version = "7.2", default-features = false }
iroh = { version = "1.0.0-rc.1", path = "..", default-features = false }
iroh-metrics = { version = "=1.0.0-rc.0", optional = true }
iroh = { version = "1.0.0", path = "..", default-features = false }
iroh-metrics = { version = "1.0.1", optional = true }
n0-future = "0.3"
n0-error = "=1.0.0-rc.0"
noq = "=1.0.0-rc.1"
rand = "0.10"
n0-error = "1.0.0"
noq = "1.0.0"
rcgen = "0.14"
rustls = { version = "0.23.33", default-features = false }
clap = { version = "4", features = ["derive"] }
+1 -1
View File
@@ -5,7 +5,7 @@
//!
//! ## Running the Example
//!
//! cargo run --example echo-no-router --features=examples
//! cargo run --example echo-no-router
use iroh::{Endpoint, EndpointAddr, endpoint::presets};
use n0_error::{AnyError as Error, Result, StdResultExt};
+1 -1
View File
@@ -4,7 +4,7 @@
//!
//! ## Usage
//!
//! cargo run --example echo --features=examples
//! cargo run --example echo
use iroh::{
Endpoint, EndpointAddr,
+1 -1
View File
@@ -6,7 +6,7 @@
//!
//! ## Usage
//!
//! cargo run --example screening-connection --features=examples
//! cargo run --example screening-connection
use std::sync::{
Arc,
atomic::{AtomicU64, Ordering},
+2 -2
View File
@@ -11,13 +11,13 @@
//!
//! In one terminal, run
//!
//! cargo run --example search --features=examples -- listen "hello-world" "foo-bar" "hello-moon"
//! cargo run --example search -- listen "hello-world" "foo-bar" "hello-moon"
//!
//! This spawns an iroh endpoint with three blobs. It will print the endpoint's endpoint id.
//!
//! In another terminal, run
//!
//! cargo run --example search --features=examples -- query <endpoint-id> hello
//! cargo run --example search -- query <endpoint-id> hello
//!
//! Replace <endpoint-id> with the endpoint id from above. This will connect to the listening endpoint with our
//! protocol and query for the string `hello`. The listening endpoint will return a number of how many
+11 -11
View File
@@ -3,10 +3,10 @@
//! To connect to an iroh endpoint a [`EndpointAddr`] is needed, which may contain a
//! [`RelayUrl`] or one or more *direct addresses* in addition to the [`EndpointId`].
//!
//! Since there is a conversion from [`EndpointId`] to [`EndpointAddr`], you can also use
//! Since there is a conversion from [`EndpointId`] to [`EndpointAddr`], you can also
//! connect directly with a [`EndpointId`].
//!
//! For this to work however, the endpoint has to get the addressing information by
//! For this to work however, the endpoint has to get the addressing information by
//! other means.
//!
//! [`AddressLookup`] is an automated system for an [`Endpoint`] to retrieve this addressing
@@ -50,9 +50,9 @@
//! [`iroh-mdns-address-lookup`]: https://docs.rs/iroh-mdns-address-lookup
//! [`iroh-mainline-address-lookup`]: https://docs.rs/iroh-mainline-address-lookup
//!
//! To use multiple Address Lookup'ssimultaneously you can call [`Builder::address_lookup`].
//! To use multiple Address Lookups simultaneously you can call [`Builder::address_lookup`].
//! This will use [`AddressLookupServices`] under the hood, which performs lookups to all
//! Address Lookupsystems at the same time.
//! Address Lookup systems at the same time.
//!
//! [`Builder::address_lookup`] takes any type that implements [`AddressLookupBuilder`]. You can
//! implement that trait on a builder struct if your Address Lookup needs information
@@ -60,8 +60,8 @@
//! is built by calling [`AddressLookupBuilder::into_address_lookup`], passing the finished [`Endpoint`] to your
//! builder.
//!
//! If your Address Lookupdoes not need any information from its endpoint, you can
//! pass the Address Lookupservice directly to [`Builder::address_lookup`]: All types that
//! If your Address Lookup does not need any information from its endpoint, you can
//! pass the Address Lookup service directly to [`Builder::address_lookup`]: All types that
//! implement [`AddressLookup`] also have a blanket implementation of [`AddressLookupBuilder`].
//!
//! # Examples
@@ -334,7 +334,7 @@ pub trait AddressLookup: std::fmt::Debug + Send + Sync + 'static {
/// Publishes the given [`EndpointData`] to the Address Lookup mechanism.
///
/// This is fire and forget, since the [`Endpoint`] can not wait for successful
/// publishing. If publishing is async, the implementation should start it's own task.
/// publishing. If publishing is async, the implementation should start its own task.
///
/// This will be called from a tokio task, so it is safe to spawn new tasks.
/// These tasks will be run on the runtime of the [`super::Endpoint`].
@@ -369,7 +369,7 @@ impl<T: AddressLookup> AddressLookup for Arc<T> {
/// directly from [`Item`].
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Item {
/// The endpoint info for the endpoint, as discovered by the the Address Lookup.
/// The endpoint info for the endpoint, as discovered by the Address Lookup.
endpoint_info: EndpointInfo,
/// A static string to identify the Address Lookup source.
///
@@ -421,12 +421,12 @@ impl Item {
self.last_updated
}
/// Converts into a [`EndpointAddr`] by cloning the needed fields.
/// Returns an [`EndpointAddr`] by cloning the needed fields.
pub fn to_endpoint_addr(&self) -> EndpointAddr {
self.endpoint_info.to_endpoint_addr()
}
/// Converts into a [`EndpointAddr`] without cloning.
/// Converts into an [`EndpointAddr`] without cloning.
pub fn into_endpoint_addr(self) -> EndpointAddr {
self.endpoint_info.into_endpoint_addr()
}
@@ -457,7 +457,7 @@ impl From<Item> for EndpointInfo {
///
/// See [`AddressLookup`] and [`Self::resolve`] for details.
///
/// [`Endpoint]: crate::Endpoint
/// [`Endpoint`]: crate::Endpoint
#[derive(Debug, Default, Clone)]
pub struct AddressLookupServices {
services: Arc<RwLock<Vec<Box<dyn AddressLookup>>>>,
+4 -6
View File
@@ -82,15 +82,13 @@ impl DnsAddressLookup {
}
}
/// Creates a new DNS discovery using the `iroh.link` domain.
/// Creates a new DNS address lookup using the `iroh.link` domain.
///
/// This uses the [`N0_DNS_ENDPOINT_ORIGIN_PROD`] domain.
///
/// # Usage during tests
///
/// For testing it is possible to use the [`N0_DNS_ENDPOINT_ORIGIN_STAGING`] domain
/// with [`DnsAddressLookup::builder`]. This would then use a hosted staging discovery
/// service for testing purposes.
/// When running with the environment variable `IROH_FORCE_STAGING_RELAYS`
/// set to any non empty value the [`N0_DNS_ENDPOINT_ORIGIN_STAGING`] domain
/// is used instead.
pub fn n0_dns() -> DnsAddressLookupBuilder {
if force_staging_infra() {
Self::builder(N0_DNS_ENDPOINT_ORIGIN_STAGING.to_string())
+4 -3
View File
@@ -3,7 +3,7 @@
//! Often an application might get endpoint addressing information out-of-band in an
//! application-specific way. [`EndpointTicket`]'s are one common way used to achieve this.
//! This addressing information is often only usable for a limited time so needs to
//! be able to be removed again once know it is no longer useful.
//! be able to be removed again once you know it is no longer useful.
//!
//! This is where the [`MemoryLookup`] is useful: it allows applications to add and
//! retract endpoint addressing information that is otherwise out-of-band to iroh.
@@ -29,10 +29,11 @@ use super::{AddressLookup, EndpointData, EndpointInfo, Error, Item};
/// Often an application might get endpoint addressing information out-of-band in an
/// application-specific way. [`EndpointTicket`]'s are one common way used to achieve this.
/// This addressing information is often only usable for a limited time so needs to
/// be able to be removed again once know it is no longer useful.
/// be able to be removed again once you know it is no longer useful.
///
/// This is where the [`MemoryLookup`] is useful: it allows applications to add and
/// retract endpoint addressing information that is otherwise out-of-band to iroh.
///
/// # Examples
///
/// ```no_run
@@ -100,7 +101,7 @@ impl MemoryLookup {
/// [`Endpoint`]: crate::Endpoint
pub const PROVENANCE: &'static str = "memory_lookup";
/// Creates a new static Address Lookup instance.
/// Creates a new empty Memory Lookup instance.
pub fn new() -> Self {
Self::default()
}
+4 -2
View File
@@ -259,7 +259,9 @@ impl AddressLookupBuilder for PkarrPublisherBuilder {
/// that it only publishes address lookup information, for the corresponding resolver use
/// the [`PkarrResolver`] together with [`AddressLookupServices`].
///
/// This publisher will **only** publish the [`RelayUrl`] if it is set, otherwise the *direct addresses* are published instead.
/// By default this publisher only publishes the [`RelayUrl`], to avoid leaking IP addresses to
/// the public pkarr server. Which addresses are published is controlled by the [`AddrFilter`]
/// set via [`PkarrPublisherBuilder::addr_filter`].
///
/// [pkarr]: https://pkarr.org
/// [module docs]: crate::address_lookup::pkarr
@@ -276,7 +278,7 @@ pub struct PkarrPublisher {
impl PkarrPublisher {
/// Returns a [`PkarrPublisherBuilder`] that publishes endpoint info to a [pkarr] relay at `pkarr_relay`.
///
/// If no further options are set, the pkarr publisher will use [`DEFAULT_PKARR_TTL`] as the
/// If no further options are set, the pkarr publisher will use [`DEFAULT_PKARR_TTL`] as the
/// time-to-live value for the published packets, and it will republish Address Lookup information
/// every [`DEFAULT_REPUBLISH_INTERVAL`], even if the information is unchanged.
///
+7 -7
View File
@@ -24,13 +24,13 @@ pub mod prod {
use crate::RelayUrl;
/// Hostname of the default NA east relay.
pub const NA_EAST_RELAY_HOSTNAME: &str = "use1-1.relay.n0.iroh-canary.iroh.link.";
pub const NA_EAST_RELAY_HOSTNAME: &str = "use1-1.relay.n0.iroh.link.";
/// Hostname of the default NA west relay.
pub const NA_WEST_RELAY_HOSTNAME: &str = "usw1-1.relay.n0.iroh-canary.iroh.link.";
pub const NA_WEST_RELAY_HOSTNAME: &str = "usw1-1.relay.n0.iroh.link.";
/// Hostname of the default EU relay.
pub const EU_RELAY_HOSTNAME: &str = "euc1-1.relay.n0.iroh-canary.iroh.link.";
pub const EU_RELAY_HOSTNAME: &str = "euc1-1.relay.n0.iroh.link.";
/// Hostname of the default Asia-Pacific relay.
pub const AP_RELAY_HOSTNAME: &str = "aps1-1.relay.n0.iroh-canary.iroh.link.";
pub const AP_RELAY_HOSTNAME: &str = "aps1-1.relay.n0.iroh.link.";
/// Get the default [`RelayMap`].
pub fn default_relay_map() -> RelayMap {
@@ -69,7 +69,7 @@ pub mod prod {
RelayConfig::from(RelayUrl::from(url))
}
/// Get the default [`RelayConfig`] for Asia-Pacific
/// Get the default [`RelayConfig`] for Asia-Pacific.
pub fn default_ap_relay() -> RelayConfig {
// The default Asia-Pacific relay server run by number0.
let url: Url = format!("https://{AP_RELAY_HOSTNAME}")
@@ -91,9 +91,9 @@ pub mod staging {
use crate::RelayUrl;
/// Hostname of the default NA relay.
pub const NA_EAST_RELAY_HOSTNAME: &str = "staging-use1-1.relay.iroh.network.";
pub const NA_EAST_RELAY_HOSTNAME: &str = "use1-1.staging-relay.n0.iroh.link.";
/// Hostname of the default EU relay.
pub const EU_RELAY_HOSTNAME: &str = "staging-euw1-1.relay.iroh.network.";
pub const EU_RELAY_HOSTNAME: &str = "euc1-1.staging-relay.n0.iroh.link.";
/// Get the default [`RelayMap`].
pub fn default_relay_map() -> RelayMap {
+82 -48
View File
@@ -26,13 +26,22 @@ use tokio_util::sync::WaitForCancellationFutureOwned;
use tracing::{Instrument, Span, debug, event, info_span, instrument, warn};
use url::Url;
/// Types for defining custom transports
#[cfg(feature = "unstable-custom-transports")]
pub mod transports {
//! Types for defining custom transports and path selectors.
//!
//! <div class="warning">
//!
//! These items are unstable and gated behind the `unstable-custom-transport` feature.
//! They are not covered by semantic versioning guarantees and may change in any release
//! without a major version bump.
//!
//! </div>
pub use super::socket::{
remote_map::{PathSelection, PathSelectionContext, PathSelectionData, PathSelector},
transports::{
Addr, AddrKind, RecvInfo, Transmit,
Addr, AddrKind, FourTuple, RecvInfo, Transmit,
custom::{CustomEndpoint, CustomSender, CustomTransport},
},
};
@@ -53,9 +62,10 @@ use crate::address_lookup::PkarrResolver;
use crate::dns::DnsResolver;
#[cfg(feature = "unstable-custom-transports")]
use crate::endpoint::transports::CustomTransport;
#[cfg(feature = "unstable-net-report")]
use crate::net_report::Report as NetReport;
pub use crate::tls::TlsConfigError;
use crate::{
NetReport,
address_lookup::{
AddrFilter, AddressLookupBuilder, AddressLookupFailed, AddressLookupServices,
DynAddressLookupBuilder, UserData,
@@ -400,7 +410,7 @@ impl Builder {
/// socket should be bound or the routing will be non-deterministic.
///
/// To use a subnet with a non-zero prefix length as the default route in addition to
/// being routed when its prefix matches, use [`BindOpts::set_is_default_route].
/// being routed when its prefix matches, use [`BindOpts::set_is_default_route`].
/// Subnets with a prefix length of zero are always marked as default routes.
///
/// Finally note that most outgoing datagrams are part of an existing network flow. That
@@ -601,7 +611,7 @@ impl Builder {
///
/// This filter is applied once, at the [`AddressLookupServices`] level, before
/// distributing data to any individual address lookup service. This ensures
/// consistent filtering regardless of how the services configured.
/// consistent filtering regardless of how the services are configured.
///
/// [`AddressLookupServices`]: crate::address_lookup::AddressLookupServices
pub fn addr_filter(mut self, filter: AddrFilter) -> Self {
@@ -788,7 +798,15 @@ impl Builder {
self
}
/// Adds a custom transport
/// Adds a custom transport to the endpoint.
///
/// <div class="warning">
///
/// This API is unstable and gated behind the `unstable-custom-transport` feature.
/// It is not covered by semantic versioning guarantees and may change in any release
/// without a major version bump.
///
/// </div>
#[cfg(feature = "unstable-custom-transports")]
pub fn add_custom_transport(mut self, factory: Arc<dyn CustomTransport>) -> Self {
self.transports.push(TransportConfig::Custom(factory));
@@ -807,6 +825,14 @@ impl Builder {
/// across multiple endpoints if desired. See `examples/custom-transport.rs` for
/// an example implementation.
///
/// <div class="warning">
///
/// This API is unstable and gated behind the `unstable-custom-transport` feature.
/// It is not covered by semantic versioning guarantees and may change in any release
/// without a major version bump.
///
/// </div>
///
/// [`PathSelector`]: socket::remote_map::PathSelector
#[cfg(feature = "unstable-custom-transports")]
pub fn path_selector(mut self, selector: Arc<dyn PathSelector>) -> Self {
@@ -842,7 +868,7 @@ pub enum EndpointError {
/// [`Endpoint::connect`] and [`Endpoint::accept`] methods. Once established, the
/// [`Connection`] gives access to most [QUIC] features. Individual streams to send data to
/// the peer are created using the [`Connection::open_bi`], [`Connection::accept_bi`],
/// [`Connection::open_uni`] and [`Connection::open_bi`] functions.
/// [`Connection::open_uni`] and [`Connection::accept_uni`] functions.
///
/// Note that due to the light-weight properties of streams a stream will only be accepted
/// once the initiating peer has sent some data on it.
@@ -1186,8 +1212,8 @@ impl Endpoint {
/// understand if the endpoint has ever been considered "online". But after
/// that initial call to [`Endpoint::online`], to understand if your
/// endpoint is no longer able to be connected to by endpoints outside
/// of the private or local network, watch for changes in it's [`EndpointAddr`].
/// If there are no `addrs`in the [`EndpointAddr`], you may not be dialable by other endpoints
/// of the private or local network, watch for changes in its [`EndpointAddr`].
/// If there are no `addrs` in the [`EndpointAddr`], you may not be dialable by other endpoints
/// on the internet.
///
/// The `EndpointAddr` will change as:
@@ -1280,7 +1306,7 @@ impl Endpoint {
/// This has no timeout, so if that is needed, you need to wrap it in a
/// timeout. We recommend using a timeout close to
/// [`crate::NET_REPORT_TIMEOUT`]s, so you can be sure that at least one
/// [`crate::NetReport`] has been attempted.
/// net report has been attempted.
///
/// To understand if the endpoint has gone back "offline",
/// you must use the [`Endpoint::watch_addr`] method, to
@@ -1299,20 +1325,22 @@ impl Endpoint {
///
/// # Examples
///
/// ```no run
/// use iroh::Endpoint;
///
/// #[tokio::main]
/// async fn main() {
/// ```no_run
/// # #[cfg(with_crypto_provider)]
/// # {
/// # #[tokio::main]
/// # async fn main() -> n0_error::Result<()> {
/// # use iroh::{Endpoint, endpoint::presets};
/// // After this await returns, the endpoint is bound to a local socket.
/// // It can be dialed, but almost certainly hasn't finished picking a
/// // relay.
/// let endpoint = Endpoint::bind().await;
/// let endpoint = Endpoint::bind(presets::N0).await?;
///
/// // After this await returns we have a connection to at least one relay
/// // and holepunching should work as expected.
/// endpoint.online().await;
/// }
/// # Ok(()) }
/// # }
/// ```
pub async fn online(&self) {
let mut watcher = self.inner.home_relay_status();
@@ -1335,7 +1363,7 @@ impl Endpoint {
///
/// The watched value has one entry per home relay whose URL is known,
/// and is empty when no relays are configured or before the endpoint has
/// selected one the home relay from the list of configured relays.
/// selected a home relay from the list of configured relays.
/// The watcher updates whenever any home relay's connection status changes.
/// See [`RelayStatus`] for the information available on each entry.
///
@@ -1347,21 +1375,29 @@ impl Endpoint {
self.inner.home_relay_status()
}
/// Returns a [`Watcher`] for any net-reports run from this [`Endpoint`].
/// Returns a [`Watcher`] for any net report runs from this [`Endpoint`].
///
/// A `net-report` checks the network conditions of the [`Endpoint`], such as
/// whether it is connected to the internet via Ipv4 and/or Ipv6, its NAT
/// <div class="warning">
///
/// This API is unstable and gated behind the `unstable-net-report` feature.
/// It is not covered by semantic versioning guarantees and may change in any release
/// without a major version bump.
///
/// </div>
///
/// A net report checks the network conditions of the [`Endpoint`], such as
/// whether it is connected to the internet via IPv4 and/or IPv6, its NAT
/// status, its latency to the relay servers, and its public addresses.
///
/// The [`Endpoint`] continuously runs `net-reports` to monitor if network
/// conditions have changed. This [`Watcher`] will return the latest result
/// of the `net-report`.
/// The [`Endpoint`] continuously runs net reports to monitor if network
/// conditions have changed. This [`Watcher`] will return the latest
/// net report.
///
/// When issuing the first call to this method the first report might
/// still be underway, in this case the [`Watcher`] might not be initialized
/// with [`Some`] value yet. Once the net-report has been successfully
/// run, the [`Watcher`] will always return [`Some`] report immediately, which
/// is the most recently run `net-report`.
/// with [`Some`] value yet. Once the net report has been successfully
/// run, the [`Watcher`] will always return [`Some`] immediately, which
/// is the most recently run net report.
///
/// The returned watcher only becomes disconnected once the last clone of the [`Endpoint`]
/// is dropped. Closing the endpoint does not disconnect the watcher. Thus, a stream created
@@ -1383,21 +1419,11 @@ impl Endpoint {
/// # });
/// # }
/// ```
#[doc(hidden)]
#[cfg(feature = "unstable-net-report")]
pub fn net_report(&self) -> impl Watcher<Value = Option<NetReport>> + use<> {
self.inner.net_report()
}
/// Returns the last [`NetReport`] generated by this endpoint.
///
/// Returns `None` if no net report was ever generated.
///
/// This method is hidden in the docs because it is not part of the public api
#[doc(hidden)]
pub fn last_net_report(&self) -> Option<NetReport> {
self.inner.net_report().get()
}
/// Returns the local socket addresses on which the underlying sockets are bound.
///
/// The [`Endpoint`] always binds on an IPv4 address and also tries to bind on an IPv6
@@ -1663,7 +1689,7 @@ impl Endpoint {
/// kernel during the "Time-Wait" period of the TCP socket.
///
/// Be aware however that the underlying UDP sockets are only closed once all clones of
/// the the respective [`Endpoint`] are dropped.
/// the respective [`Endpoint`] are dropped.
pub async fn close(&self) {
self.inner.close().await;
}
@@ -1916,8 +1942,8 @@ impl RelayMode {
/// # fn main() -> n0_error::Result<()> {
/// # use iroh::RelayMode;
/// RelayMode::custom([
/// "https://use1-1.relay.n0.iroh-canary.iroh.link.".parse()?,
/// "https://euw-1.relay.n0.iroh-canary.iroh.link.".parse()?,
/// "https://use1-1.relay.n0.iroh.link.".parse()?,
/// "https://euw-1.relay.n0.iroh.link.".parse()?,
/// ]);
/// # Ok(()) }
/// ```
@@ -3151,6 +3177,7 @@ mod tests {
#[tokio::test]
#[traced_test]
#[cfg(feature = "unstable-net-report")]
async fn watch_net_report() -> Result {
let endpoint = Endpoint::builder(presets::Minimal)
.relay_mode(RelayMode::Staging)
@@ -3237,14 +3264,14 @@ mod tests {
async fn test_custom_relay() -> Result {
let _ep = Endpoint::builder(presets::Minimal)
.relay_mode(RelayMode::custom([RelayUrl::from_str(
"https://use1-1.relay.n0.iroh-canary.iroh.link.",
"https://use1-1.relay.n0.iroh.link.",
)?]))
.bind()
.await?;
let relays = RelayMap::try_from_iter([
"https://use1-1.relay.n0.iroh.iroh.link/",
"https://euc1-1.relay.n0.iroh.iroh.link/",
"https://use1-1.relay.n0.iroh.link/",
"https://euc1-1.relay.n0.iroh.link/",
])?;
let _ep = Endpoint::builder(presets::Minimal)
.relay_mode(RelayMode::Custom(relays))
@@ -3783,11 +3810,16 @@ mod tests {
// create watchers to verify they terminate after the endpoint is dropped.
let mut addrs = ep.watch_addr().stream();
let mut net_reports = ep.net_report().stream();
// returns None
let net_report = ep.last_net_report();
info!("last Net report {net_report:?}");
#[cfg(feature = "unstable-net-report")]
let mut net_reports = {
let net_reports = ep.net_report().stream();
// returns None
let net_report = ep.net_report().get();
info!("last Net report {net_report:?}");
net_reports
};
// this should work
let sockets = ep.bound_sockets();
@@ -3820,6 +3852,8 @@ mod tests {
while let Some(addr) = addrs.next().await {
info!("Addrs stream: {addr:?}");
}
#[cfg(feature = "unstable-net-report")]
while let Some(net_report) = net_reports.next().await {
info!("Net report stream: {net_report:?}");
}
+1 -1
View File
@@ -111,7 +111,7 @@ impl BindOpts {
/// Returns whether this is a default route.
///
/// If [`Self::set_is_default_route`] has been called then that value is returned.
/// Otherwise, returns `true` if the [`prefix_len`][`Self::prefix_len] is `0` and
/// Otherwise, returns `true` if the [`prefix_len`][`Self::prefix_len`] is `0` and
/// `false` otherwise.
pub fn is_default_route(&self) -> bool {
match self.is_default_route {
+7 -5
View File
@@ -214,7 +214,7 @@ impl Incoming {
self.inner.remote_address_validated()
}
/// Decrypt the Initial packet payload
/// Decrypts the Initial packet payload.
///
/// This clones and decrypts the packet payload (~1200 bytes).
/// Can be used to extract information from the TLS ClientHello without completing the handshake.
@@ -840,7 +840,7 @@ impl<T: ConnectionState> Connection<T> {
self.inner.accept_uni()
}
/// Accept the next incoming bidirectional stream.
/// Accepts the next incoming bidirectional stream.
///
/// **Important Note**: The peer that calls [`open_bi`] must write to its [`SendStream`]
/// before the peer `Connection` is able to accept the stream using
@@ -861,7 +861,7 @@ impl<T: ConnectionState> Connection<T> {
self.inner.read_datagram()
}
/// Wait for the connection to be closed for any reason.
/// Waits for the connection to be closed for any reason.
///
/// Despite the return type's name, closed connections are often not an error condition
/// at the application layer. Cases that might be routine include
@@ -1043,6 +1043,8 @@ impl<T: ConnectionState> Connection<T> {
self.inner.set_max_concurrent_uni_streams(count)
}
/// Sets the connection-level flow control receive window.
///
/// See [`noq_proto::TransportConfig::receive_window`].
#[inline]
pub fn set_receive_window(&self, receive_window: VarInt) {
@@ -1188,10 +1190,10 @@ impl Connection<OutgoingZeroRtt> {
/// Waits until the full handshake occurs and returns a [`ZeroRttStatus`].
///
/// If `ZeroRttStatus::Accepted` is returned, than any streams created before
/// If `ZeroRttStatus::Accepted` is returned, then any streams created before
/// the handshake has completed can still be used.
///
/// If `ZeroRttStatus::Rejected` is returned, than any streams created before
/// If `ZeroRttStatus::Rejected` is returned, then any streams created before
/// the handshake will error and any data sent should be re-sent on a
/// new stream.
///
+1 -1
View File
@@ -55,7 +55,7 @@ impl AfterHandshakeOutcome {
/// For each hook, all installed hooks are invoked in the order they were installed on
/// the endpoint builder. If a hook returns `Accept`, processing continues with the next
/// hook. If a hook returns `Reject`, processing is aborted and further hooks
/// are not invoked for this hook.
/// are not invoked for this hook point.
///
/// ## Notes to implementers
///
+5 -5
View File
@@ -17,7 +17,7 @@
use crate::endpoint::Builder;
/// Defines a preset
/// A reusable bundle of endpoint [`Builder`] configuration.
pub trait Preset {
/// Applies the configuration to the passed in [`Builder`].
fn apply(self, builder: Builder) -> Builder;
@@ -86,8 +86,8 @@ impl Preset for Minimal {
/// - setting the [`rustls::crypto::CryptoProvider`] to [ring] or [aws-lc-rs], depending
/// on which feature is enabled in iroh (preferring ring if both are enabled).
///
/// Due to the last point, this preset is only available with the `ring` or
/// `aws-lc-rs` preset installed.
/// Due to the last point, this preset is only available with the `tls-ring` or
/// `tls-aws-lc-rs` feature enabled.
/// If you want to set your own crypto provider, we recommend copying the
/// implementation of this preset into your own and setting the appropriate crypto
/// provider there.
@@ -148,8 +148,8 @@ impl Preset for N0 {
/// - setting the [`rustls::crypto::CryptoProvider`] to [ring] or [aws-lc-rs], depending
/// on which feature is enabled in iroh (preferring ring if both are enabled).
///
/// Due to the last point, this preset is only available with the `ring` or
/// `aws-lc-rs` preset installed.
/// Due to the last point, this preset is only available with the `tls-ring` or
/// `tls-aws-lc-rs` feature enabled.
/// If you want to set your own crypto provider, we recommend copying the
/// implementation of this preset into your own and setting the appropriate crypto
/// provider there.
+1 -1
View File
@@ -487,7 +487,7 @@ impl QuicTransportConfigBuilder {
/// interact with the [`QuicTransportConfigBuilder::max_idle_timeout`], if the last path is
/// abandoned the entire connection will be closed.
///
/// Note: values higher than [`PATH_MAX_IDLE_TIMEOUT`] are clamped and a warning is logged.
/// Note: values higher than `PATH_MAX_IDLE_TIMEOUT` (15 seconds) are clamped and a warning is logged.
pub fn default_path_max_idle_timeout(mut self, timeout: Duration) -> Self {
if timeout > PATH_MAX_IDLE_TIMEOUT {
warn!(
+12 -3
View File
@@ -1,6 +1,6 @@
//! Peer-to-peer QUIC connections.
//!
//! iroh is a library to establish direct connectivity between peers. It exposes an
//! iroh is a library to establish direct connectivity between peers. It exposes an
//! interface to [QUIC] connections and streams to the user, while implementing direct
//! connectivity using [hole punching] complemented by relay servers under the hood.
//!
@@ -73,7 +73,7 @@
//!
//! If one of the iroh endpoints can be reached directly, connectivity can also be
//! established without involving a Relay server. This is done by using the endpoint's
//! listening addresses in the connection establishement instead of the [`RelayUrl`] which
//! listening addresses in the connection establishment instead of the [`RelayUrl`] which
//! is used to identify a Relay server. Of course it is also possible to use both a
//! [`RelayUrl`] and direct addresses at the same time to connect.
//!
@@ -289,7 +289,16 @@ pub use iroh_dns::dns;
pub use iroh_dns::endpoint_info;
pub use iroh_relay::{RelayConfig, RelayMap};
pub use n0_watcher::Watcher;
pub use net_report::{NetReportConfig, Report as NetReport, TIMEOUT as NET_REPORT_TIMEOUT};
pub use net_report::{NetReportConfig, TIMEOUT as NET_REPORT_TIMEOUT};
#[cfg(feature = "unstable-net-report")]
pub mod unstable_net_report {
//! Exports of net report types reachable via [`crate::endpoint::Endpoint::net_report`].
/// This API is unstable and gated behind the `unstable-net-report` feature.
/// It is not covered by semantic versioning guarantees and may change in any release
/// without a major version bump.
pub use crate::net_report::{Probe, RelayLatencies, Report as NetReport};
}
#[cfg(any(test, feature = "test-utils"))]
pub mod test_utils;
+16 -20
View File
@@ -5,9 +5,6 @@
//! etc and reachability to the configured relays.
// Based on <https://github.com/tailscale/tailscale/blob/main/net/netcheck/netcheck.go>
#![cfg_attr(iroh_docsrs, feature(doc_cfg))]
#![deny(missing_docs, rustdoc::broken_intra_doc_links)]
#![cfg_attr(not(test), deny(clippy::unwrap_used))]
#![cfg_attr(wasm_browser, allow(unused))]
use std::{
@@ -18,15 +15,11 @@ use std::{
};
use defaults::timeouts::PROBES_TIMEOUT;
// exported primarily for use in documentation
pub use defaults::timeouts::TIMEOUT;
use iroh_base::RelayUrl;
#[cfg(not(wasm_browser))]
use iroh_dns::dns::DnsResolver;
#[cfg(not(wasm_browser))]
use iroh_relay::RelayConfig;
#[cfg(not(wasm_browser))]
use iroh_relay::quic::QuicClient;
use iroh_relay::{RelayConfig, quic::QuicClient};
use iroh_relay::{
RelayMap,
quic::{QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON},
@@ -46,19 +39,29 @@ use tokio::task::JoinSet;
use tokio_util::sync::CancellationToken;
use tracing::{debug, trace, warn};
#[cfg(not(wasm_browser))]
use self::reportgen::QadProbeReport;
use self::reportgen::{ProbeFinished, ProbeReport};
#[cfg(not(wasm_browser))]
use self::reportgen::{QadProbeReport, SocketState};
#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
pub use self::{
// exported primarily for use in documentation
defaults::timeouts::TIMEOUT,
metrics::Metrics,
probes::Probe,
report::{RelayLatencies, Report},
};
pub(crate) use self::{
options::Options,
reportgen::{IfStateDetails, QuicConfig},
};
mod defaults;
mod metrics;
mod options;
mod probes;
mod report;
mod reportgen;
mod options;
pub(crate) use self::reportgen::IfStateDetails;
#[cfg(not(wasm_browser))]
#[allow(missing_docs)]
#[stack_error(derive, add_meta)]
@@ -76,13 +79,6 @@ enum QadProbeError {
ReceiverDropped,
}
#[cfg(not(wasm_browser))]
use self::reportgen::SocketState;
pub use self::{metrics::Metrics, report::Report};
pub(crate) use self::{
options::Options, probes::Probe, report::RelayLatencies, reportgen::QuicConfig,
};
/// Configuration for the net report component.
///
/// Controls which probes and checks are performed when generating network reports.
+2
View File
@@ -20,6 +20,8 @@ const HTTPS_OFFSET: Duration = Duration::from_millis(200);
/// The protocol used to time an endpoint's latency.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, derive_more::Display)]
#[repr(u8)]
#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
#[non_exhaustive]
pub enum Probe {
/// HTTPS
Https,
+11 -5
View File
@@ -13,6 +13,8 @@ use super::{ProbeReport, probes::Probe};
/// A net_report report.
#[derive(Default, Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
#[non_exhaustive]
pub struct Report {
/// A QAD IPv4 round trip completed.
pub udp_v4: bool,
@@ -22,14 +24,13 @@ pub struct Report {
pub mapping_varies_by_dest_ipv4: Option<bool>,
/// Whether the reported public address differs when probing different servers (on IPv6).
pub mapping_varies_by_dest_ipv6: Option<bool>,
/// Probe indicating the presence of port mapping protocols on the LAN.
/// `None` for unknown
/// The relay server with the lowest latency, if any.
pub preferred_relay: Option<RelayUrl>,
/// keyed by relay Url
/// The measured latency to each relay, keyed by relay URL.
pub relay_latency: RelayLatencies,
/// ip:port of global IPv4
/// The discovered global IPv4 address and port, if any.
pub global_v4: Option<SocketAddrV4>,
/// `[ip]:port` of global IPv6
/// The discovered global IPv6 address and port, if any.
pub global_v6: Option<SocketAddrV6>,
/// CaptivePortal is set when we think there's a captive portal that is
/// intercepting HTTP traffic.
@@ -44,11 +45,13 @@ impl fmt::Display for Report {
impl Report {
/// Do we have any indication that UDP is working?
#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
pub fn has_udp(&self) -> bool {
self.udp_v4 || self.udp_v6
}
/// Whether the reported public address differs when probing different servers.
#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
pub fn mapping_varies_by_dest(&self) -> Option<bool> {
match (
self.mapping_varies_by_dest_ipv4,
@@ -129,6 +132,7 @@ impl Report {
/// Latencies per relay endpoint.
#[derive(Debug, Default, PartialEq, Eq, Clone, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
pub struct RelayLatencies {
#[cfg(not(wasm_browser))]
ipv4: BTreeMap<RelayUrl, Duration>,
@@ -172,6 +176,7 @@ impl RelayLatencies {
/// Returns an iterator over all the relays and their latencies.
#[cfg(not(wasm_browser))]
#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
pub fn iter(&self) -> impl Iterator<Item = (Probe, &'_ RelayUrl, Duration)> + '_ {
self.https
.iter()
@@ -182,6 +187,7 @@ impl RelayLatencies {
/// Returns an iterator over all the relays and their latencies.
#[cfg(wasm_browser)]
#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
pub fn iter(&self) -> impl Iterator<Item = (Probe, &'_ RelayUrl, Duration)> + '_ {
self.https.iter().map(|(k, v)| (Probe::Https, k, *v))
}
+3 -3
View File
@@ -174,7 +174,7 @@ pub enum IncomingFilterOutcome {
///
/// What this does depends on the connection type:
///
/// - **Direct (UDP) connections** : this is QUIC source address
/// - **Direct (UDP) connections**: this is QUIC source address
/// validation. If the socket address was spoofed, the retry token is
/// sent to the spoofed address, so we never hear from the attacker
/// again. If the address was real, the client repeats the connection
@@ -182,7 +182,7 @@ pub enum IncomingFilterOutcome {
/// [`Incoming::remote_addr_validated`] set to `true`. The token is
/// bound to the source address.
///
/// - **Relay connections** : there is no source address to validate
/// - **Relay connections**: there is no source address to validate
/// (the relay already vouches for the packet origin), so the
/// "validation" itself has no security meaning. However, the retry
/// still imposes a real cost on the client: an extra round trip
@@ -491,7 +491,7 @@ impl RouterBuilder {
self
}
/// Returns the [`Endpoint`] of the endpoint.
/// Returns the [`Endpoint`] stored in this builder.
pub fn endpoint(&self) -> &Endpoint {
&self.endpoint
}
+2 -1
View File
@@ -476,6 +476,7 @@ impl Socket {
///
/// [`Watcher`]: n0_watcher::Watcher
/// [`Watcher::initialized`]: n0_watcher::Watcher::initialized
#[cfg(feature = "unstable-net-report")]
pub(crate) fn net_report(&self) -> impl Watcher<Value = Option<Report>> + use<> {
self.net_report.watch().map(|(r, _)| r)
}
@@ -695,7 +696,7 @@ impl Socket {
}
}
/// Manages currently running [`crate::NetReport`] to learn this endpoint's IP addresses.
/// Manages currently running net reports to learn this endpoint's IP addresses.
///
/// Invariants:
/// - only one direct addr update must be running at a time
+24 -8
View File
@@ -1,32 +1,41 @@
use iroh_metrics::{Counter, MetricsGroup};
use serde::{Deserialize, Serialize};
/// Enum of metrics for the module
// TODO(frando): Add description doc strings for each metric.
#[allow(missing_docs)]
/// Metrics collected by the iroh socket.
#[derive(Debug, Serialize, Deserialize, MetricsGroup)]
#[non_exhaustive]
#[metrics(name = "socket", default)]
pub struct Metrics {
/// Intended to count updates to the local direct address set, but currently unused
/// (never incremented).
pub update_direct_addrs: Counter,
// Sends (data or disco)
/// Number of bytes sent over IPv4.
pub send_ipv4: Counter,
/// Number of bytes sent over IPv6.
pub send_ipv6: Counter,
/// Number of bytes sent over the relay transport.
pub send_relay: Counter,
// Data packets (non-disco)
/// Number of data bytes received over the relay transport.
pub recv_data_relay: Counter,
// Number of bytes received on any custom transport.
/// Number of data bytes received over any custom transport.
pub recv_data_custom: Counter,
/// Number of data bytes received over IPv4.
pub recv_data_ipv4: Counter,
/// Number of data bytes received over IPv6.
pub recv_data_ipv6: Counter,
/// Number of QUIC datagrams received.
pub recv_datagrams: Counter,
/// Number of datagrams received using GRO
/// Number of receive events that used GRO (coalesced datagram batches).
///
/// This counts batches, not the individual datagrams within them. See
/// [`Self::recv_datagrams`] for the datagram count.
pub recv_gro_datagrams: Counter,
// How many times our relay home endpoint DI has changed from non-zero to a different non-zero.
/// Number of times the home relay changed to a different relay.
///
/// This includes the initial assignment from no home relay to a home relay.
pub relay_home_change: Counter,
/*
@@ -79,11 +88,18 @@ pub struct Metrics {
/// Number of custom transport paths closed.
pub transport_custom_paths_removed: Counter,
/// Number of iterations of the main socket actor loop.
pub actor_tick_main: Counter,
/// Number of actor messages processed by the socket actor loop.
pub actor_tick_msg: Counter,
/// Number of periodic re-STUN timer ticks handled by the socket actor loop.
pub actor_tick_re_stun: Counter,
/// Number of port-mapping change events handled by the socket actor loop.
pub actor_tick_portmap_changed: Counter,
/// Intended to count direct address heartbeat ticks, but currently unused (never incremented).
pub actor_tick_direct_addr_heartbeat: Counter,
/// Number of local network interface (link) change events handled by the socket actor loop.
pub actor_link_change: Counter,
/// Number of times an input watcher or receiver closed in the socket actor loop.
pub actor_tick_other: Counter,
}
+4 -6
View File
@@ -807,12 +807,10 @@ impl PartialEq<TransportAddr> for Addr {
/// Identifies a network path by the combination of remote and local addresses.
///
/// Mirrors [`noq::FourTuple`] but uses transport-specific addresses.
///
/// The meaning of the local address is a bit particular:
/// * For IP transports it is the interface IP, if known.
/// * For custom transports it is a custom transport address, if the transport reports one.
/// * For relay transports there is no separate local address; the relay URL identifies the path.
/// * For custom transports it is a custom transport address, if the transport implementation reports one.
/// * For relay transports there is no separate local address.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
pub enum FourTuple {
@@ -842,7 +840,7 @@ pub enum FourTuple {
#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
impl FourTuple {
/// Creates a four-tuple from a remote address, with no known local address.
pub(super) fn from_remote(remote: Addr) -> Self {
pub fn from_remote(remote: Addr) -> Self {
match remote {
Addr::Ip(remote) => Self::Ip {
remote,
@@ -861,7 +859,7 @@ impl FourTuple {
/// The variant is determined by `remote`. The `local` address is retained only when
/// it matches that variant. A mismatched `local` is dropped, which cannot happen for
/// values derived together from the same network path.
pub(super) fn new(remote: Addr, local: LocalTransportAddr) -> Self {
pub fn new(remote: Addr, local: LocalTransportAddr) -> Self {
match remote {
Addr::Ip(remote) => Self::Ip {
remote,
+1 -1
View File
@@ -1,6 +1,6 @@
//! TLS configuration for iroh.
//!
//! Currently there is one mechanisms available
//! Currently there is one mechanism available:
//! - Raw Public Keys, using the TLS extension described in [RFC 7250]
//!
//! [RFC 7250]: https://datatracker.ietf.org/doc/html/rfc7250
+1 -1
View File
@@ -114,7 +114,7 @@ impl ServerCertVerifier for ServerCertificateVerifier {
#[derive(Default, Debug)]
pub(super) struct ClientCertificateVerifier;
/// We requires either following of X.509 client certificate chains:
/// We require one of the following client certificate configurations:
///
/// - a valid raw public key configuration
impl ClientCertVerifier for ClientCertificateVerifier {