1#![deny(unsafe_code)]
6
7pub mod client;
8pub mod endpoint;
9pub mod events;
10pub(crate) mod io;
11pub(crate) mod pool;
12pub mod registry;
13pub mod server;
14pub mod session;
15pub mod stream;
16
17pub use client::{fetch, raw_connect};
18#[cfg(feature = "compression")]
19pub use endpoint::CompressionOptions;
20pub use endpoint::{
21 parse_direct_addrs, ConnectionEvent, DiscoveryOptions, EndpointStats, IrohEndpoint,
22 NetworkingOptions, NodeAddrInfo, NodeOptions, PathInfo, PeerStats, PoolOptions,
23 StreamingOptions,
24};
25pub use events::TransportEvent;
26pub use registry::{get_endpoint, insert_endpoint, remove_endpoint};
27pub use server::respond;
28pub use server::serve;
29pub use server::serve_with_events;
30pub use server::ServeHandle;
31pub use server::ServerLimits;
32pub use session::{
33 session_accept, session_close, session_closed, session_connect, session_create_bidi_stream,
34 session_create_uni_stream, session_max_datagram_size, session_next_bidi_stream,
35 session_next_uni_stream, session_ready, session_recv_datagram, session_remote_id,
36 session_send_datagram, CloseInfo,
37};
38pub use stream::{BodyReader, HandleStore, StoreConfig};
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46#[non_exhaustive]
47pub enum ErrorCode {
48 InvalidInput,
49 ConnectionFailed,
50 Timeout,
51 BodyTooLarge,
52 HeaderTooLarge,
53 PeerRejected,
54 Cancelled,
55 Internal,
56}
57
58#[derive(Debug, Clone)]
62pub struct CoreError {
63 pub code: ErrorCode,
64 pub message: String,
65}
66
67impl CoreError {
68 pub fn invalid_input(detail: impl std::fmt::Display) -> Self {
69 CoreError {
70 code: ErrorCode::InvalidInput,
71 message: detail.to_string(),
72 }
73 }
74 pub fn connection_failed(detail: impl std::fmt::Display) -> Self {
75 CoreError {
76 code: ErrorCode::ConnectionFailed,
77 message: detail.to_string(),
78 }
79 }
80 pub fn timeout(detail: impl std::fmt::Display) -> Self {
81 CoreError {
82 code: ErrorCode::Timeout,
83 message: detail.to_string(),
84 }
85 }
86 pub fn body_too_large(detail: impl std::fmt::Display) -> Self {
87 CoreError {
88 code: ErrorCode::BodyTooLarge,
89 message: detail.to_string(),
90 }
91 }
92 pub fn header_too_large(detail: impl std::fmt::Display) -> Self {
93 CoreError {
94 code: ErrorCode::HeaderTooLarge,
95 message: detail.to_string(),
96 }
97 }
98 pub fn peer_rejected(detail: impl std::fmt::Display) -> Self {
99 CoreError {
100 code: ErrorCode::PeerRejected,
101 message: detail.to_string(),
102 }
103 }
104 pub fn internal(detail: impl std::fmt::Display) -> Self {
105 CoreError {
106 code: ErrorCode::Internal,
107 message: detail.to_string(),
108 }
109 }
110 pub fn invalid_handle(handle: u64) -> Self {
111 CoreError {
112 code: ErrorCode::InvalidInput,
113 message: format!("unknown handle: {handle}"),
114 }
115 }
116 pub fn cancelled() -> Self {
117 CoreError {
118 code: ErrorCode::Cancelled,
119 message: "aborted".to_string(),
120 }
121 }
122}
123
124impl std::fmt::Display for CoreError {
125 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126 write!(f, "{:?}: {}", self.code, self.message)
127 }
128}
129
130impl std::error::Error for CoreError {}
131
132pub const ALPN: &[u8] = b"iroh-http/2";
136pub const ALPN_DUPLEX: &[u8] = b"iroh-http/2-duplex";
138
139pub(crate) type BoxBody =
143 http_body_util::combinators::BoxBody<bytes::Bytes, std::convert::Infallible>;
144
145pub(crate) fn box_body<B>(body: B) -> BoxBody
147where
148 B: http_body::Body<Data = bytes::Bytes, Error = std::convert::Infallible>
149 + Send
150 + Sync
151 + 'static,
152{
153 use http_body_util::BodyExt;
154 body.map_err(|_| unreachable!()).boxed()
155}
156
157pub fn secret_key_sign(secret_key_bytes: &[u8; 32], data: &[u8]) -> Result<[u8; 64], CoreError> {
162 std::panic::catch_unwind(|| {
163 let key = iroh::SecretKey::from_bytes(secret_key_bytes);
164 key.sign(data).to_bytes()
165 })
166 .map_err(|_| CoreError::internal("secret_key_sign panicked"))
167}
168
169pub fn public_key_verify(public_key_bytes: &[u8; 32], data: &[u8], sig_bytes: &[u8; 64]) -> bool {
172 std::panic::catch_unwind(|| {
173 let Ok(key) = iroh::PublicKey::from_bytes(public_key_bytes) else {
174 return false;
175 };
176 let sig = iroh::Signature::from_bytes(sig_bytes);
177 key.verify(data, &sig).is_ok()
178 })
179 .unwrap_or(false)
180}
181
182pub fn generate_secret_key() -> Result<[u8; 32], CoreError> {
184 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
185 iroh::SecretKey::generate(&mut rand::rng()).to_bytes()
186 }))
187 .map_err(|_| CoreError::internal("generate_secret_key panicked"))
188}
189
190pub fn base32_encode(bytes: &[u8]) -> String {
194 base32::encode(base32::Alphabet::Rfc4648Lower { padding: false }, bytes)
195}
196
197pub(crate) fn base32_decode(s: &str) -> Result<Vec<u8>, String> {
199 base32::decode(base32::Alphabet::Rfc4648Lower { padding: false }, s)
200 .ok_or_else(|| format!("invalid base32 string: {s}"))
201}
202
203pub(crate) fn parse_node_id(s: &str) -> Result<iroh::PublicKey, CoreError> {
205 let bytes = base32_decode(s).map_err(CoreError::invalid_input)?;
206 let arr: [u8; 32] = bytes
207 .try_into()
208 .map_err(|_| CoreError::invalid_input("node-id must be 32 bytes"))?;
209 iroh::PublicKey::from_bytes(&arr).map_err(|e| CoreError::invalid_input(e.to_string()))
210}
211
212pub fn node_ticket(ep: &IrohEndpoint) -> Result<String, CoreError> {
219 let info = ep.node_addr();
220 serde_json::to_string(&info)
221 .map_err(|e| CoreError::internal(format!("failed to serialize node ticket: {e}")))
222}
223
224pub struct ParsedNodeAddr {
226 pub node_id: iroh::PublicKey,
227 pub direct_addrs: Vec<std::net::SocketAddr>,
228}
229
230pub fn parse_node_addr(s: &str) -> Result<ParsedNodeAddr, CoreError> {
238 if let Ok(info) = serde_json::from_str::<NodeAddrInfo>(s) {
239 let node_id = parse_node_id(&info.id)?;
240 let mut direct_addrs = Vec::new();
241 for addr_str in &info.addrs {
242 if addr_str.contains("://") {
244 continue;
245 }
246 let addr = addr_str
247 .parse::<std::net::SocketAddr>()
248 .map_err(|_| CoreError::invalid_input(format!("malformed address: {addr_str}")))?;
249 direct_addrs.push(addr);
250 }
251 return Ok(ParsedNodeAddr {
252 node_id,
253 direct_addrs,
254 });
255 }
256 let node_id = parse_node_id(s)?;
257 Ok(ParsedNodeAddr {
258 node_id,
259 direct_addrs: Vec::new(),
260 })
261}
262
263#[derive(Debug, Clone)]
271pub struct FfiResponse {
272 pub status: u16,
273 pub headers: Vec<(String, String)>,
274 pub body_handle: u64,
276 pub url: String,
278}
279
280#[derive(Debug)]
282pub struct RequestPayload {
283 pub req_handle: u64,
284 pub req_body_handle: u64,
285 pub res_body_handle: u64,
286 pub method: String,
287 pub url: String,
288 pub headers: Vec<(String, String)>,
289 pub remote_node_id: String,
290 pub is_bidi: bool,
291}
292
293#[derive(Debug)]
295pub struct FfiDuplexStream {
296 pub read_handle: u64,
297 pub write_handle: u64,
298}
299
300#[cfg(test)]
301mod tests {
302 use super::*;
303
304 #[test]
305 fn base32_round_trip() {
306 let original: Vec<u8> = (0..32).collect();
307 let encoded = base32_encode(&original);
308 let decoded = base32_decode(&encoded).unwrap();
309 assert_eq!(decoded, original);
310 }
311
312 #[test]
313 fn base32_empty() {
314 let encoded = base32_encode(&[]);
315 assert_eq!(encoded, "");
316 let decoded = base32_decode("").unwrap();
317 assert!(decoded.is_empty());
318 }
319
320 #[test]
321 fn base32_decode_invalid_char() {
322 let result = base32_decode("!!!invalid!!!");
323 assert!(result.is_err());
324 }
325
326 #[test]
327 fn parse_node_id_invalid_base32() {
328 let result = parse_node_id("!!!not-base32!!!");
329 assert!(result.is_err());
330 }
331
332 #[test]
333 fn parse_node_id_wrong_length() {
334 let result = parse_node_id("aa");
335 assert!(result.is_err());
336 }
337
338 #[test]
339 fn core_error_display() {
340 let e = CoreError::timeout("30s elapsed");
341 assert!(e.to_string().contains("Timeout"));
342 assert!(e.to_string().contains("30s elapsed"));
343 }
344}