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
extern crate regex;

use std::process::{Command, ChildStdout, Stdio};
use std::io;
use std::io::{BufReader};
use std::io::prelude::*;
use regex::Regex;

pub struct Scan {
    pid: Option<u32>,
    queue: Vec<Option<String>>,
    out: BufReader<ChildStdout>,
}

impl Scan {
    pub fn stop(&mut self) {
        if let Some(pid) = self.pid.take() {
            // Brute force kill our child.
            Command::new("kill").arg("-TERM").arg(&format!("{}", pid)).output().unwrap();
        }
    }
}

#[derive(Debug, Eq, PartialEq, Clone)]
pub struct Discovery {
    _name: String,
    _mac: Mac,
}

impl Discovery {
    pub fn name(&self) -> &str {
        &self._name
    }

    pub fn mac(&self) -> &Mac {
        &self._mac
    }
}

#[derive(Debug, Eq, PartialEq, Clone)]
pub struct Mac([u8; 6]);


impl Iterator for Scan {
    type Item = Discovery;

    fn next(&mut self) -> Option<Discovery> {
        loop {
            let s = match self.queue.pop() {
                Some(Some(s)) => s,
                _ => {
                    let mut s = String::new();
                    match self.out.read_line(&mut s) {
                        Ok(len) => {
                            if len == 0 {
                                return None;
                            }
                            s
                        }
                        Err(_) => return None,
                    }
                }
            };

            let re = Regex::new(r#"(?m)^([A-F0-9]{2}):([A-F0-9]{2}):([A-F0-9]{2}):([A-F0-9]{2}):([A-F0-9]{2}):([A-F0-9]{2})\s*(.*?)[\r\n]*$"#).unwrap();
            if let Some(cap) = re.captures(&s) {
                return Some(Discovery {
                    _name: cap.at(7).unwrap().to_string(),
                    _mac: Mac([
                        u8::from_str_radix(cap.at(1).unwrap(), 16).unwrap(),
                        u8::from_str_radix(cap.at(2).unwrap(), 16).unwrap(),
                        u8::from_str_radix(cap.at(3).unwrap(), 16).unwrap(),
                        u8::from_str_radix(cap.at(4).unwrap(), 16).unwrap(),
                        u8::from_str_radix(cap.at(5).unwrap(), 16).unwrap(),
                        u8::from_str_radix(cap.at(6).unwrap(), 16).unwrap(),
                    ]),
                });
            }
        }
    }
}

pub fn scan() -> io::Result<Scan> {
    // hcitool requires a TTY, so fake it for now.
    // This was the easiest option -.- pty/tty are better crates going forward.
    let mut hcitool = Command::new("python")
        .arg("-c")
        .arg(r#"import pty; pty.spawn(["hcitool", "lescan"])"#)
        .stdin(Stdio::null())
        .stderr(Stdio::null())
        .stdout(Stdio::piped())
        .spawn()
        .expect("failed to execute `hcitool`");

    let pid = hcitool.id();
    let mut buf = BufReader::new(hcitool.stdout.take().unwrap());

    // Queue two lines to find i/o error line.
    let mut queue = vec![];
    let mut s = String::new();
    match buf.read_line(&mut s) {
        Ok(_) => {
            if s.find("Input/output error").is_some() {
                hcitool.wait().unwrap();
                Command::new("hciconfig").arg("hdi0").arg("down").output().unwrap();
                Command::new("hciconfig").arg("hdi0").arg("up").output().unwrap();
                return scan();
            } else {
                queue.push(Some(s));
            }
        }
        Err(_) => {
            queue.push(None);
        }
    };

    Ok(Scan {
        pid: Some(pid),
        queue: queue,
        out: buf,
    })
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
    }
}