aboutsummaryrefslogtreecommitdiff
path: root/src/diplonat.rs
blob: 6334e5b4a72be5f6054e8ab1f91d48c0838e4bdc (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
use anyhow::{Result, anyhow};
use tokio::try_join;

use crate::config::ConfigOpts;
use crate::consul_actor::ConsulActor;
use crate::fw_actor::FirewallActor;
use crate::igd_actor::IgdActor;

pub struct Diplonat {
  consul: ConsulActor,

  firewall: Option<FirewallActor>,
  igd: Option<IgdActor>,
}

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

    let firewall_actor = FirewallActor::new(
        config.firewall,
        &consul_actor.rx_open_ports
    ).await?;
    
    let igd_actor = IgdActor::new(
      config.igd,
      &consul_actor.rx_open_ports
    ).await?;

    if firewall_actor.is_none() && igd_actor.is_none() {
      return Err(anyhow!(
        "At least enable *one* module, otherwise it's boring!"));
    }

    let ctx = Self {
      consul: consul_actor,
      firewall: firewall_actor,
      igd: igd_actor,
    };

    return Ok(ctx);
  }

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

    try_join!(
      self.consul.listen(),
      async {
        match firewall {
          Some(x) => x.listen().await,
          None => Ok(())
        }
      },
      async {
        match igd {
          Some(x) => x.listen().await,
          None => Ok(())
        }
      },
    )?;

    return Ok(());
  }
}