aboutsummaryrefslogtreecommitdiffstats
path: root/src/config.rs
blob: c6306bc3a9273659bff89d20f5f847527dddfa5b (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
// 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)]
pub struct Route {
    // TODO: Figure out a way to allow arbitrary unix paths (arbitrary
    // non-unicode) without base64
    pub programs: Vec<Vec<String>>,
    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<Vec<String>> =
                    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<Vec<String>>,
                    #[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)
}

#[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)
}