h3x 0.6.1

Peer-to-peer DHTTP/3 transport over QUIC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
use std::{
    cell::LazyCell,
    fmt,
    hash::{Hash, Hasher},
    str::FromStr,
};

use either::Either;
use http::{
    Uri,
    uri::{Authority, PathAndQuery},
};
use peg::{error::ParseError, str::LineCol};

use super::BindHost;
use crate::dquic::{
    net::Family,
    qinterface::bind_uri::{BindUri, Scheme},
};

/// A flexible bind pattern parsed from a string.
///
/// See [module documentation](super) for the full syntax description.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BindPattern {
    /// The resolved scheme (`iface` or `inet`). Always present after parsing.
    pub scheme: Scheme,
    /// Host part — exact name/IP or glob pattern (carries family if applicable).
    pub host: BindHost,
    /// Port number. `None` means default (0 = system-assigned).
    pub port: Option<u16>,
    /// Optional path-and-query suffix carried through to generated URIs,
    /// validated as [`PathAndQuery`] during parsing.
    pub path_and_query: Option<PathAndQuery>,
}

impl Hash for BindPattern {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.scheme.hash(state);
        self.host.hash(state);
        self.port.hash(state);
        self.path_and_query
            .as_ref()
            .map(|pq| pq.as_str())
            .hash(state);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn match_helpers_reject_uri_of_other_shape() {
        let iface_pattern: BindPattern = "iface://v4.en*:8080".parse().unwrap();
        let inet_uri: BindUri = "inet://127.0.0.1:8080".parse().unwrap();
        assert!(!iface_pattern.matches_iface_bind_uri(&inet_uri));

        let inet_pattern: BindPattern = "inet://127.0.0.1:8080".parse().unwrap();
        let iface_uri: BindUri = "iface://v4.enp17s0:8080".parse().unwrap();
        assert!(!inet_pattern.matches_inet_bind_uri(&iface_uri));
    }

    #[test]
    fn ip_hosts_do_not_match_interface_links() {
        let pattern: BindPattern = "127.0.0.1:8080".parse().unwrap();

        assert_eq!(pattern.match_interface_links("lo").count(), 0);
    }

    #[test]
    fn interface_bind_uris_expand_only_iface_patterns() {
        let iface_pattern: BindPattern = "iface://v4.lo:8080".parse().unwrap();
        let inet_pattern: BindPattern = "inet://127.0.0.1:8080".parse().unwrap();

        let iface_uris: Vec<_> = iface_pattern
            .interface_bind_uris("lo")
            .map(|uri| uri.to_string())
            .collect();

        assert_eq!(iface_uris, ["iface://v4.lo:8080/"]);
        assert!(inet_pattern.interface_bind_uris("lo").next().is_none());
    }

    #[test]
    fn unknown_explicit_scheme_falls_back_to_iface() {
        let pattern: BindPattern = "custom://v4.en*:8080/path?query".parse().unwrap();

        assert_eq!(pattern.scheme, Scheme::Iface);
        assert_eq!(pattern.path_and_query_str(), Some("/path?query"));
        assert_eq!(pattern.to_string(), "iface://v4.en*:8080/path?query");
    }
}

// ---------------------------------------------------------------------------
// Display
// ---------------------------------------------------------------------------

impl fmt::Display for BindPattern {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}://", self.scheme)?;
        if let Some(family) = self.host.family() {
            let tag = match family {
                Family::V4 => "v4",
                Family::V6 => "v6",
            };
            write!(f, "{tag}.")?;
        }
        if self.host.as_ip_addr().is_some_and(|ip| ip.is_ipv6()) {
            write!(f, "[{}]", self.host)?;
        } else {
            write!(f, "{}", self.host)?;
        }
        if let Some(port) = self.port {
            write!(f, ":{port}")?;
        }
        if let Some(ref pq) = self.path_and_query {
            write!(f, "{pq}")?;
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// PEG parser
// ---------------------------------------------------------------------------

peg::parser! {
    grammar bind_parser() for str {
        // -- atoms --

        rule family() -> Family
            = "v4" { Family::V4 }
            / "V4" { Family::V4 }
            / "v6" { Family::V6 }
            / "V6" { Family::V6 }

        /// Scheme prefix like `iface://` or `inet://`.
        rule scheme() -> &'input str
            = s:$(['a'..='z' | 'A'..='Z']+) "://" { s }

        /// Port number after `:`.
        rule port() -> u16
            = ":" n:$(['0'..='9']+) {?
                n.parse().or(Err("valid port number"))
            }

        /// A host character — anything except `:`, `/`, `?`, `#`, `[`, `]`.
        rule host_char() -> char
            = c:[^ ':' | '/' | '?' | '#' | '[' | ']'] { c }

        /// A bracket segment: `[...]` (IPv6 address or glob character class).
        rule bracket_segment()
            = "[" [^ ']']+ "]"

        /// A single host token: bracket segment or plain character.
        rule host_token()
            = bracket_segment()
            / host_char()

        /// Host string — one or more host tokens captured as a single slice.
        rule host_str() -> &'input str
            = s:$(host_token()+) { s }

        /// Path-and-query remainder: everything from `/` or `?` onward.
        rule path_and_query() -> &'input str
            = s:$(['/' | '?'] [_]*) { s }

        // -- composite rules --

        /// `scheme://family.host:port/path?query`  (full form)
        pub rule full() -> BindPattern
            = s:scheme()
              fam:(f:family() "." { f })?
              h:host_str()
              p:port()?
              pq:path_and_query()?
            {?
                let host = BindHost::classify(h, fam)?;
                let scheme = infer_scheme(Some(s), &host);
                let path_and_query = pq
                    .map(|s| s.parse::<PathAndQuery>())
                    .transpose()
                    .map_err(|_| "valid path-and-query")?;
                Ok(BindPattern { scheme, host, port: p, path_and_query })
            }

        /// `family.host:port/path?query`  (no scheme)
        pub rule no_scheme() -> BindPattern
            = fam:(f:family() "." { f })?
              h:host_str()
              p:port()?
              pq:path_and_query()?
            {?
                let host = BindHost::classify(h, fam)?;
                let scheme = infer_scheme(None, &host);
                let path_and_query = pq
                    .map(|s| s.parse::<PathAndQuery>())
                    .transpose()
                    .map_err(|_| "valid path-and-query")?;
                Ok(BindPattern { scheme, host, port: p, path_and_query })
            }

        /// Top-level entry: bare IP first, then full form, then no-scheme.
        ///
        /// `bare_ip` has highest priority — its `{? ... }` semantic guard
        /// ensures only valid IP addresses match; everything else backtracks.
        pub rule bind() -> BindPattern
            = b:bare_ip() { b }
            / b:full() { b }
            / b:no_scheme() { b }

        /// Bare IP address: `::1`, `::`, `2001:db8::1`, `127.0.0.1`.
        ///
        /// Captures everything up to `/`, `?`, or `#` (or end of input) and
        /// validates it as an [`IpAddr`].  Falls back via PEG ordered choice
        /// if validation fails.
        rule bare_ip() -> BindPattern
            = s:$([^ '/' | '?' | '#']+) pq:path_and_query()? {?
                let addr = s.parse::<std::net::IpAddr>().or(Err("valid IP address"))?;
                let path_and_query = pq
                    .map(|s| s.parse::<PathAndQuery>())
                    .transpose()
                    .map_err(|_| "valid path-and-query")?;
                Ok(BindPattern {
                    scheme: Scheme::Inet,
                    host: BindHost::Ip { addr, repr: s.to_owned() },
                    port: None,
                    path_and_query,
                })
            }
    }
}

// ---------------------------------------------------------------------------
// Scheme inference helper
// ---------------------------------------------------------------------------

/// Infer the bind scheme from an optional explicit scheme string and the host.
fn infer_scheme(explicit: Option<&str>, host: &BindHost) -> Scheme {
    if let Some(s) = explicit {
        return match s.to_ascii_lowercase().as_str() {
            "iface" => Scheme::Iface,
            "inet" => Scheme::Inet,
            _ => Scheme::Iface,
        };
    }
    if host.is_ip_addr() {
        Scheme::Inet
    } else {
        Scheme::Iface
    }
}

// ---------------------------------------------------------------------------
// FromStr
// ---------------------------------------------------------------------------

impl FromStr for BindPattern {
    type Err = ParseError<LineCol>;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        bind_parser::bind(s)
    }
}

// ---------------------------------------------------------------------------
// BindPattern → BindUri expansion
// ---------------------------------------------------------------------------

impl BindPattern {
    /// Returns the path-and-query as a string slice, if present.
    #[must_use]
    pub fn path_and_query_str(&self) -> Option<&str> {
        self.path_and_query.as_ref().map(|pq| pq.as_str())
    }

    /// Returns the effective port (defaults to 0 when omitted).
    #[must_use]
    pub fn effective_port(&self) -> u16 {
        self.port.unwrap_or(0)
    }

    /// Check if a concrete [`BindUri`] could be produced by this pattern.
    ///
    /// Compares scheme, port, and host. Wildcard ports (None) match any port.
    /// For `iface://` URIs, the family prefix is matched separately from the
    /// interface name. Glob/exact hosts use [`BindHost::matches`] for pattern
    /// matching.
    #[must_use]
    pub fn matches(&self, bind_uri: &BindUri) -> bool {
        if self.scheme != bind_uri.scheme() {
            return false;
        }
        match self.scheme {
            Scheme::Iface => self.matches_iface_bind_uri(bind_uri),
            Scheme::Inet => self.matches_inet_bind_uri(bind_uri),
            _ => false,
        }
    }

    pub(crate) fn interface_bind_uris<'a>(
        &'a self,
        interface: &'a str,
    ) -> impl Iterator<Item = BindUri> + use<'a> {
        let template = self.template();
        match self.scheme {
            Scheme::Iface => {
                Either::Left(self.match_interface_links(interface).filter_map(template))
            }
            _ => Either::Right(std::iter::empty()),
        }
    }

    fn port_matches(&self, actual: u16) -> bool {
        if let Some(expected) = self.port
            && expected != actual
        {
            return false;
        }
        true
    }

    fn matches_iface_bind_uri(&self, bind_uri: &BindUri) -> bool {
        let Some((family, interface, port)) = bind_uri.as_iface_bind_uri() else {
            return false;
        };
        if !self.port_matches(port) {
            return false;
        }
        match &self.host {
            BindHost::Ip { .. } => false,
            host => {
                if let Some(pattern_family) = host.family()
                    && pattern_family != family
                {
                    return false;
                }
                host.matches(interface)
            }
        }
    }

    fn matches_inet_bind_uri(&self, bind_uri: &BindUri) -> bool {
        let Some(addr) = bind_uri.as_inet_bind_uri() else {
            return false;
        };
        if !self.port_matches(addr.port()) {
            return false;
        }
        match &self.host {
            BindHost::Ip { addr: pattern, .. } => *pattern == addr.ip(),
            BindHost::Glob { .. } | BindHost::Exact { .. } => false,
        }
    }

    pub(crate) fn template(&self) -> impl Fn(Authority) -> Option<BindUri> + use<> {
        let mut uri_template = Uri::from_static("iface://v4.lo:0/").into_parts();
        uri_template.scheme = Some(self.scheme.into());
        uri_template.path_and_query =
            (self.path_and_query.clone()).or(uri_template.path_and_query.clone());
        let uri_template = Uri::from_parts(uri_template)
            .expect("BUG: bind URI template built from valid scheme and path-and-query");

        move |authority: Authority| {
            let mut uri_parts = uri_template.clone().into_parts();
            // original authority is just a placeholder; replace it with the actual authority for every bind URI.
            uri_parts.authority = Some(authority);

            let bind_uri =
                (Uri::from_parts(uri_parts).ok()).and_then(|uri| BindUri::try_from(uri).ok())?;
            Some(bind_uri)
        }
    }

    pub(crate) fn match_interface_links(&self, interface: &str) -> impl Iterator<Item = Authority> {
        match &self.host {
            BindHost::Ip { .. } => Either::Left(std::iter::empty()),
            host if !host.matches(interface) => Either::Left(std::iter::empty()),
            host => Either::Right(host.families().iter().filter_map(move |family| {
                format!("{family}.{interface}:{port}", port = self.effective_port())
                    .parse()
                    .ok()
            })),
        }
    }

    /// Expand this bind pattern into concrete [`BindUri`]s.
    ///
    /// For IP hosts, a single URI is produced directly.
    /// For glob / exact hosts, the `interfaces` list is filtered and each
    /// matching interface is expanded with the applicable IP families.
    pub fn to_bind_uris<'a, I>(
        &'a self,
        interfaces: I,
    ) -> impl Iterator<Item = BindUri> + use<'a, I>
    where
        I: IntoIterator<Item = &'a str>,
    {
        let template = LazyCell::new(|| self.template());
        let port = self.effective_port();
        match &self.host {
            BindHost::Ip { addr, .. } => {
                let link: Authority = if addr.is_ipv6() {
                    format!("[{addr}]:{port}")
                } else {
                    format!("{addr}:{port}")
                }
                .parse()
                .expect("BUG: formatted IP address and port is a valid authority");
                Either::Left(template(link).into_iter())
            }
            // WORKAROUND: clippy bug: https://github.com/rust-lang/rust-clippy/issues/16641 (not fixed)
            #[allow(clippy::redundant_closure)]
            BindHost::Glob { .. } | BindHost::Exact { .. } => Either::Right(
                interfaces
                    .into_iter()
                    .flat_map(move |iface| self.match_interface_links(iface))
                    .flat_map(move |link| template(link)),
            ),
        }
    }
}