aboutsummaryrefslogtreecommitdiffstats
path: root/src/config.rs
blob: e032da52ea913b59579c8123ac91059e38babaae (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
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
// SPDX-FileCopyrightText: 2025 Tomasz Kramkowski <tomasz@kramkow.ski>
// SPDX-License-Identifier: GPL-3.0-or-later

use std::{
    collections::HashMap, fmt, fs::File, io::Read, os::unix::fs::PermissionsExt, path::Path,
    process, time::Duration,
};

use anyhow::bail;
use rumqttc::{AsyncClient, EventLoop, MqttOptions, QoS};
use serde::{
    de::{self, Visitor},
    Deserialize, Deserializer,
};

use crate::PROGRAM;

#[derive(Deserialize, Debug)]
pub struct Credentials {
    pub username: String,
    pub password: String,
}

fn default_host() -> String {
    "localhost".to_string()
}

fn default_port() -> u16 {
    1883
}

fn default_qos() -> QoS {
    QoS::ExactlyOnce
}

fn default_id() -> String {
    PROGRAM.to_string()
}

fn default_timeout() -> Duration {
    Duration::from_secs(60)
}

#[allow(clippy::enum_variant_names)]
#[derive(Deserialize, Debug)]
#[serde(remote = "QoS", rename_all = "kebab-case")]
#[repr(u8)]
pub enum QoSDef {
    AtMostOnce = 0,
    AtLeastOnce = 1,
    ExactlyOnce = 2,
}

pub fn deserialize_qos_opt<'de, D>(deserializer: D) -> Result<Option<QoS>, D::Error>
where
    D: Deserializer<'de>,
{
    #[derive(Deserialize)]
    struct Helper(#[serde(with = "QoSDef")] QoS);

    let helper = Option::deserialize(deserializer)?;
    Ok(helper.map(|Helper(external)| external))
}

#[derive(Debug, PartialEq, Clone)]
pub struct Program {
    // TODO: Figure out a way to allow arbitrary unix paths (arbitrary
    // non-unicode) without base64
    pub command: Vec<String>,
    pub timeout: Option<Duration>,
}

impl<'de> Deserialize<'de> for Program {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct VecOrProgram;

        impl<'de> Visitor<'de> for VecOrProgram {
            type Value = Program;

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

            fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
            where
                A: serde::de::SeqAccess<'de>,
            {
                let vec: Vec<String> =
                    Deserialize::deserialize(de::value::SeqAccessDeserializer::new(seq))?;
                Ok(Program {
                    command: vec,
                    timeout: None,
                })
            }

            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
            where
                A: serde::de::MapAccess<'de>,
            {
                #[derive(Deserialize)]
                struct Helper {
                    command: Vec<String>,
                    #[serde(default, deserialize_with = "deserialize_timeout_opt")]
                    timeout: Option<Duration>,
                }

                let helper: Helper =
                    Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))?;
                Ok(Program {
                    command: helper.command,
                    timeout: helper.timeout,
                })
            }
        }

        deserializer.deserialize_any(VecOrProgram)
    }
}

#[derive(Debug)]
pub struct Route {
    pub programs: Vec<Program>,
    pub qos: Option<QoS>,
}

impl<'de> Deserialize<'de> for Route {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct VecOrRoute;

        impl<'de> Visitor<'de> for VecOrRoute {
            type Value = Route;

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

            fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
            where
                A: serde::de::SeqAccess<'de>,
            {
                let vec: Vec<Program> =
                    Deserialize::deserialize(de::value::SeqAccessDeserializer::new(seq))?;
                Ok(Route {
                    programs: vec,
                    qos: None,
                })
            }

            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
            where
                A: serde::de::MapAccess<'de>,
            {
                #[derive(Deserialize)]
                struct RouteHelper {
                    programs: Vec<Program>,
                    #[serde(default, deserialize_with = "deserialize_qos_opt")]
                    qos: Option<QoS>,
                }

                let helper: RouteHelper =
                    Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))?;
                Ok(Route {
                    programs: helper.programs,
                    qos: helper.qos,
                })
            }
        }

        deserializer.deserialize_any(VecOrRoute)
    }
}

pub fn deserialize_timeout<'de, D>(deserializer: D) -> Result<Duration, D::Error>
where
    D: Deserializer<'de>,
{
    struct DurationVisitor;

    impl<'de> de::Visitor<'de> for DurationVisitor {
        type Value = Duration;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a positive number")
        }

        fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            if v < 0 {
                return Err(de::Error::invalid_value(
                    de::Unexpected::Signed(v),
                    &"a non-negative number",
                ));
            }
            if v == 0 {
                Ok(Duration::MAX)
            } else {
                Ok(Duration::from_secs(v as u64))
            }
        }

        fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            if v < 0.0 {
                return Err(de::Error::invalid_value(
                    de::Unexpected::Float(v),
                    &"a non-negative number",
                ));
            }
            if v == 0.0 {
                Ok(Duration::MAX)
            } else {
                Ok(Duration::from_secs_f64(v))
            }
        }
    }

    deserializer.deserialize_any(DurationVisitor)
}

pub fn deserialize_timeout_opt<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
where
    D: Deserializer<'de>,
{
    #[derive(Deserialize)]
    struct Helper(#[serde(deserialize_with = "deserialize_timeout")] Duration);

    let helper = Option::deserialize(deserializer)?;
    Ok(helper.map(|Helper(external)| external))
}

#[derive(Deserialize, Debug)]
pub struct Config {
    #[serde(default = "default_host")]
    pub host: String,
    #[serde(default = "default_port")]
    pub port: u16,
    #[serde(with = "QoSDef", default = "default_qos")]
    pub qos: QoS,
    #[serde(default = "default_timeout", deserialize_with = "deserialize_timeout")]
    pub timeout: Duration,
    pub credentials: Option<Credentials>,
    #[serde(default = "default_id")]
    pub id: String,
    pub routes: HashMap<String, Route>,
}

impl Config {
    pub fn mqtt_client(&self) -> (AsyncClient, EventLoop) {
        let client_id = format!("{}_{}", self.id, process::id());
        let mut options = MqttOptions::new(client_id, &self.host, self.port);
        if let Some(credentials) = &self.credentials {
            options.set_credentials(&credentials.username, &credentials.password);
        }
        // TODO: Make configurable
        options.set_keep_alive(Duration::from_secs(5));
        options.set_max_packet_size(10 * 1024 * 1024, 10 * 1024 * 1024);
        AsyncClient::new(options, 10)
    }
}

pub fn load<P: AsRef<Path>>(path: P) -> anyhow::Result<Config> {
    let mut f = File::open(path)?;
    let mut config = String::new();
    f.read_to_string(&mut config)?;
    let config: Config = toml::from_str(&config)?;
    if config.credentials.is_some() {
        let mode = f.metadata()?.permissions().mode();
        if mode & 0o044 != 0o000 {
            bail!("Config file contains credentials while being group or world readable.");
        }
    }
    Ok(config)
}

#[cfg(test)]
mod tests {
    use super::*;
    use rumqttc::QoS;
    use std::time::Duration;

    impl Program {
        fn new(command: Vec<&str>) -> Self {
            Program {
                command: command.into_iter().map(str::to_string).collect(),
                timeout: None,
            }
        }

        fn new_with_timeout(command: Vec<&str>, timeout: Duration) -> Self {
            Program {
                command: command.into_iter().map(str::to_string).collect(),
                timeout: Some(timeout),
            }
        }
    }

    #[test]
    fn load_full_config() {
        let toml_str = r#"
            host = "foo.bar.baz"
            port = 1234
            qos = "at-most-once"
            id = "custom-id"
            timeout = 15.5

            [credentials]
            username = "testuser"
            password = "testpassword"

            [routes]
            "topic/map" = { programs = [
                    ["/bin/program1"],
                    ["/bin/program2", "arg"],
                    { command = ["/bin/program3", "arg"]},
                ], qos = "exactly-once" }
            "topic/seq" = [
                ["/bin/program4", "arg"],
                { command = ["/bin/program5"], timeout = 1.2 },
            ]
        "#;

        let config: Config = toml::from_str(toml_str).expect("Failed to parse full config");

        assert_eq!(config.host, "foo.bar.baz");
        assert_eq!(config.port, 1234);
        assert_eq!(config.qos, QoS::AtMostOnce);
        assert_eq!(config.id, "custom-id");
        assert_eq!(config.timeout, Duration::from_secs_f64(15.5));

        let creds = config.credentials.expect("Credentials should be present");
        assert_eq!(creds.username, "testuser");
        assert_eq!(creds.password, "testpassword");

        assert_eq!(config.routes.len(), 2);

        let route_map = config.routes.get("topic/map").unwrap();
        assert_eq!(
            route_map.programs,
            vec![
                Program::new(vec!["/bin/program1"]),
                Program::new(vec!["/bin/program2", "arg"]),
                Program::new(vec!["/bin/program3", "arg"]),
            ]
        );
        assert_eq!(route_map.qos, Some(QoS::ExactlyOnce));

        let route_seq = config.routes.get("topic/seq").unwrap();
        assert_eq!(
            route_seq.programs,
            vec![
                Program::new(vec!["/bin/program4", "arg"]),
                Program::new_with_timeout(vec!["/bin/program5"], Duration::from_secs_f64(1.2)),
            ]
        );
        assert_eq!(route_seq.qos, None);
    }

    #[test]
    fn load_minimal_config() {
        let config: Config = toml::from_str("[routes]").expect("Failed to parse minimal config");

        assert_eq!(config.host, default_host());
        assert_eq!(config.port, default_port());
        assert_eq!(config.qos, default_qos());
        assert_eq!(config.id, default_id());
        assert_eq!(config.timeout, default_timeout());
        assert!(config.credentials.is_none());
        assert!(config.routes.is_empty());
    }

    #[test]
    fn load_route_seq() {
        let toml_str = r#"
            [routes]
            "some/topic" = [["/foo/bar"], ["/baz/qux", "arg"]]
        "#;

        let config: Config = toml::from_str(toml_str).unwrap();
        let route = config.routes.get("some/topic").unwrap();

        assert_eq!(
            route.programs,
            vec![
                Program::new(vec!["/foo/bar"]),
                Program::new(vec!["/baz/qux", "arg"])
            ]
        );
        assert_eq!(route.qos, None);
    }

    #[test]
    fn load_route_map() {
        let toml_str = r#"
            [routes]
            "topic/with_qos" = { programs = [["/foo/bar", "arg"]], qos = "at-least-once" }
            "topic/without_qos" = { programs = [["/baz/qux"]] }
        "#;

        let config: Config = toml::from_str(toml_str).unwrap();

        let route_with_qos = config.routes.get("topic/with_qos").unwrap();
        assert_eq!(
            route_with_qos.programs,
            vec![Program::new(vec!["/foo/bar", "arg"])]
        );
        assert_eq!(route_with_qos.qos, Some(QoS::AtLeastOnce));

        let route_without_qos = config.routes.get("topic/without_qos").unwrap();
        assert_eq!(
            route_without_qos.programs,
            vec![Program::new(vec!["/baz/qux"])]
        );
        assert_eq!(route_without_qos.qos, None);
    }

    #[test]
    fn load_timeout() {
        let config_int: Config = toml::from_str("timeout = 10\n[routes]").unwrap();
        assert_eq!(config_int.timeout, Duration::from_secs(10));

        let config_float: Config = toml::from_str("timeout = 2.5\n[routes]").unwrap();
        assert_eq!(config_float.timeout, Duration::from_secs_f64(2.5));

        let config_zero: Config = toml::from_str("timeout = 0\n[routes]").unwrap();
        assert_eq!(config_zero.timeout, Duration::MAX);

        let config_zero: Config = toml::from_str("timeout = 0.0\n[routes]").unwrap();
        assert_eq!(config_zero.timeout, Duration::MAX);
    }

    #[test]
    fn load_timeout_negative() {
        let result = toml::from_str::<Config>("timeout = -10\n[routes]");
        assert!(result.is_err());

        let result = toml::from_str::<Config>("timeout = -1.0\n[routes]");
        assert!(result.is_err());
    }

    #[test]
    fn load_qos() {
        let toml_str = r#"
            [routes]
            "at-most-once" = { programs = [], qos = "at-most-once" }
            "at-least-once" = { programs = [], qos = "at-least-once" }
            "exactly-once" = { programs = [], qos = "exactly-once" }
        "#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(
            config.routes.get("at-most-once").unwrap().qos.unwrap(),
            QoS::AtMostOnce
        );
        assert_eq!(
            config.routes.get("at-least-once").unwrap().qos.unwrap(),
            QoS::AtLeastOnce
        );
        assert_eq!(
            config.routes.get("exactly-once").unwrap().qos.unwrap(),
            QoS::ExactlyOnce
        );
    }
}