aboutsummaryrefslogtreecommitdiff
path: root/src/diplonat.rs
blob: a94a6f874b3e81101cc1b86f98eb2b7161ad14ed (plain) (blame)
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
use anyhow::Result;
use tokio::try_join;

use crate::{
    config::ConfigOpts, consul_actor::ConsulActor, fw_actor::FirewallActor, igd_actor::IgdActor,
    stun_actor::StunActor,
};

pub struct Diplonat {
    consul: ConsulActor,
    firewall: FirewallActor,
    igd: Option<IgdActor>,
    stun: StunActor,
}

impl Diplonat {
    pub async fn new() -> Result<Self> {
        let rt_cfg = ConfigOpts::from_env()?;
        println!("{:#?}", rt_cfg);

        let ca = ConsulActor::new(&rt_cfg.consul, &rt_cfg.consul.node_name);

        let fw = FirewallActor::new(
            rt_cfg.firewall.ipv6_only,
            rt_cfg.firewall.refresh_time,
            &ca.rx_open_ports,
        )
        .await?;

        let ia = match rt_cfg.igd {
            Some(igdc) => Some(
                IgdActor::new(
                    igdc.private_ip,
                    igdc.refresh_time,
                    igdc.expiration_time,
                    &ca.rx_open_ports,
                )
                .await?,
            ),
            None => None,
        };

        let sa = StunActor::new(&rt_cfg.consul, &rt_cfg.stun, &rt_cfg.consul.node_name);

        let ctx = Self {
            consul: ca,
            igd: ia,
            firewall: fw,
            stun: sa,
        };

        Ok(ctx)
    }

    pub async fn listen(&mut self) -> Result<()> {
        let igd_opt = &mut self.igd;

        try_join!(
            self.consul.listen(),
            async {
                if let Some(igd) = igd_opt {
                    igd.listen().await
                } else {
                    Ok(())
                }
            },
            self.firewall.listen(),
            self.stun.listen(),
        )?;

        Ok(())
    }
}