veilid-core 0.5.3

Core library used to create a Veilid node and operate it as part of an application
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
use super::*;
use lazy_static::*;

lazy_static! {
    static ref BAD_PORTS: BTreeSet<u16> = BTreeSet::from([
        1,    // tcpmux
        7,    // echo
        9,    // discard
        11,   // systat
        13,   // daytime
        15,   // netstat
        17,   // qotd
        19,   // chargen
        20,   // ftp data
        21,   // ftp access
        22,   // ssh
        23,   // telnet
        25,   // smtp
        37,   // time
        42,   // name
        43,   // nicname
        53,   // domain
        77,   // priv-rjs
        79,   // finger
        87,   // ttylink
        95,   // supdup
        101,  // hostriame
        102,  // iso-tsap
        103,  // gppitnp
        104,  // acr-nema
        109,  // pop2
        110,  // pop3
        111,  // sunrpc
        113,  // auth
        115,  // sftp
        117,  // uucp-path
        119,  // nntp
        123,  // NTP
        135,  // loc-srv /epmap
        139,  // netbios
        143,  // imap2
        179,  // BGP
        389,  // ldap
        427,  // SLP (Also used by Apple Filing Protocol)
        465,  // smtp+ssl
        512,  // print / exec
        513,  // login
        514,  // shell
        515,  // printer
        526,  // tempo
        530,  // courier
        531,  // chat
        532,  // netnews
        540,  // uucp
        548,  // AFP (Apple Filing Protocol)
        556,  // remotefs
        563,  // nntp+ssl
        587,  // smtp (rfc6409)
        601,  // syslog-conn (rfc3195)
        636,  // ldap+ssl
        993,  // ldap+ssl
        995,  // pop3+ssl
        2049, // nfs
        3659, // apple-sasl / PasswordServer
        4045, // lockd
        6000, // X11
        6665, // Alternate IRC [Apple addition]
        6666, // Alternate IRC [Apple addition]
        6667, // Standard IRC [Apple addition]
        6668, // Alternate IRC [Apple addition]
        6669, // Alternate IRC [Apple addition]
        6697, // IRC + TLS
    ]);
}

pub(super) struct NetworkBindSet {
    pub port: u16,
    pub addrs: Vec<IpAddr>,
    pub search: bool,
}

impl Network {
    /////////////////////////////////////////////////////

    // Returns a port, a set of ip addresses to bind to, and a
    // bool specifying if multiple ports should be tried
    #[cfg_attr(feature = "instrument", instrument(level = "trace", skip_all, fields(__VEILID_LOG_KEY = self.log_key())))]
    fn convert_listen_address_to_bind_set(
        &self,
        listen_address: String,
    ) -> EyreResult<NetworkBindSet> {
        if listen_address.is_empty() {
            // If listen address is empty, start with port 5150 and iterate
            let ip_addrs = available_unspecified_addresses();
            Ok(NetworkBindSet {
                port: 5150,
                addrs: ip_addrs,
                search: true,
            })
        } else {
            // If no address is specified, but the port is, use ipv4 and ipv6 unspecified
            // If the address is specified, only use the specified port and fail otherwise
            let sockaddrs =
                listen_address_to_socket_addrs(&listen_address).map_err(|e| eyre!("{}", e))?;
            if sockaddrs.is_empty() {
                bail!("No valid listen address: {}", listen_address);
            }
            let port = sockaddrs[0].port();
            if port == 0 {
                Ok(NetworkBindSet {
                    port: 5150,
                    addrs: sockaddrs.iter().map(|s| s.ip()).collect(),
                    search: true,
                })
            } else {
                Ok(NetworkBindSet {
                    port,
                    addrs: sockaddrs.iter().map(|s| s.ip()).collect(),
                    search: false,
                })
            }
        }
    }

    // Add local dial info to preferred local address table
    pub(super) fn set_preferred_local_address(inner: &mut NetworkInner, pa: PeerAddress) {
        let key = (pa.protocol_type(), pa.address_type());
        let sa = pa.socket_addr();
        // let unspec_sa = match sa {
        //     SocketAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, a.port())),
        //     SocketAddr::V6(a) => {
        //         SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, a.port(), 0, 0))
        //     }
        // };
        inner.preferred_local_addresses.entry(key).or_insert(sa);
    }

    /////////////////////////////////////////////////////

    #[cfg_attr(feature = "instrument", instrument(level = "trace", skip_all, fields(__VEILID_LOG_KEY = self.log_key())))]
    pub(super) fn bind_udp_protocol_handlers(&self) -> EyreResult<StartupDisposition> {
        veilid_log!(self trace "UDP: binding protocol handlers");
        let config = self.config();
        let listen_address = config.network.protocol.udp.listen_address.clone();
        let public_address = config.network.protocol.udp.public_address.clone();
        let require_inbound_relay = config.network.privacy.require_inbound_relay;

        // Get the binding parameters from the user-specified listen address
        let bind_set = self.convert_listen_address_to_bind_set(listen_address.clone())?;

        // Now create udp inbound sockets for whatever interfaces we're listening on
        if bind_set.search {
            veilid_log!(self info
                "UDP: searching for free port starting with {} on {:?}",
                bind_set.port, bind_set.addrs
            );
        } else {
            veilid_log!(self info
                "UDP: binding protocol handlers at port {} on {:?}",
                bind_set.port, bind_set.addrs
            );
        }

        if !self.create_inbound_udp_protocol_handlers(bind_set)? {
            return Ok(StartupDisposition::BindRetry);
        };

        if !self.create_outbound_udp_protocol_handlers()? {
            return Ok(StartupDisposition::BindRetry);
        }

        // Now create tasks for udp listeners
        self.create_udp_listener_tasks()?;

        {
            let mut inner = self.inner.lock();
            if public_address.is_some()
                && !inner.resolved_detect_address_changes
                && !require_inbound_relay
            {
                inner.static_public_dial_info.insert(ProtocolType::UDP);
            }
        }

        Ok(StartupDisposition::Success)
    }

    #[cfg_attr(feature = "instrument", instrument(level = "trace", skip_all, fields(__VEILID_LOG_KEY = self.log_key())))]
    pub(super) fn register_udp_dial_info(
        &self,
        editor_public_internet: &mut RoutingDomainEditorPublicInternet<'_>,
        editor_local_network: &mut RoutingDomainEditorLocalNetwork<'_>,
    ) -> EyreResult<()> {
        veilid_log!(self trace "UDP: registering dial info");

        let config = self.config();
        let public_address = config.network.protocol.udp.public_address.clone();
        let resolved_detect_address_changes = self.inner.lock().resolved_detect_address_changes;
        let require_inbound_relay = config.network.privacy.require_inbound_relay;

        let local_dial_info_list = {
            let mut out = vec![];
            if let Some(bound_addresses) = {
                let inner = self.inner.lock();
                inner
                    .bound_address_per_protocol
                    .get(&ProtocolType::UDP)
                    .cloned()
            } {
                for addr in bound_addresses {
                    let idi_addrs = self.translate_unspecified_address(addr);
                    for idi_addr in idi_addrs {
                        out.push(DialInfo::udp_from_socketaddr(idi_addr));
                    }
                }
            }
            out.sort();
            out.dedup();
            out
        };

        // Add static public dialinfo if it's configured
        if let (Some(public_address), false) = (public_address.as_ref(), require_inbound_relay) {
            // Resolve statically configured public dialinfo
            let mut public_sockaddrs = public_address
                .to_socket_addrs()
                .wrap_err(format!("Unable to resolve address: {}", public_address))?;

            // Add all resolved addresses as public dialinfo
            for pdi_addr in &mut public_sockaddrs {
                let pdi = DialInfo::udp_from_socketaddr(pdi_addr);

                // Register the public address
                editor_public_internet.add_dial_info(pdi.clone(), DialInfoClass::Direct);

                // See if this public address is also a local interface address we haven't registered yet
                if self.is_interface_address(pdi_addr.ip()) {
                    editor_local_network.add_dial_info(
                        DialInfo::udp_from_socketaddr(pdi_addr),
                        DialInfoClass::Direct,
                    );
                }
            }
        }

        // Register local dial info
        for di in &local_dial_info_list {
            // If the local interface address is global, then register global dial info
            // if no other public address is specified
            if !resolved_detect_address_changes
                && !require_inbound_relay
                && public_address.is_none()
                && di.address().is_global()
            {
                editor_public_internet.add_dial_info(di.clone(), DialInfoClass::Direct);
            }

            // Register interface dial info as well since the address is on the local interface
            editor_local_network.add_dial_info(di.clone(), DialInfoClass::Direct);
        }

        Ok(())
    }

    #[cfg_attr(feature = "instrument", instrument(level = "trace", skip_all, fields(__VEILID_LOG_KEY = self.log_key())))]
    pub(super) fn start_ws_listeners(&self) -> EyreResult<StartupDisposition> {
        veilid_log!(self trace "WS: binding protocol handlers");
        let config = self.config();
        let listen_address = config.network.protocol.ws.listen_address.clone();
        let url = config.network.protocol.ws.url.clone();
        let require_inbound_relay = config.network.privacy.require_inbound_relay;

        // Get the binding parameters from the user-specified listen address
        let bind_set = self.convert_listen_address_to_bind_set(listen_address.clone())?;

        if bind_set.search {
            veilid_log!(self info
                "WS: searching for free port starting with {} on {:?}",
                bind_set.port, bind_set.addrs
            );
        } else {
            veilid_log!(self info
                "WS: binding protocol handlers at port {} on {:?}",
                bind_set.port, bind_set.addrs
            );
        }
        if !self.start_tcp_listener(
            bind_set,
            false,
            ProtocolType::WS,
            Box::new(|r, t| Box::new(WebsocketProtocolHandler::new(r, t))),
        )? {
            return Ok(StartupDisposition::BindRetry);
        }

        {
            let mut inner = self.inner.lock();
            if url.is_some() && !inner.resolved_detect_address_changes && !require_inbound_relay {
                inner.static_public_dial_info.insert(ProtocolType::WS);
            }
        }

        Ok(StartupDisposition::Success)
    }

    #[cfg_attr(feature = "instrument", instrument(level = "trace", skip_all, fields(__VEILID_LOG_KEY = self.log_key())))]
    pub(super) fn register_ws_dial_info(
        &self,
        editor_public_internet: &mut RoutingDomainEditorPublicInternet<'_>,
        editor_local_network: &mut RoutingDomainEditorLocalNetwork<'_>,
    ) -> EyreResult<()> {
        veilid_log!(self trace "WS: registering dial info");

        let config = self.config();
        let url = config.network.protocol.ws.url.clone();
        let path = config.network.protocol.ws.path.clone();
        let resolved_detect_address_changes = self.inner.lock().resolved_detect_address_changes;
        let require_inbound_relay = config.network.privacy.require_inbound_relay;

        let mut registered_addresses: HashSet<IpAddr> = HashSet::new();

        let socket_addresses = {
            let mut out = vec![];
            if let Some(bound_addresses) = {
                let inner = self.inner.lock();
                inner
                    .bound_address_per_protocol
                    .get(&ProtocolType::WS)
                    .cloned()
            } {
                for addr in bound_addresses {
                    for idi_addr in self
                        .translate_unspecified_address(addr)
                        .into_iter()
                        .map(SocketAddress::from_socket_addr)
                    {
                        out.push(idi_addr);
                    }
                }
            }
            out.sort();
            out.dedup();
            out
        };

        // Add static public dialinfo if it's configured
        if let Some(url) = url.as_ref() {
            let mut split_url = SplitUrl::from_str(url).wrap_err("couldn't split url")?;
            if !split_url.scheme.eq_ignore_ascii_case("ws") {
                bail!("WS URL must use 'ws://' scheme");
            }
            "ws".clone_into(&mut split_url.scheme);

            // Resolve static public hostnames
            let global_socket_addrs = split_url
                .host_port(80)
                .to_socket_addrs()
                .wrap_err("failed to resolve ws url")?;

            for gsa in global_socket_addrs {
                let pdi = DialInfo::try_ws(SocketAddress::from_socket_addr(gsa), url.clone())
                    .wrap_err("try_ws failed")?;

                editor_public_internet.add_dial_info(pdi.clone(), DialInfoClass::Direct);

                // See if this public address is also a local interface address
                if !registered_addresses.contains(&gsa.ip()) && self.is_interface_address(gsa.ip())
                {
                    editor_local_network.add_dial_info(pdi, DialInfoClass::Direct);
                }

                registered_addresses.insert(gsa.ip());
            }
        }

        for socket_address in &socket_addresses {
            // Skip addresses we already did
            if registered_addresses.contains(&socket_address.ip_addr()) {
                continue;
            }
            // Build dial info request url
            let local_url = format!("ws://{}/{}", socket_address, path);
            let local_di =
                DialInfo::try_ws(*socket_address, local_url).wrap_err("try_ws failed")?;

            if !resolved_detect_address_changes
                && !require_inbound_relay
                && url.is_none()
                && local_di.address().is_global()
            {
                // Register public dial info
                editor_public_internet.add_dial_info(local_di.clone(), DialInfoClass::Direct);
            }

            // Register local dial info
            editor_local_network.add_dial_info(local_di, DialInfoClass::Direct);
        }

        Ok(())
    }

    #[cfg(feature = "enable-protocol-wss")]
    #[cfg_attr(feature = "instrument", instrument(level = "trace", skip_all, fields(__VEILID_LOG_KEY = self.log_key())))]
    pub(super) async fn start_wss_listeners(&self) -> EyreResult<StartupDisposition> {
        veilid_log!(self trace "WSS: binding protocol handlers");

        let config = self.config();
        let listen_address = config.network.protocol.wss.listen_address.clone();
        let url = config.network.protocol.wss.url.clone();
        let resolved_detect_address_changes = self.inner.lock().resolved_detect_address_changes;
        let require_inbound_relay = config.network.privacy.require_inbound_relay;

        // Get the binding parameters from the user-specified listen address
        let bind_set = self
            .convert_listen_address_to_bind_set(listen_address.clone())
            .await?;

        if bind_set.search {
            veilid_log!(self info
                "WSS: searching for free port starting with {} on {:?}",
                bind_set.port, bind_set.addrs
            );
        } else {
            veilid_log!(self info
                "WSS: binding protocol handlers at port {} on {:?}",
                bind_set.port, bind_set.addrs
            );
        }

        if !self
            .start_tcp_listener(
                bind_set,
                true,
                ProtocolType::WSS,
                Box::new(|r, t| Box::new(WebsocketProtocolHandler::new(r, t))),
            )
            .await?
        {
            return Ok(StartupDisposition::BindRetry);
        }

        {
            let mut inner = self.inner.lock();
            if url.is_some() && !resolved_detect_address_changes && !require_inbound_relay {
                inner.static_public_dial_info.insert(ProtocolType::WSS);
            }
        }

        Ok(StartupDisposition::Success)
    }

    #[cfg(feature = "enable-protocol-wss")]
    #[cfg_attr(feature = "instrument", instrument(level = "trace", skip_all, fields(__VEILID_LOG_KEY = self.log_key())))]
    pub(super) async fn register_wss_dial_info(
        &self,
        editor_public_internet: &mut RoutingDomainEditorPublicInternet<'_>,
        editor_local_network: &mut RoutingDomainEditorLocalNetwork<'_>,
    ) -> EyreResult<()> {
        veilid_log!(self trace "WSS: registering dialinfo");
        let config = self.config();
        let url = config.network.protocol.wss.url.clone();
        let _detect_address_changes = config.network.detect_address_changes;

        // NOTE: No interface dial info for WSS, as there is no way to connect to a local dialinfo via TLS
        // If the hostname is specified, it is the public dialinfo via the URL. If no hostname
        // is specified, then TLS won't validate, so no local dialinfo is possible.
        // This is not the case with unencrypted websockets, which can be specified solely by an IP address

        let mut registered_addresses: HashSet<IpAddr> = HashSet::new();

        // Add static public dialinfo if it's configured
        if let Some(url) = url.as_ref() {
            // Add static public dialinfo if it's configured
            let mut split_url = SplitUrl::from_str(url)?;
            if !split_url.scheme.eq_ignore_ascii_case("wss") {
                bail!("WSS URL must use 'wss://' scheme");
            }
            "wss".clone_into(&mut split_url.scheme);

            // Resolve static public hostnames
            let global_socket_addrs = split_url
                .host_port(443)
                .to_socket_addrs()
                .wrap_err("failed to resolve wss url")?;
            for gsa in global_socket_addrs {
                let pdi = DialInfo::try_wss(SocketAddress::from_socket_addr(gsa), url.clone())
                    .wrap_err("try_wss failed")?;

                editor_public_internet.add_dial_info(pdi.clone(), DialInfoClass::Direct);

                // See if this public address is also a local interface address
                if !registered_addresses.contains(&gsa.ip()) && self.is_interface_address(gsa.ip())
                {
                    editor_local_network.add_dial_info(pdi, DialInfoClass::Direct);
                }

                registered_addresses.insert(gsa.ip());
            }
        } else {
            bail!("WSS URL must be specified due to TLS requirements");
        }

        Ok(())
    }

    #[cfg_attr(feature = "instrument", instrument(level = "trace", skip_all, fields(__VEILID_LOG_KEY = self.log_key())))]
    pub(super) fn start_tcp_listeners(&self) -> EyreResult<StartupDisposition> {
        veilid_log!(self trace "TCP: binding protocol handlers");

        let config = self.config();
        let listen_address = config.network.protocol.tcp.listen_address.clone();
        let public_address = config.network.protocol.tcp.public_address.clone();
        let resolved_detect_address_changes = self.inner.lock().resolved_detect_address_changes;
        let require_inbound_relay = config.network.privacy.require_inbound_relay;

        // Get the binding parameters from the user-specified listen address
        let bind_set = self.convert_listen_address_to_bind_set(listen_address.clone())?;

        if bind_set.search {
            veilid_log!(self info
                "TCP: searching for free port starting with {} on {:?}",
                bind_set.port, bind_set.addrs
            );
        } else {
            veilid_log!(self info
                "TCP: binding protocol handlers at port {} on {:?}",
                bind_set.port, bind_set.addrs
            );
        }
        if !self.start_tcp_listener(
            bind_set,
            false,
            ProtocolType::TCP,
            Box::new(|c, _| Box::new(RawTcpProtocolHandler::new(c))),
        )? {
            return Ok(StartupDisposition::BindRetry);
        }

        {
            let mut inner = self.inner.lock();
            if public_address.is_some()
                && !resolved_detect_address_changes
                && !require_inbound_relay
            {
                inner.static_public_dial_info.insert(ProtocolType::TCP);
            }
        }

        Ok(StartupDisposition::Success)
    }

    #[cfg_attr(feature = "instrument", instrument(level = "trace", skip_all, fields(__VEILID_LOG_KEY = self.log_key())))]
    pub(super) fn register_tcp_dial_info(
        &self,
        editor_public_internet: &mut RoutingDomainEditorPublicInternet<'_>,
        editor_local_network: &mut RoutingDomainEditorLocalNetwork<'_>,
    ) -> EyreResult<()> {
        veilid_log!(self trace "TCP: registering dialinfo");

        let config = self.config();
        let public_address = config.network.protocol.tcp.public_address.clone();
        let resolved_detect_address_changes = self.inner.lock().resolved_detect_address_changes;
        let require_inbound_relay = config.network.privacy.require_inbound_relay;

        let mut registered_addresses: HashSet<IpAddr> = HashSet::new();

        let socket_addresses = {
            let mut out = vec![];
            if let Some(bound_addresses) = {
                let inner = self.inner.lock();
                inner
                    .bound_address_per_protocol
                    .get(&ProtocolType::TCP)
                    .cloned()
            } {
                for addr in bound_addresses {
                    for idi_addr in self
                        .translate_unspecified_address(addr)
                        .into_iter()
                        .map(SocketAddress::from_socket_addr)
                    {
                        out.push(idi_addr);
                    }
                }
            }
            out.sort();
            out.dedup();
            out
        };

        // Add static public dialinfo if it's configured
        if let (Some(public_address), false) = (public_address.as_ref(), require_inbound_relay) {
            // Resolve statically configured public dialinfo
            let mut public_sockaddrs = public_address
                .to_socket_addrs()
                .wrap_err("failed to resolve tcp address")?;

            // Add all resolved addresses as public dialinfo
            for pdi_addr in &mut public_sockaddrs {
                // Skip addresses we already did
                if registered_addresses.contains(&pdi_addr.ip()) {
                    continue;
                }
                let pdi = DialInfo::tcp_from_socketaddr(pdi_addr);

                editor_public_internet.add_dial_info(pdi.clone(), DialInfoClass::Direct);

                // See if this public address is also a local interface address
                if self.is_interface_address(pdi_addr.ip()) {
                    editor_local_network.add_dial_info(pdi, DialInfoClass::Direct);
                }
            }
        }

        for socket_address in &socket_addresses {
            let di = DialInfo::tcp(*socket_address);

            // Register global dial info if no public address is specified
            if !resolved_detect_address_changes
                && !require_inbound_relay
                && public_address.is_none()
                && di.address().is_global()
            {
                editor_public_internet.add_dial_info(di.clone(), DialInfoClass::Direct);
            }
            // Register interface dial info
            editor_local_network.add_dial_info(di.clone(), DialInfoClass::Direct);
            registered_addresses.insert(socket_address.ip_addr());
        }

        Ok(())
    }
}