~zethra/stargazer

ref: 0d90acda5b1c79a14699af75a40a4675040f567c stargazer/src/config.rs -rw-r--r-- 13.1 KiB
0d90acda — Ben Aaron Goldberg docs: update changelog 3 months ago
                                                                                
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// stargazer - A Gemini Server
// Copyright (C) 2021 Ben Aaron Goldberg <ben@benaaron.dev>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use crate::router::{
    CGIRoute, RedirectRoute, Route, RoutePath, SCGIAddress, SCGIRoute,
    StaticRoute,
};
use anyhow::{bail, Context, Result};
use ini::{Ini, Properties};
use log::warn;
use std::fs;
use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use users::get_user_by_name;

#[derive(Debug, Clone)]
/// Program configuration
pub struct Config {
    /// Interfaces to listen on
    pub listen: Vec<SocketAddr>,
    /// Where to store certs
    pub store: PathBuf,
    /// Routes to server (only domains for now)
    pub routes: Vec<Route>,
    /// Number of worker threads (defaults to num cpus)
    pub worker_threads: usize,
    /// Max time to read a request (0 to disable)
    pub request_timeout: u64,
    /// Max time from start of request to end of response (0 to disable)
    pub response_timeout: u64,
    /// Cert organization name
    pub organization: String,
    /// Logging connections and other info to stdout
    pub conn_logging: bool,
}

pub fn load(config_path: impl AsRef<Path>) -> Result<Config> {
    let res: Result<Config> = (|| {
        let config_path = config_path.as_ref();
        let mut conf = Ini::load_from_file_noescape(&config_path)?;

        let general = conf.general_section_mut();
        let listen = general
            .remove("listen")
            .context("Missing key `listen`")?
            .split(' ')
            .map(parse_interface)
            .collect::<Result<Vec<_>>>()?;
        if listen.is_empty() {
            bail!("At least 1 value must be in the `listen` array");
        }
        let worker_threads = match general.remove("worker-threads") {
            Some(s) => s.parse().context(
                "Value given for `worker-threads` isn't a valid number",
            )?,
            None => num_cpus::get(),
        };
        if worker_threads == 0 {
            bail!("Value of `worker-threads` must be > 0");
        }
        let request_timeout = match general.remove("request-timeout") {
            Some(s) => s.parse().context(
                "Value given for `request-timeout` isn't a valid number",
            )?,
            None => 5,
        };
        let response_timeout = match general.remove("response-timeout") {
            Some(s) => s.parse().context(
                "Value given for `response-timeout` isn't a valid number",
            )?,
            None => 0,
        };
        let conn_logging = general
            .remove("connection-logging")
            .map(|s| match s.to_lowercase().as_str() {
                "on" | "true" | "yes" => true,
                "off" | "false" | "no" => false,
                s => {
                    warn!("Invalid value for `connection-logging`: '{}'. Turing on", s);
                    true
                }
            })
            .unwrap_or(true);
        check_section_empty("general", &general)?;

        let tls_section = conf
            .section_mut(Some(":tls"))
            .context("Missing key `:tls`")?;
        let store = Path::new(
            &tls_section
                .remove("store")
                .context("Missing key `store` in `:tls`")?,
        )
        .to_owned();
        if !store.exists() {
            fs::create_dir_all(&store).context(
                "`store` directory doesn't exist and couldn't be created",
            )?;
        }
        let organization = tls_section
            .remove("organization")
            .unwrap_or_else(|| "stargazer".to_owned());
        check_section_empty(":tls", &tls_section)?;

        let mut sites = Vec::with_capacity(5);

        for (section, props) in conf.iter_mut() {
            let section = match section {
                Some(section) => section,
                None => continue,
            };
            if section == ":tls" {
                continue;
            }
            let (domain, route) =
                if let Some((domain, route)) = split_once(section, ':') {
                    (domain.to_owned(), RoutePath::Prefix(route.to_owned()))
                } else if let Some((domain, route)) = split_once(section, '=') {
                    (domain.to_owned(), RoutePath::Exact(route.to_owned()))
                } else if let Some((domain, route)) = split_once(section, '~') {
                    (
                        domain.to_owned(),
                        RoutePath::Regex(Box::new(
                            regex::Regex::new(route).with_context(|| {
                                format!("Invalid regex `{}`", route)
                            })?,
                        )),
                    )
                } else {
                    (section.to_owned(), RoutePath::All)
                };
            let scgi = props.remove_yn("scgi");
            let cgi = props.remove_yn("cgi");
            let redirect = props.remove("redirect");
            if count_true(&[scgi, cgi, redirect.is_some()]) > 1 {
                bail!("Route {} has more than on of `cgi`, `scgi`, or `redirect` set", section);
            }

            let cgi_user = match props.remove("cgi-user") {
                Some(name) => {
                    Some(get_user_by_name(&name).with_context(|| {
                        format!("Invalid user name for `cgi-user`: `{}`", name)
                    })?)
                }
                None => None,
            };
            let cgi_timeout = match props.remove("cgi-timeout") {
                Some(s) => Some(s.parse().with_context(|| {
                    "Value for `cgi-timeout` in invalid, must be an integer"
                })?),
                None => None,
            };

            let route_type = if scgi {
                let scgi_addr = props.remove("scgi-address").context(
                    "Routes with `scgi` on must include an `scg-address`",
                )?;
                let mut is_sock = false;
                let mut addr = None;
                if let Ok(mut sock_addr) = scgi_addr.to_socket_addrs() {
                    if let Some(sock_addr) = sock_addr.next() {
                        is_sock = true;
                        addr = Some(SCGIAddress::Tcp(sock_addr));
                    }
                }
                if !is_sock {
                    addr = Some(SCGIAddress::Unix(
                        Path::new(&scgi_addr).to_owned(),
                    ));
                }
                SCGIRoute {
                    addr: addr.unwrap(),
                    timeout: cgi_timeout,
                }
                .into()
            } else if redirect.is_some() {
                let permanent = props.remove_yn("permanent");
                RedirectRoute {
                    url: redirect.unwrap(),
                    permanent,
                }
                .into()
            } else {
                let root =
                    Path::new(&props.remove("root").with_context(|| {
                        format!(
                            "site configs need to have a root. `{}` does not",
                            section
                        )
                    })?)
                    .to_owned();
                if !root.exists() {
                    bail!(
                        "`root` directory for site `{}` doesn't exist",
                        section
                    );
                }
                let index = props
                    .remove("index")
                    .unwrap_or_else(|| "index.gmi".to_owned())
                    .to_owned();
                if index.contains('/') {
                    bail!("`index` in config cannot contain '/'");
                }
                let auto_index = props.remove_yn("auto-index");
                if cgi {
                    if auto_index {
                        bail!("Routes with `cgi` on cannot use `auto-index`");
                    }
                    CGIRoute {
                        root,
                        index,
                        user: cgi_user,
                        timeout: cgi_timeout,
                    }
                    .into()
                } else {
                    StaticRoute {
                        root,
                        index,
                        auto_index,
                    }
                    .into()
                }
            };

            sites.push(Route {
                domain,
                path: route,
                rewrite: props.remove("rewrite"),
                route_type,
                lang: props.remove("lang"),
                charset: props.remove("charset"),
            });
            check_section_empty(section, props)?;
        }

        // Reverse order so site is checked first
        sites.reverse();
        if sites.is_empty() {
            bail!("At least one route must be specified in config file. Please \
                  refer to stargazer.ini(5) for details");
        }

        Ok(Config {
            listen,
            store,
            conn_logging,
            routes: sites,
            worker_threads,
            request_timeout,
            response_timeout,
            organization,
        })
    })();
    res.with_context(|| {
        format!(
            "Error loading config file: {}",
            config_path.as_ref().display()
        )
    })
}

pub fn dev_config() -> Result<Config> {
    let root =
        std::env::current_dir().context("Couldn't access current directory")?;
    if !root.exists() {
        bail!("Current directory doesn't exist");
    }
    let conf = Config {
        listen: vec![SocketAddr::from(([127, 0, 0, 1], 1965))],
        store: dirs::data_dir()
            .context("Cannot locate user data directory")?
            .join("stargazer-dev-store"),
        routes: vec![Route {
            domain: "localhost".to_owned(),
            path: RoutePath::All,
            rewrite: None,
            lang: None,
            charset: None,
            route_type: StaticRoute {
                root,
                index: "index.gmi".to_owned(),
                auto_index: true,
            }
            .into(),
        }],
        worker_threads: num_cpus::get(),
        request_timeout: 5,
        response_timeout: 10,
        organization: "stargazer".to_owned(),
        conn_logging: false,
    };
    fs::create_dir_all(&conf.store).with_context(|| {
        format!(
            "Error creating dev store directory at {}",
            conf.store.display()
        )
    })?;
    Ok(conf)
}

fn parse_interface(s: &str) -> Result<SocketAddr> {
    Ok(if s.contains(':') {
        if s.starts_with('[') && s.ends_with(']') {
            let addr = &s[1..s.len() - 1];
            let ip = IpAddr::from_str(addr).with_context(|| {
                format!("Error parsing IP address `{}`", addr)
            })?;
            SocketAddr::new(ip, 1965)
        } else {
            s.to_socket_addrs()
                .with_context(|| format!("Error parsing socket address {}", s))?
                .next()
                .with_context(|| {
                    format!("Error parsing socket address {}", s)
                })?
        }
    } else {
        let ip = IpAddr::from_str(s)
            .with_context(|| format!("Error parsing IP address `{}`", s))?;
        SocketAddr::new(ip, 1965)
    })
}

// STABLE Replace with std::str::split_once when stable
#[inline]
fn split_once(s: &str, delimiter: char) -> Option<(&str, &str)> {
    let idx = s.find(delimiter)?;
    Some((&s[..idx], &s[(idx + 1)..]))
}
fn check_section_empty(name: &str, section: &Properties) -> Result<()> {
    if !section.is_empty() {
        let extra: String = section
            .iter()
            .map(|(k, v)| format!("{}={}\n", k, v))
            .collect();
        bail!(
            "Section `{}` contains parameters that are either not allowed for this route type or is unknown:\n{}",
            name,
            extra
        );
    }
    Ok(())
}

trait RemoveYN {
    fn remove_yn(self, name: &str) -> bool;
}

impl RemoveYN for &mut Properties {
    fn remove_yn(self, name: &str) -> bool {
        self.remove(name)
            .map(|s| match s.to_lowercase().as_str() {
                "on" | "true" | "yes" => true,
                "off" | "false" | "no" => false,
                s => {
                    warn!("Invalid value for `{}`: '{}'. Turing off", name, s);
                    false
                }
            })
            .unwrap_or(false)
    }
}

fn count_true(bools: &[bool]) -> usize {
    let mut count = 0;
    for b in bools {
        if *b {
            count += 1;
        }
    }
    count
}