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
use crate::errors::*;

use crate::blobs::Blob;
use crate::config::Config;
use crate::geoip::MaxmindReader;
use crate::json::LuaJsonValue;
use crate::keyring::KeyRingEntry;
use serde_json;
use std::fs;
use std::fmt::Debug;
use std::path::PathBuf;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use crate::engine::ctx::Script;
use sn0int_common::ModuleID;
use sn0int_common::metadata::{Metadata, Source};
use chrootable_https::dns::Resolver;
use crate::psl::PslReader;
use crate::paths;
use std::cmp::Ordering;
use std::path::Path;
use crate::term;
use crate::worker::{self, Event};

pub mod ctx;
pub mod isolation;
pub mod structs;


/// Data that is passed to every script
#[derive(Debug)]
pub struct Environment {
    pub verbose: u64,
    pub keyring: Vec<KeyRingEntry>,
    pub dns_config: Resolver,
    pub proxy: Option<SocketAddr>,
    pub options: HashMap<String, String>,
    pub blobs: Vec<Blob>,
    pub psl: PslReader,
    pub geoip: MaxmindReader,
    pub asn: MaxmindReader,
}

#[derive(Debug)]
pub struct Engine<'a> {
    path: PathBuf,
    modules: HashMap<String, Vec<Module>>,
    config: &'a Config
}

impl<'a> Engine<'a> {
    pub fn new(verbose_init: bool, config: &'a Config) -> Result<Engine> {
        let path = paths::module_dir()?;

        let mut engine = Engine {
            path,
            modules: HashMap::new(),
            config,
        };

        if verbose_init {
            engine.reload_modules()?;
        } else {
            engine.reload_modules_quiet()?;
        }

        Ok(engine)
    }

    pub fn reload_modules(&mut self) -> Result<usize> {
        let modules = worker::spawn_fn("Loading modules", || {
            self.reload_modules_quiet()
                .context("Failed to load modules")?;
            Ok(self.list().len())
        }, true)?;
        term::info(&format!("Loaded {} modules", modules));
        Ok(modules)
    }

    pub fn private_modules(path: &Path) -> Result<bool> {
        let metadata = fs::symlink_metadata(&path)?.file_type();
        if metadata.is_symlink() {
            debug!("Folder is a symlink, flagging modules as private");
            return Ok(true);
        }

        if path.join(".git").exists() {
            debug!("Folder is a git repo, flagging modules as private");
            return Ok(true);
        }

        Ok(false)
    }

    pub fn reload_modules_quiet(&mut self) -> Result<()> {
        self.modules = HashMap::new();

        for author in fs::read_dir(&self.path)? {
            let author = author?;
            let path = author.path();

            if !path.is_dir() {
                continue;
            }

            let private_modules = Self::private_modules(&path)?;

            let author_name = author.file_name()
                                    .into_string()
                                    .map_err(|_| format_err!("Failed to decode filename"))?;

            // skip if the namespace has an explicit path configured
            if self.config.namespaces.contains_key(&author_name) {
                continue;
            }

            self.load_module_folder(&path, &author_name, private_modules)?;
        }

        for (author, folder) in &self.config.namespaces {
            let folder = if folder.is_absolute() {
                folder.to_owned()
            } else {
                let folder = folder.strip_prefix("~/")
                    .unwrap_or(&folder);

                dirs::home_dir()
                    .ok_or_else(|| format_err!("Failed to find home folder"))?
                    .join(folder)
            };

            self.load_module_folder(&folder, &author, true)?;
        }

        Ok(())
    }

    pub fn load_module_folder(&mut self, folder: &Path, author_name: &str, private_modules: bool) -> Result<()> {
        debug!("Loading modules from {:?}", folder);

        for module in fs::read_dir(folder)? {
            let module = module?;
            let module_name = module.file_name()
                                    .into_string()
                                    .map_err(|_| format_err!("Failed to decode filename"))?;

            // find last instance of .lua in filename, if any
            let (module_name, ext) = if let Some(idx) = module_name.rfind(".lua") {
                module_name.split_at(idx)
            } else {
                // TODO: show warning
                continue;
            };

            // if .lua is not at the end, skip
            if ext != ".lua" {
                // TODO: show warning
                continue;
            }

            if let Err(err) = self.load_single_module(&module.path(), &author_name, &module_name, private_modules) {
                let root = err.find_root_cause();
                term::warn(&format!("Failed to load {}/{}: {}", author_name, module_name, root));
            }
        }

        Ok(())
    }

    pub fn load_single_module(&mut self, path: &Path, author_name: &str, module_name: &str, private_module: bool) -> Result<()> {
        let module_name = module_name.to_string();
        let module = Module::load(path, &author_name, &module_name, private_module)
            .context(format!("Failed to parse {}/{}", author_name, module_name))?;

        for key in &[&module_name, &format!("{}/{}", author_name, module_name)] {
            if !self.modules.contains_key(*key) {
                self.modules.insert(key.to_string(), Vec::new());
            }

            let vec = self.modules.get_mut(*key).unwrap();
            vec.push(module.clone());
        }

        Ok(())
    }

    pub fn get(&self, name: &str) -> Result<&Module> {
        if let Some(module) = self.get_opt(name)? {
            Ok(module)
        } else {
            bail!("Module not found")
        }
    }

    pub fn get_opt(&self, name: &str) -> Result<Option<&Module>> {
        if let Some(modules) = self.modules.get(name) {
            if modules.len() != 1 {
                bail!("Ambiguous name: {:?}", modules)
            } else {
                Ok(Some(&modules[0]))
            }
        } else {
            Ok(None)
        }
    }

    pub fn list(&self) -> Vec<&Module> {
        let mut modules: Vec<_> = self.modules.iter()
            .filter(|(key, _)| key.contains('/'))
            .flat_map(|(_, v)| v.iter())
            .collect();
        modules.sort_by(|a, b| a.cmp_canonical(b));
        modules
    }

    pub fn variants(&self) -> Vec<String> {
        self.modules.iter()
            .filter(|(_, values)| values.len() == 1)
            .map(|(key, _)| key.to_owned())
            .collect()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Module {
    name: String,
    author: String,
    description: String,
    version: String,
    source: Option<Source>,
    keyring_access: Vec<String>,
    private_module: bool,
    script: Script,
}

impl Module {
    pub fn load(path: &Path, author: &str, name: &str, private_module: bool) -> Result<Module> {
        debug!("Loading lua module {}/{} from {:?}", author, name, path);
        let code = fs::read_to_string(path)
            .context("Failed to read module")?;

        let metadata = code.parse::<Metadata>()
            .context("Failed to parse module metadata")?;

        let script = Script::load_unchecked(code)?;

        Ok(Module {
            name: name.to_string(),
            author: author.to_string(),
            description: metadata.description,
            version: metadata.version,
            source: metadata.source,
            keyring_access: metadata.keyring_access,
            private_module,
            script,
        })
    }

    #[inline]
    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn canonical(&self) -> String {
        format!("{}/{}", self.author, self.name)
    }

    #[inline]
    pub fn id(&self) -> ModuleID {
        ModuleID {
            author: self.author.to_string(),
            name: self.name.to_string(),
        }
    }

    #[inline]
    pub fn description(&self) -> &str {
        &self.description
    }

    #[inline]
    pub fn version(&self) -> &str {
        &self.version
    }

    #[inline]
    pub fn source(&self) -> &Option<Source> {
        &self.source
    }

    #[inline]
    pub fn keyring_access(&self) -> &[String] {
        &self.keyring_access
    }

    #[inline]
    pub fn is_private(&self) -> bool {
        self.private_module
    }

    pub fn run(&self, env: Environment, reporter: Arc<Mutex<Box<dyn Reporter>>>, arg: LuaJsonValue) -> Result<()> {
        debug!("Executing lua script {}", self.canonical());
        self.script.run(env, reporter, arg.into())
    }

    #[inline]
    fn cmp_canonical(&self, other: &Module) -> Ordering {
        if self.author == other.author {
            self.name.cmp(&other.name)
        } else {
            self.author.cmp(&other.author)
        }
    }

    pub fn source_equals(&self, other: &str) -> bool {
        match self.source() {
            Some(source) => source.group_as_str() == other,
            None => other == "",
        }
    }
}

pub trait Reporter: Debug {
    fn send(&mut self, event: &Event) -> Result<()>;

    fn recv(&mut self) -> Result<serde_json::Value>;
}

#[derive(Debug)]
pub struct DummyReporter;

impl DummyReporter {
    pub fn new() -> Arc<Mutex<Box<dyn Reporter>>> {
        Arc::new(Mutex::new(Box::new(DummyReporter)))
    }
}

impl Reporter for DummyReporter {
    fn send(&mut self, _event: &Event) -> Result<()> {
        Ok(())
    }

    fn recv(&mut self) -> Result<serde_json::Value> {
        unimplemented!("DummyReporter::recv doesn't exist")
    }
}