rama-net 0.3.0

rama network types and utilities
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
//! [`service::Matcher`]s implementations to match on [`Socket`]s.
//!
//! See [`service::matcher` module] for more information.
//!
//! [`service::Matcher`]: rama_core::matcher::Matcher
//! [`Socket`]: crate::stream::Socket
//! [`service::matcher` module]: rama_core::matcher

mod socket;
#[doc(inline)]
pub use socket::SocketAddressMatcher;

mod port;
#[doc(inline)]
pub use port::PortMatcher;

mod private_ip;
#[doc(inline)]
pub use private_ip::PrivateIpNetMatcher;

mod loopback;
#[doc(inline)]
pub use loopback::LoopbackMatcher;

pub mod ip;
#[doc(inline)]
pub use ip::IpNetMatcher;

use std::{fmt, sync::Arc};

use crate::address::SocketAddress;

use rama_core::matcher::Matcher as _;
use rama_core::{extensions::Extensions, matcher::IteratorMatcherExt};

/// A matcher to match on a [`Socket`].
///
/// [`Socket`]: crate::stream::Socket
pub struct SocketMatcher<Socket> {
    kind: SocketMatcherKind<Socket>,
    negate: bool,
}

impl<Socket> Clone for SocketMatcher<Socket> {
    fn clone(&self) -> Self {
        Self {
            kind: self.kind.clone(),
            negate: self.negate,
        }
    }
}

impl<Socket> fmt::Debug for SocketMatcher<Socket> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SocketMatcher")
            .field("kind", &self.kind)
            .field("negate", &self.negate)
            .finish()
    }
}

/// The different kinds of socket matchers.
enum SocketMatcherKind<Socket> {
    /// [`SocketAddressMatcher`], a matcher that matches on the [`SocketAddr`] of the peer.
    ///
    /// [`SocketAddr`]: core::net::SocketAddr
    SocketAddress(SocketAddressMatcher),
    /// [`LoopbackMatcher`], a matcher that matches if the peer address is a loopback address.
    Loopback(LoopbackMatcher),
    /// [`PrivateIpNetMatcher`], a matcher that matches if the peer address is a private address.
    PrivateIpNet(PrivateIpNetMatcher),
    /// [`PortMatcher`], a matcher based on the port part of the [`SocketAddr`] of the peer.
    ///
    /// [`SocketAddr`]: core::net::SocketAddr
    Port(PortMatcher),
    /// [`IpNetMatcher`], a matcher to match on whether or not
    /// the [`IpNet`] contains the [`SocketAddr`] of the peer.
    ///
    /// [`IpNet`]: ipnet::IpNet
    /// [`SocketAddr`]: core::net::SocketAddr
    IpNet(IpNetMatcher),
    /// zero or more matchers that all need to match in order for the matcher to return `true`.
    All(Vec<SocketMatcher<Socket>>),
    /// `true` if no matchers are defined, or any of the defined matcher match.
    Any(Vec<SocketMatcher<Socket>>),
    /// A custom matcher that implements [`rama_core::matcher::Matcher`].
    Custom(Arc<dyn rama_core::matcher::Matcher<Socket>>),
}

impl<Socket> Clone for SocketMatcherKind<Socket> {
    fn clone(&self) -> Self {
        match self {
            Self::SocketAddress(matcher) => Self::SocketAddress(matcher.clone()),
            Self::Loopback(matcher) => Self::Loopback(matcher.clone()),
            Self::PrivateIpNet(matcher) => Self::PrivateIpNet(matcher.clone()),
            Self::Port(matcher) => Self::Port(matcher.clone()),
            Self::IpNet(matcher) => Self::IpNet(matcher.clone()),
            Self::All(matcher) => Self::All(matcher.clone()),
            Self::Any(matcher) => Self::Any(matcher.clone()),
            Self::Custom(matcher) => Self::Custom(matcher.clone()),
        }
    }
}

impl<Socket> fmt::Debug for SocketMatcherKind<Socket> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::SocketAddress(matcher) => f.debug_tuple("SocketAddress").field(matcher).finish(),
            Self::Loopback(matcher) => f.debug_tuple("Loopback").field(matcher).finish(),
            Self::PrivateIpNet(matcher) => f.debug_tuple("PrivateIpNet").field(matcher).finish(),
            Self::Port(matcher) => f.debug_tuple("Port").field(matcher).finish(),
            Self::IpNet(matcher) => f.debug_tuple("IpNet").field(matcher).finish(),
            Self::All(matcher) => f.debug_tuple("All").field(matcher).finish(),
            Self::Any(matcher) => f.debug_tuple("Any").field(matcher).finish(),
            Self::Custom(_) => f.debug_tuple("Custom").finish(),
        }
    }
}

impl<Socket> SocketMatcher<Socket> {
    /// Create a new socket address matcher to match on a socket address.
    ///
    /// See [`SocketAddressMatcher::new`] for more information.
    pub fn socket_addr(addr: impl Into<SocketAddress>) -> Self {
        Self {
            kind: SocketMatcherKind::SocketAddress(SocketAddressMatcher::new(addr)),
            negate: false,
        }
    }

    /// Create a new optional socket address matcher to match on a socket address,
    /// this matcher will match in case socket address could not be found.
    ///
    /// See [`SocketAddressMatcher::optional`] for more information.
    pub fn optional_socket_addr(addr: impl Into<SocketAddress>) -> Self {
        Self {
            kind: SocketMatcherKind::SocketAddress(SocketAddressMatcher::optional(addr)),
            negate: false,
        }
    }

    /// Add a new socket address matcher to the existing [`SocketMatcher`] to also match on a socket address.
    #[must_use]
    pub fn and_socket_addr(self, addr: impl Into<SocketAddress>) -> Self {
        self.and(Self::socket_addr(addr))
    }

    /// Add a new optional socket address matcher to the existing [`SocketMatcher`] to also match on a socket address.
    ///
    /// See [`SocketAddressMatcher::optional`] for more information.
    #[must_use]
    pub fn and_optional_socket_addr(self, addr: impl Into<SocketAddress>) -> Self {
        self.and(Self::optional_socket_addr(addr))
    }

    /// Add a new socket address matcher to the existing [`SocketMatcher`] as an alternative matcher to match on a socket address.
    ///
    /// See [`SocketAddressMatcher::new`] for more information.
    #[must_use]
    pub fn or_socket_addr(self, addr: impl Into<SocketAddress>) -> Self {
        self.or(Self::socket_addr(addr))
    }

    /// Add a new optional socket address matcher to the existing [`SocketMatcher`] as an alternative matcher to match on a socket address.
    ///
    /// See [`SocketAddressMatcher::optional`] for more information.
    #[must_use]
    pub fn or_optional_socket_addr(self, addr: impl Into<SocketAddress>) -> Self {
        self.or(Self::optional_socket_addr(addr))
    }

    /// create a new loopback matcher to match on whether or not the peer address is a loopback address.
    ///
    /// See [`LoopbackMatcher::new`] for more information.
    #[must_use]
    pub fn loopback() -> Self {
        Self {
            kind: SocketMatcherKind::Loopback(LoopbackMatcher::new()),
            negate: false,
        }
    }

    /// Create a new optional loopback matcher to match on whether or not the peer address is a loopback address,
    /// this matcher will match in case socket address could not be found.
    ///
    /// See [`LoopbackMatcher::optional`] for more information.
    #[must_use]
    pub fn optional_loopback() -> Self {
        Self {
            kind: SocketMatcherKind::Loopback(LoopbackMatcher::optional()),
            negate: false,
        }
    }

    /// Add a new loopback matcher to the existing [`SocketMatcher`] to also match on whether or not the peer address is a loopback address.
    ///
    /// See [`LoopbackMatcher::new`] for more information.
    #[must_use]
    pub fn and_loopback(self) -> Self {
        self.and(Self::loopback())
    }

    /// Add a new loopback matcher to the existing [`SocketMatcher`] to also match on whether or not the peer address is a loopback address.
    ///
    /// See [`LoopbackMatcher::optional`] for more information.
    #[must_use]
    pub fn and_optional_loopback(self) -> Self {
        self.and(Self::optional_loopback())
    }

    /// Add a new loopback matcher to the existing [`SocketMatcher`] as an alternative matcher to match on whether or not the peer address is a loopback address.
    ///
    /// See [`LoopbackMatcher::new`] for more information.
    #[must_use]
    pub fn or_loopback(self) -> Self {
        self.or(Self::loopback())
    }

    /// Add a new loopback matcher to the existing [`SocketMatcher`] as an alternative matcher to match on whether or not the peer address is a loopback address.
    ///
    /// See [`LoopbackMatcher::optional`] for more information.
    #[must_use]
    pub fn or_optional_loopback(self) -> Self {
        self.or(Self::optional_loopback())
    }

    /// create a new port matcher to match on the port part a [`SocketAddr`](core::net::SocketAddr).
    ///
    /// See [`PortMatcher::new`] for more information.
    #[must_use]
    pub fn port(port: u16) -> Self {
        Self {
            kind: SocketMatcherKind::Port(PortMatcher::new(port)),
            negate: false,
        }
    }

    /// Create a new optional port matcher to match on the port part a [`SocketAddr`](core::net::SocketAddr),
    /// this matcher will match in case socket address could not be found.
    ///
    /// See [`PortMatcher::optional`] for more information.
    #[must_use]
    pub fn optional_port(port: u16) -> Self {
        Self {
            kind: SocketMatcherKind::Port(PortMatcher::optional(port)),
            negate: false,
        }
    }

    /// Add a new port matcher to the existing [`SocketMatcher`] to
    /// also matcher on the port part of the [`SocketAddr`](core::net::SocketAddr).
    ///
    /// See [`PortMatcher::new`] for more information.
    #[must_use]
    pub fn and_port(self, port: u16) -> Self {
        self.and(Self::port(port))
    }

    /// Add a new port matcher to the existing [`SocketMatcher`] as an alternative matcher
    /// to match on the port part of the [`SocketAddr`](core::net::SocketAddr).
    ///
    /// See [`PortMatcher::optional`] for more information.
    #[must_use]
    pub fn and_optional_port(self, port: u16) -> Self {
        self.and(Self::optional_port(port))
    }

    /// Add a new port matcher to the existing [`SocketMatcher`] as an alternative matcher
    /// to match on the port part of the [`SocketAddr`](core::net::SocketAddr).
    ///
    /// See [`PortMatcher::new`] for more information.
    #[must_use]
    pub fn or_port(self, port: u16) -> Self {
        self.or(Self::port(port))
    }

    /// Add a new port matcher to the existing [`SocketMatcher`] as an alternative matcher
    /// to match on the port part of the [`SocketAddr`](core::net::SocketAddr).
    ///
    /// See [`PortMatcher::optional`] for more information.
    #[must_use]
    pub fn or_optional_port(self, port: u16) -> Self {
        self.or(Self::optional_port(port))
    }

    /// create a new IP network matcher to match on an IP Network.
    ///
    /// See [`IpNetMatcher::new`] for more information.
    pub fn ip_net(ip_net: impl ip::IntoIpNet) -> Self {
        Self {
            kind: SocketMatcherKind::IpNet(IpNetMatcher::new(ip_net)),
            negate: false,
        }
    }

    /// Create a new optional IP network matcher to match on an IP Network,
    /// this matcher will match in case socket address could not be found.
    ///
    /// See [`IpNetMatcher::optional`] for more information.
    pub fn optional_ip_net(ip_net: impl ip::IntoIpNet) -> Self {
        Self {
            kind: SocketMatcherKind::IpNet(IpNetMatcher::optional(ip_net)),
            negate: false,
        }
    }

    /// Add a new IP network matcher to the existing [`SocketMatcher`] to also match on an IP Network.
    ///
    /// See [`IpNetMatcher::new`] for more information.
    #[must_use]
    pub fn and_ip_net(self, ip_net: impl ip::IntoIpNet) -> Self {
        self.and(Self::ip_net(ip_net))
    }

    /// Add a new IP network matcher to the existing [`SocketMatcher`] as an alternative matcher to match on an IP Network.
    ///
    /// See [`IpNetMatcher::optional`] for more information.
    #[must_use]
    pub fn and_optional_ip_net(self, ip_net: impl ip::IntoIpNet) -> Self {
        self.and(Self::optional_ip_net(ip_net))
    }

    /// Add a new IP network matcher to the existing [`SocketMatcher`] as an alternative matcher to match on an IP Network.
    ///
    /// See [`IpNetMatcher::new`] for more information.
    #[must_use]
    pub fn or_ip_net(self, ip_net: impl ip::IntoIpNet) -> Self {
        self.or(Self::ip_net(ip_net))
    }

    /// Add a new IP network matcher to the existing [`SocketMatcher`] as an alternative matcher to match on an IP Network.
    ///
    /// See [`IpNetMatcher::optional`] for more information.
    #[must_use]
    pub fn or_optional_ip_net(self, ip_net: impl ip::IntoIpNet) -> Self {
        self.or(Self::optional_ip_net(ip_net))
    }

    /// create a new local IP network matcher to match on whether or not the peer address is a private address.
    ///
    /// See [`PrivateIpNetMatcher::new`] for more information.
    #[must_use]
    pub fn private_ip_net() -> Self {
        Self {
            kind: SocketMatcherKind::PrivateIpNet(PrivateIpNetMatcher::new()),
            negate: false,
        }
    }

    /// Create a new optional local IP network matcher to match on whether or not the peer address is a private address,
    /// this matcher will match in case socket address could not be found.
    ///
    /// See [`PrivateIpNetMatcher::optional`] for more information.
    #[must_use]
    pub fn optional_private_ip_net() -> Self {
        Self {
            kind: SocketMatcherKind::PrivateIpNet(PrivateIpNetMatcher::optional()),
            negate: false,
        }
    }

    /// Add a new local IP network matcher to the existing [`SocketMatcher`] to also match on whether or not the peer address is a private address.
    ///
    /// See [`PrivateIpNetMatcher::new`] for more information.
    #[must_use]
    pub fn and_private_ip_net(self) -> Self {
        self.and(Self::private_ip_net())
    }

    /// Add a new local IP network matcher to the existing [`SocketMatcher`] to also match on whether or not the peer address is a private address.
    ///
    /// See [`PrivateIpNetMatcher::optional`] for more information.
    #[must_use]
    pub fn and_optional_private_ip_net(self) -> Self {
        self.and(Self::optional_private_ip_net())
    }

    /// Add a new local IP network matcher to the existing [`SocketMatcher`] as an alternative matcher to match on whether or not the peer address is a private address.
    ///
    /// See [`PrivateIpNetMatcher::new`] for more information.
    #[must_use]
    pub fn or_private_ip_net(self) -> Self {
        self.or(Self::private_ip_net())
    }

    /// Add a new local IP network matcher to the existing [`SocketMatcher`] as an alternative matcher to match on whether or not the peer address is a private address.
    ///
    /// See [`PrivateIpNetMatcher::optional`] for more information.
    #[must_use]
    pub fn or_optional_private_ip_net(self) -> Self {
        self.or(Self::optional_private_ip_net())
    }

    /// Create a matcher that matches according to a custom predicate.
    ///
    /// See [`rama_core::matcher::Matcher`] for more information.
    pub fn custom<M>(matcher: M) -> Self
    where
        M: rama_core::matcher::Matcher<Socket>,
    {
        Self {
            kind: SocketMatcherKind::Custom(Arc::new(matcher)),
            negate: false,
        }
    }

    /// Add a custom matcher to match on top of the existing set of [`SocketMatcher`] matchers.
    ///
    /// See [`rama_core::matcher::Matcher`] for more information.
    #[must_use]
    pub fn and_custom<M>(self, matcher: M) -> Self
    where
        M: rama_core::matcher::Matcher<Socket>,
    {
        self.and(Self::custom(matcher))
    }

    /// Create a custom matcher to match as an alternative to the existing set of [`SocketMatcher`] matchers.
    ///
    /// See [`rama_core::matcher::Matcher`] for more information.
    #[must_use]
    pub fn or_custom<M>(self, matcher: M) -> Self
    where
        M: rama_core::matcher::Matcher<Socket>,
    {
        self.or(Self::custom(matcher))
    }

    /// Add a [`SocketMatcher`] to match on top of the existing set of [`SocketMatcher`] matchers.
    #[must_use]
    pub fn and(mut self, matcher: Self) -> Self {
        match (self.negate, &mut self.kind) {
            (false, SocketMatcherKind::All(v)) => {
                v.push(matcher);
                self
            }
            _ => Self {
                kind: SocketMatcherKind::All(vec![self, matcher]),
                negate: false,
            },
        }
    }

    /// Create a [`SocketMatcher`] matcher to match as an alternative to the existing set of [`SocketMatcher`] matchers.
    #[must_use]
    pub fn or(mut self, matcher: Self) -> Self {
        match (self.negate, &mut self.kind) {
            (false, SocketMatcherKind::Any(v)) => {
                v.push(matcher);
                self
            }
            _ => Self {
                kind: SocketMatcherKind::Any(vec![self, matcher]),
                negate: false,
            },
        }
    }

    /// Negate the current matcher
    #[must_use]
    pub fn negate(self) -> Self {
        Self {
            kind: self.kind,
            negate: true,
        }
    }
}

impl<Socket> rama_core::matcher::Matcher<Socket> for SocketMatcherKind<Socket>
where
    Socket: crate::stream::Socket,
{
    fn matches(&self, ext: Option<&Extensions>, stream: &Socket) -> bool {
        match self {
            Self::SocketAddress(matcher) => matcher.matches(ext, stream),
            Self::IpNet(matcher) => matcher.matches(ext, stream),
            Self::Loopback(matcher) => matcher.matches(ext, stream),
            Self::PrivateIpNet(matcher) => matcher.matches(ext, stream),
            Self::Port(matcher) => matcher.matches(ext, stream),
            Self::All(matchers) => matchers.iter().matches_and(ext, stream),
            Self::Any(matchers) => matchers.iter().matches_or(ext, stream),
            Self::Custom(matcher) => matcher.matches(ext, stream),
        }
    }
}

impl<Socket> rama_core::matcher::Matcher<Socket> for SocketMatcher<Socket>
where
    Socket: crate::stream::Socket,
{
    fn matches(&self, ext: Option<&Extensions>, stream: &Socket) -> bool {
        let result = self.kind.matches(ext, stream);
        if self.negate { !result } else { result }
    }
}

impl<S> SocketMatcherKind<S> {
    /// Match against a value of the matcher's own input type `S` (rather than a
    /// [`Socket`](crate::stream::Socket)), given that each socket-address leaf
    /// matcher also implements [`Matcher<S>`](rama_core::matcher::Matcher).
    ///
    /// This lets crates whose input `S` is not a `Socket` — e.g. an HTTP
    /// `Request`, matched through its `SocketInfo` extension — reuse the
    /// composite `All`/`Any`/`Custom` logic without exposing the private
    /// matcher kinds. The `Socket`-based [`Matcher`] impl is unaffected.
    ///
    /// [`Matcher`]: rama_core::matcher::Matcher
    fn matches_input(&self, ext: Option<&Extensions>, target: &S) -> bool
    where
        S: 'static,
        SocketAddressMatcher: rama_core::matcher::Matcher<S>,
        LoopbackMatcher: rama_core::matcher::Matcher<S>,
        PrivateIpNetMatcher: rama_core::matcher::Matcher<S>,
        PortMatcher: rama_core::matcher::Matcher<S>,
        IpNetMatcher: rama_core::matcher::Matcher<S>,
    {
        match self {
            Self::SocketAddress(matcher) => matcher.matches(ext, target),
            Self::IpNet(matcher) => matcher.matches(ext, target),
            Self::Loopback(matcher) => matcher.matches(ext, target),
            Self::PrivateIpNet(matcher) => matcher.matches(ext, target),
            Self::Port(matcher) => matcher.matches(ext, target),
            // `All`/`Any` replicate the ext-merging semantics of
            // `matches_and`/`matches_or` (which require `Matcher<S>` on the
            // nested matcher, unavailable for a non-`Socket` `S`).
            Self::All(matchers) => match ext {
                None => matchers.iter().all(|m| m.matches_input(None, target)),
                Some(ext) => {
                    let inner = Extensions::new();
                    if matchers
                        .iter()
                        .all(|m| m.matches_input(Some(&inner), target))
                    {
                        ext.extend(&inner);
                        true
                    } else {
                        false
                    }
                }
            },
            Self::Any(matchers) => {
                if matchers.is_empty() {
                    return true;
                }
                match ext {
                    None => matchers.iter().any(|m| m.matches_input(None, target)),
                    Some(ext) => {
                        for m in matchers {
                            let inner = Extensions::new();
                            if m.matches_input(Some(&inner), target) {
                                ext.extend(&inner);
                                return true;
                            }
                        }
                        false
                    }
                }
            }
            Self::Custom(matcher) => matcher.matches(ext, target),
        }
    }
}

impl<S> SocketMatcher<S> {
    /// Match against a value of the matcher's own input type `S` via the
    /// socket-address leaves' [`Matcher<S>`](rama_core::matcher::Matcher)
    /// impls, applying this matcher's negation on top.
    pub fn matches_input(&self, ext: Option<&Extensions>, target: &S) -> bool
    where
        S: 'static,
        SocketAddressMatcher: rama_core::matcher::Matcher<S>,
        LoopbackMatcher: rama_core::matcher::Matcher<S>,
        PrivateIpNetMatcher: rama_core::matcher::Matcher<S>,
        PortMatcher: rama_core::matcher::Matcher<S>,
        IpNetMatcher: rama_core::matcher::Matcher<S>,
    {
        let result = self.kind.matches_input(ext, target);
        if self.negate { !result } else { result }
    }
}