summaryrefslogtreecommitdiff
path: root/src/router/router.rs
blob: 3f1e629a72aac2ec617bf21d1f8e3bab76a437d9 (plain)
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
use emissary_core::router::Router;
use emissary_core::{Config, Ntcp2Config, SamConfig, TransitConfig};
use emissary_util::reseeder::Reseeder;
use emissary_util::runtime::tokio::Runtime as TokioRuntime;
use emissary_util::storage::{Storage, StorageBundle};
use serde::{Deserialize, Serialize};

use std::future::Future;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::Mutex;

lazy_static::lazy_static! {
    pub static ref ROUTER: Arc<Mutex<Option<Router<TokioRuntime>>>> = Arc::new(Mutex::new(None));
}

pub trait RouterUtils {
    fn config(&mut self) -> impl Future<Output = Result<(), Box<dyn std::error::Error>>> + Send;
    fn reseed(&mut self) -> impl Future<Output = Result<(), Box<dyn std::error::Error>>> + Send;
    fn start(
        self,
    ) -> impl Future<Output = Result<Router<TokioRuntime>, Box<dyn std::error::Error>>> + Send;
}

#[derive(Debug, Deserialize, Serialize)]
pub struct EmissaryConfig {
    pub storage: Option<PathBuf>,
    pub auto_update: Option<bool>,
    pub http_proxy_port: Option<u16>,
    pub socks_proxy_port: Option<u16>,
}

pub struct Emissary {
    config: EmissaryConfig,
    storage: Option<Storage>,
    storage_bundle: Option<StorageBundle>,
}

impl Emissary {
    pub fn new(config: EmissaryConfig) -> Self {
        Self {
            config,
            storage: None,
            storage_bundle: None,
        }
    }

    fn ensure_configured(&self) -> Result<(), Box<dyn std::error::Error>> {
        if self.storage.is_none() || self.storage_bundle.is_none() {
            Err("Router not configured. Call `config()` first.".into())
        } else {
            Ok(())
        }
    }
}

impl RouterUtils for Emissary {
    async fn config(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        if self.config.storage.is_none() {
            self.config.storage = Some(PathBuf::from("/var/lib/mesk/router/"));
        }
        if self.config.auto_update.is_none() {
            self.config.auto_update = Some(true);
        }
        if self.config.http_proxy_port.is_none() {
            self.config.http_proxy_port = Some(4445);
        }
        if self.config.socks_proxy_port.is_none() {
            self.config.socks_proxy_port = Some(4446);
        }

        let storage = Storage::new(Some(self.config.storage.clone().unwrap())).await?;
        let bundle = storage.load().await;

        self.storage = Some(storage);
        self.storage_bundle = Some(bundle);

        Ok(())
    }

    async fn reseed(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        self.ensure_configured()?;

        let storage = self.storage.as_ref().unwrap();
        let mut bundle = self.storage_bundle.take().unwrap();

        if bundle.routers.is_empty() {
            match Reseeder::reseed(None, false).await {
                Ok(reseed_routers) => {
                    for info in reseed_routers {
                        if let Err(e) = storage
                            .store_router_info(info.name.to_string(), info.router_info.clone())
                            .await
                        {
                            println!("Failed to store reseeded router info: {}", e);
                        }
                        bundle.routers.push(info.router_info);
                    }
                }
                Err(e) => {
                    if bundle.routers.is_empty() {
                        self.storage_bundle = Some(bundle);
                        return Err(format!("Reseed failed and no routers available: {}", e).into());
                    } else {
                        println!("Reseed failed, but using existing routers: {}", e);
                    }
                }
            }
        }

        self.storage_bundle = Some(bundle);
        Ok(())
    }

    async fn start(self) -> Result<Router<TokioRuntime>, Box<dyn std::error::Error>> {
        let storage = self.storage.unwrap();
        let bundle = self.storage_bundle.unwrap();

        let config = Config {
            ntcp2: Some(Ntcp2Config {
                port: 25515,
                key: bundle.ntcp2_key,
                iv: bundle.ntcp2_iv,
                publish: true,
                host: None,
            }),
            samv3_config: Some(SamConfig {
                tcp_port: self.config.http_proxy_port.unwrap_or(4445),
                udp_port: self.config.socks_proxy_port.unwrap_or(4446),
                host: "127.0.0.1".to_string(),
            }),
            routers: bundle.routers,
            profiles: bundle.profiles,
            router_info: bundle.router_info,
            static_key: Some(bundle.static_key),
            signing_key: Some(bundle.signing_key),
            transit: Some(TransitConfig {
                max_tunnels: Some(1000),
            }),
            ..Default::default()
        };

        let (router, _events, router_info) = Router::<TokioRuntime>::new(
            config,
            None, // AddressBook
            Some(Arc::new(storage.clone())),
        )
        .await
        .map_err(|e| format!("Router creation failed: {}", e))?;

        storage.store_local_router_info(router_info).await?;

        Ok(router)
    }
}