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
use certificate;
use dirs;
use error::Error;
use identity;
use mtdparts::parse_mtd;
use rand::thread_rng;
use rand::RngCore;
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::Seek;
use std::io::SeekFrom;
use std::io::{Read, Write};
use std::mem;
use toml;

#[derive(Deserialize, Serialize)]
pub struct AuthorizationToml {
    identity: String,
    resource: String,
}

#[derive(Deserialize, Serialize)]
pub struct PublisherConfigToml {
    shadow: String,
    secret: Option<String>,
}

#[derive(Deserialize, Serialize)]
pub struct SubscriberConfigToml {
    shadow: String,
    secret: Option<String>,
    shard:  Option<String>,
}

#[derive(Deserialize, Default, Serialize)]
pub struct ConfigToml {
    secret:    Option<String>,
    principal: Option<String>,
    keepalive: Option<u16>,
    publish:   Option<PublisherConfigToml>,
    subscribe: Option<SubscriberConfigToml>,
    authorize: Option<Vec<AuthorizationToml>>,
    names:     Option<HashMap<String, String>>,
}

impl ConfigToml {
    fn secret(o: Option<&String>) -> Result<identity::Secret, Error> {
        if let Some(ref s) = o{
            if s.starts_with(":") {
                let mut fu_brwcheck: String;
                let mut s: Vec<&str> = s.split(":").collect();


                if s.get(1) == Some(&"mtdname") || s.get(1) == Some(&"mtdblock") {
                    if let Some(name) = s.get(2).map(|v| v.to_string()) {
                        let f = File::open("/proc/mtd").expect("open /proc/mtd");
                        let names = parse_mtd(f).expect("parsing /proc/mtd");
                        let dev = names.get(&name).expect(&format!("mtd partition {} not found", name));
                        fu_brwcheck = format!("/dev/{}", dev);

                        if s.get(1) == Some(&"mtdblock") {
                            if !fu_brwcheck.contains("mtdblock") {
                                fu_brwcheck = fu_brwcheck.replace("mtd", "mtdblock");
                            }
                        }
                        s[1] = "mtd";
                        s[2] = &fu_brwcheck;
                    }
                }

                if s.get(1) == Some(&"mtd") {
                    if let Some(mtd) = s.get(2) {
                        info!("reading secret from mtd {}", mtd);
                        let offset = s.get(3).and_then(|v| v.parse().ok()).unwrap_or(40);
                        let mut f = OpenOptions::new()
                            .read(true)
                            .write(true)
                            .open(mtd)
                            .expect(&format!("cannot open {}", mtd));
                        f.seek(SeekFrom::Start(offset))?;

                        let mut b = [0u8; 32];
                        f.read_exact(&mut b)?;

                        if b == [0xff; 32] || b == [0x0; 32] {
                            f.seek(SeekFrom::Start(offset))?;
                            thread_rng().try_fill_bytes(&mut b).unwrap();
                            f.write(&b)?;
                        }
                        return Ok(identity::Secret::from_array(b));
                    }
                }

                return Err(Error::NoSecrets);
            }

            let s: identity::Secret = s.parse()?;
            return Ok(s);
        }
        Err(Error::NoSecrets)
    }

    fn publisher(&mut self, identity: identity::Identity) -> Result<Option<PublisherConfig>, Error> {
        let publish = match &self.publish {
            None => return Ok(None),
            Some(v) => v,
        };

        let shadow = publish.shadow.parse::<identity::Address>()?;

        let mut auth = certificate::Authenticator::new(identity, shadow.clone());
        if let Some(authorize) = mem::replace(&mut self.authorize, None) {
            for i in authorize {
                match i.identity.parse() {
                    Ok(identity) => {
                        auth.allow(identity, vec![i.resource]);
                    }
                    Err(e) => {
                        warn!("in config: {}", e);
                    }
                }
            }
        }

        Ok(Some(PublisherConfig { shadow, auth }))
    }

    fn subscriber(&mut self) -> Result<Option<SubscriberConfig>, Error> {
        let subscribe = match &self.subscribe {
            None => return Ok(None),
            Some(v) => v,
        };

        let shadow = subscribe.shadow.parse::<identity::Address>()?;

        Ok(Some(SubscriberConfig { shadow }))
    }

    fn names(&mut self) -> Result<HashMap<String, identity::Identity>, Error> {
        let mut r = HashMap::new();
        if let Some(names) = mem::replace(&mut self.names, None) {
            for (k, v) in names {
                r.insert(k, v.parse()?);
            }
        }
        Ok(r)
    }
}

#[derive(Clone)]
pub struct Authorization {
    pub identity: identity::Identity,
    pub path:     String,
}

#[derive(Clone)]
pub struct PublisherConfig {
    pub shadow: identity::Address,
    pub auth:   certificate::Authenticator,
}

#[derive(Debug, Clone)]
pub struct SubscriberConfig {
    pub shadow: identity::Address,
}

#[derive(Clone)]
pub struct Config {
    pub secret:    identity::Secret,
    pub principal: Option<identity::Secret>,
    pub keepalive: Option<u16>,
    pub publish:   Option<PublisherConfig>,
    pub subscribe: Option<SubscriberConfig>,
    pub names:     HashMap<String, identity::Identity>,
}

pub fn load() -> Result<Config, Error> {
    let defaultfile = dirs::home_dir()
        .unwrap_or("/root/".into())
        .join(".devguard/carrier.toml");
    let filename = env::var("CARRIER_CONFIG_FILE").map(|v| v.into()).unwrap_or(defaultfile);

    let mut buffer = String::default();
    File::open(&filename)
        .expect(&format!(
            "cannot open config file {:?}. maybe run carrier setup",
            filename
        ))
        .read_to_string(&mut buffer)
        .expect(&format!("cannot read config file {:?}", filename));
    let mut config: ConfigToml = toml::from_str(&buffer).expect(&format!(
        "cannot open config file {:?}. maybe run carrier setup",
        filename
    ));

    let secret = ConfigToml::secret(config.secret.as_ref())?;
    Ok(Config {
        publish: config.publisher(secret.identity())?,
        secret,
        principal: ConfigToml::secret(config.principal.as_ref()).ok(),
        keepalive: config.keepalive,
        subscribe: config.subscriber()?,
        names: config.names()?,
    })
}

impl Config {
    pub fn resolve_identity<S: Into<String>>(&self, s: S) -> Result<identity::Identity, Error> {
        let s = s.into();
        if let Some(v) = self.names.get(&s) {
            return Ok(v.clone());
        }
        s.parse()
    }
}

pub fn setup() -> Result<(), Error> {
    let defaultfile = dirs::home_dir()
        .unwrap_or("/root/".into())
        .join(".devguard/carrier.toml");
    let filename = env::var("CARRIER_CONFIG_FILE").map(|v| v.into()).unwrap_or(defaultfile);

    let mut config: ConfigToml = if let Ok(mut f) = File::open(&filename) {
        let mut buffer = String::default();
        f.read_to_string(&mut buffer)
            .expect(&format!("cannot read config file {:?}", filename));
        toml::from_str(&buffer).expect(&format!(
            "cannot open config file {:?}. maybe run carrier setup",
            filename
        ))
    } else {
        ConfigToml::default()
    };

    if config.secret.is_none() {
        config.secret = Some(identity::Secret::gen().to_string());
    }

    let secret: identity::Secret = config.secret.as_ref().unwrap().parse().unwrap();
    println!("identity: {}", secret.identity());

    let s = toml::to_vec(&config).unwrap();
    let mut f = File::create(&filename).expect(&format!("cannot create config file {:?}", filename));
    f.write_all(&s)
        .expect(&format!("cannot write config file {:?}", filename));

    Ok(())
}