aboutsummaryrefslogtreecommitdiff
path: root/src/config.rs
blob: 8eb7d8d238bd53c5c5e163a96e93c806e73e9bec (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
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
/*
    This file is part of gnix (https://codeberg.org/metamuffin/gnix)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2025 metamuffin <metamuffin.org>
*/
use crate::{
    modules::{Node, NodeKind},
    State,
};
use anyhow::Context;
use inotify::{EventMask, Inotify, WatchMask};
use log::{error, info};
use rand::random;
use serde::{
    de::{value, Error, SeqAccess, Visitor},
    Deserialize, Deserializer, Serialize,
};
use serde_yml::value::TaggedValue;
use std::{
    collections::BTreeMap,
    fmt,
    fs::read_to_string,
    marker::PhantomData,
    net::SocketAddr,
    ops::Deref,
    path::{Path, PathBuf},
    sync::{Arc, RwLock},
};

#[derive(Deserialize)]
pub struct Config {
    #[serde(default = "return_true")]
    pub watch_config: bool,
    pub http: Option<HttpConfig>,
    pub https: Option<HttpsConfig>,
    #[serde(default = "random_bytes")]
    pub private_key: [u8; 32],
    #[serde(default)]
    pub limits: Limits,
    pub handler: DynNode,
    #[serde(default = "return_true")]
    pub disable_server_header: bool
}

fn random_bytes() -> [u8; 32] {
    [(); 32].map(|_| random())
}
pub fn return_true() -> bool {
    true
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct Limits {
    pub max_incoming_connections: usize,
    pub max_outgoing_connections: usize,
    pub max_incoming_connections_h3: usize,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct HttpConfig {
    #[serde(deserialize_with = "string_or_seq")]
    pub bind: Vec<SocketAddr>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct HttpsConfig {
    #[serde(deserialize_with = "string_or_seq")]
    pub bind: Vec<SocketAddr>,
    #[serde(deserialize_with = "seq_or_not")]
    pub cert_path: Vec<PathBuf>,
    pub cert_fallback: Option<PathBuf>,
    #[serde(default)]
    pub disable_h3: bool,
    #[serde(default)]
    pub disable_h2: bool,
    #[serde(default)]
    pub disable_h1: bool,
}

// try deser Vec<T> but fall back to deser T and putting that in Vec
pub fn seq_or_not<'de, D, V: Deserialize<'de>>(des: D) -> Result<Vec<V>, D::Error>
where
    D: Deserializer<'de>,
{
    struct SeqOrNot<V>(PhantomData<V>);
    impl<'de, V: Deserialize<'de>> Visitor<'de> for SeqOrNot<V> {
        type Value = Vec<V>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a sequence or not a sequence")
        }
        fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
        where
            A: serde::de::EnumAccess<'de>,
        {
            Ok(vec![V::deserialize(value::EnumAccessDeserializer::new(
                data,
            ))?])
        }
        fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
        where
            A: serde::de::MapAccess<'de>,
        {
            Ok(vec![V::deserialize(value::MapAccessDeserializer::new(
                map,
            ))?])
        }
        fn visit_str<E>(self, val: &str) -> Result<Vec<V>, E>
        where
            E: Error,
        {
            Ok(vec![V::deserialize(value::StrDeserializer::new(val))?])
        }

        fn visit_seq<A>(self, val: A) -> Result<Vec<V>, A::Error>
        where
            A: SeqAccess<'de>,
        {
            Vec::<V>::deserialize(value::SeqAccessDeserializer::new(val))
        }
    }
    des.deserialize_any(SeqOrNot::<V>(PhantomData))
}

// fall back to expecting a single string and putting that in a 1-length vector
fn string_or_seq<'de, D>(des: D) -> Result<Vec<SocketAddr>, D::Error>
where
    D: Deserializer<'de>,
{
    struct StringOrList;
    impl<'de> Visitor<'de> for StringOrList {
        type Value = Vec<SocketAddr>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("sequence or list")
        }

        fn visit_str<E>(self, val: &str) -> Result<Vec<SocketAddr>, E>
        where
            E: Error,
        {
            let addr = SocketAddr::deserialize(value::StrDeserializer::new(val))?;
            Ok(vec![addr])
        }

        fn visit_seq<A>(self, val: A) -> Result<Vec<SocketAddr>, A::Error>
        where
            A: SeqAccess<'de>,
        {
            Vec::<SocketAddr>::deserialize(value::SeqAccessDeserializer::new(val))
        }
    }

    des.deserialize_any(StringOrList)
}

pub static NODE_KINDS: RwLock<BTreeMap<String, &'static dyn NodeKind>> =
    RwLock::new(BTreeMap::new());

#[derive(Clone)]
pub struct DynNode(Arc<dyn Node>);

impl<'de> Deserialize<'de> for DynNode {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let tv = TaggedValue::deserialize(deserializer)?;
        let s = tv.tag.to_string();
        let s = s.strip_prefix("!").unwrap_or(s.as_str());
        let inst = NODE_KINDS
            .read()
            .unwrap()
            .get(s)
            .ok_or(serde::de::Error::unknown_variant(s, &[]))?
            .instanciate(tv.value)
            .map_err(|e| {
                let x = format!("instanciating module {s:?}: {e:?}");
                serde::de::Error::custom(e.context(x))
            })?;

        Ok(Self(inst))
    }
}
impl Deref for DynNode {
    type Target = dyn Node;
    fn deref(&self) -> &Self::Target {
        self.0.as_ref()
    }
}

impl Config {
    pub fn load(path: &Path) -> anyhow::Result<Config> {
        info!("loading config from {path:?}");
        let raw = read_to_string(path).context("reading config file")?;
        let config: Config = serde_yml::from_str(&raw).context("during parsing")?;
        Ok(config)
    }
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            max_incoming_connections: 512,
            max_incoming_connections_h3: 4096,
            max_outgoing_connections: 256,
        }
    }
}

pub fn setup_file_watch(config_path: PathBuf, state: Arc<State>) {
    std::thread::spawn(move || {
        let mut inotify = Inotify::init().unwrap();
        inotify
            .watches()
            .add(
                config_path.parent().unwrap(),
                WatchMask::MODIFY | WatchMask::CREATE | WatchMask::DELETE,
            )
            .unwrap();
        let mut buffer = [0u8; 4096];
        loop {
            let events = inotify
                .read_events_blocking(&mut buffer)
                .expect("Failed to read inotify events");

            for event in events {
                if event.mask.contains(EventMask::MODIFY) {
                    if config_path.metadata().map(|m| m.len()).unwrap_or_default() == 0 {
                        continue;
                    }
                    match Config::load(&config_path) {
                        Ok(conf) => {
                            let mut r = state.config.blocking_write();
                            *r = Arc::new(conf)
                        }
                        Err(e) => error!("config has errors: {e:?}"),
                    }
                }
            }
        }
    });
}