summaryrefslogtreecommitdiff
path: root/src/config.rs
blob: 065ee28da516d06e5a4e52ecf92612e071780350 (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
/*
    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::{
    certs::CertPackage,
    deser_helpers::{seq_or_not, string_or_seq},
    modules::{Node, MODULES},
};
use anyhow::{anyhow, bail, Context, Result};
use rand::random;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_yml::Value;
use std::{
    fs::read_to_string,
    net::SocketAddr,
    path::{Path, PathBuf},
    sync::Arc,
};

#[derive(Serialize, Deserialize)]
pub struct Config {
    pub http: Option<HttpConfig>,
    pub https: Option<HttpsConfig>,
    #[serde(default = "random_bytes")]
    pub private_key: [u8; 32],
    #[serde(default)]
    pub limits: Limits,
    #[serde(default)]
    pub source_ip_from_header: bool,
    pub handler: DynNodeConfig,
    #[serde(default)]
    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,
    pub max_requests_per_connnection: 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,
}

#[derive(Serialize, Deserialize)]
pub struct ConfigPackage {
    pub config: String,
    pub certificates: Vec<CertPackage>, // name, fullchain, key
}

pub type DynNode = Arc<dyn Node>;

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DynNodeConfig(serde_yml::Value);
impl DynNodeConfig {
    pub fn parse<T: DeserializeOwned>(self) -> serde_yml::Result<T> {
        serde_yml::from_value(self.0)
    }
}

pub struct InstContext {
    config: DynNodeConfig,
}
impl InstContext {
    pub fn config(&self) -> DynNodeConfig {
        self.config.clone()
    }
    pub fn instantiate_child(&self, config: DynNodeConfig) -> Result<DynNode> {
        instantiate_handler(config)
    }
}

impl Config {
    pub fn new(raw: &str) -> Result<Self> {
        Ok(serde_yml::from_str(&raw).context("parsing config YAML")?)
    }
    pub fn create_handler(&self) -> Result<DynNode> {
        instantiate_handler(self.handler.clone())
    }
}

fn instantiate_handler(config: DynNodeConfig) -> Result<DynNode> {
    let Value::Tagged(tv) = config.0 else {
        bail!("handler is not a tagged value")
    };
    let kind = tv.tag.string;
    let cons = MODULES
        .iter()
        .find(|m| m.name() == kind)
        .ok_or(anyhow!("unknown module name {kind:?}"))?;

    cons.instantiate(InstContext {
        config: DynNodeConfig(tv.value),
    })
}

impl ConfigPackage {
    pub fn new(entry: &Path) -> Result<Self> {
        let config = read_to_string(entry).context("reading main config file")?;
        let config_parsed: Config = serde_yml::from_str(&config).context("parsing config YAML")?;
        let certificates = config_parsed
            .https
            .map(|h| CertPackage::create_from_recursive(&h.cert_path))
            .transpose()?
            .unwrap_or_default();
        Ok(Self {
            config,
            certificates,
        })
    }
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            max_incoming_connections: 512,
            max_incoming_connections_h3: 4096,
            max_requests_per_connnection: 16,
            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 | WatchMask::MOVED_TO,
//             )
//             .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.name == config_path.file_name() {
//                     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:?}"),
//                     }
//                 }
//             }
//         }
//     });
// }