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
#![deny(missing_docs)]
use nix::sys::select::*;
use nix::sys::time::{TimeVal, TimeValLike};
use nix::unistd::getpid;
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::os::unix::io::AsRawFd;
use std::os::unix::net::UnixDatagram;
use std;
use super::Result;

const BUF_SIZE: usize = 10_240;
const PATH_DEFAULT_CLIENT: &str = "/tmp";
const PATH_DEFAULT_SERVER: &str = "/var/run/wpa_supplicant/wlan0";

/// Error type used for some library functions
#[derive(Debug, Fail, PartialEq)]
enum WpaError {
    #[fail(display = "Failed to execute the specified command")]
    Failure,
}

/// Builder object used to construct a `WpaCtrl` session
#[derive(Default)]
pub struct WpaCtrlBuilder {
    cli_path: Option<PathBuf>,
    ctrl_path: Option<PathBuf>,
}

impl WpaCtrlBuilder {
    /// A path-like object for this application's UNIX domain socket
    /// 
    /// # Examples
    ///
    /// ```
    /// use wpactrl::WpaCtrl;
    /// let wpa = WpaCtrl::new()
    ///             .cli_path("/tmp")
    ///             .open()
    ///             .unwrap();
    /// ```
    pub fn cli_path<I, P>(mut self, cli_path: I) -> Self
        where I: Into<Option<P>>, P: AsRef<Path> + Sized, PathBuf: From<P> {
        self.cli_path = cli_path.into().map(PathBuf::from);
        self
    }

    /// A path-like object for the wpasupplicant / hostap UNIX domain sockets
    /// 
    /// # Examples
    ///
    /// ```
    /// use wpactrl::WpaCtrl;
    /// let wpa = WpaCtrl::new()
    ///             .ctrl_path("/var/run/wpa_supplicant/wlan0")
    ///             .open()
    ///             .unwrap();
    /// ```
    pub fn ctrl_path<I, P>(mut self, ctrl_path: I) -> Self
        where I: Into<Option<P>>, P: AsRef<Path> + Sized, PathBuf: From<P> {
        self.ctrl_path = ctrl_path.into().map(PathBuf::from);
        self
    }

    /// Open a control interface to wpasupplicant.
    ///
    /// # Examples
    ///
    /// ```
    /// use wpactrl::WpaCtrl;
    /// let wpa = WpaCtrl::new().open().unwrap();
    /// ```
    pub fn open(self) -> Result<WpaCtrl> {
        let mut counter = 0;
        loop {
            counter += 1;
            let bind_filename = format!("wpa_ctrl_{}-{}", getpid(), counter);
            let bind_filepath = self.cli_path.as_ref().map(|p|p.as_path()).unwrap_or_else(||Path::new(PATH_DEFAULT_CLIENT)).join(bind_filename);
            match UnixDatagram::bind(&bind_filepath) {
                Ok(socket) => {
                    socket.connect(self.ctrl_path.unwrap_or_else(||PATH_DEFAULT_SERVER.into()))?;
                    socket.set_nonblocking(true)?;
                    return Ok(WpaCtrl(WpaCtrlInternal {
                        buffer: [0; BUF_SIZE],
                        handle: socket,
                        filepath: bind_filepath,
                    }))
                },
                Err(ref e) if counter < 2 && e.kind() == std::io::ErrorKind::AddrInUse => {
                    std::fs::remove_file(bind_filepath)?;
                    continue;
                },
                Err(e) => Err(e)?,
            };
        }
    }
}

struct WpaCtrlInternal {
    buffer: [u8; BUF_SIZE],
    handle: UnixDatagram,
    filepath: PathBuf,
}

impl WpaCtrlInternal {
    /// Check if any messages are available
    pub fn pending(&mut self) -> Result<bool> {
        let mut fd_set = FdSet::new();
        let raw_fd = self.handle.as_raw_fd();
        fd_set.insert(raw_fd);
        select(raw_fd+1, Some(&mut fd_set), None, None, Some(&mut TimeVal::seconds(0)))?;
        Ok(fd_set.contains(raw_fd))
    }

    /// Receive a message
    pub fn recv(&mut self) -> Result<Option<String>> {
        if self.pending()? {
            let buf_len = self.handle.recv(&mut self.buffer)?;
            std::str::from_utf8(&self.buffer[0..buf_len]).map(|s|Some(s.to_owned())).map_err(|e|e.into())
        } else {
            Ok(None)
        }
    }

    /// Send a command to wpasupplicant / hostapd. 
    fn request<F: FnMut(&str)>(&mut self, cmd: &str, mut cb: F) -> Result<String> {
        self.handle.send(cmd.as_bytes())?;
        loop {
            let mut fd_set = FdSet::new();
            fd_set.insert(self.handle.as_raw_fd());
            select(self.handle.as_raw_fd()+1, Some(&mut fd_set), None, None, Some(&mut TimeVal::seconds(10)))?;
            match self.handle.recv(&mut self.buffer) {
                Ok(len) => {
                    let s = std::str::from_utf8(&self.buffer[0..len])?;
                    if s.starts_with('<') {
                        cb(s)
                    } else {
                        return Ok(s.to_owned());
                    }
                },
                Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
                Err(e) => return Err(e.into()),
            }
        }
    }
}

impl Drop for WpaCtrlInternal {
    fn drop(&mut self) {
        if let Err(e) = std::fs::remove_file(&self.filepath) {
            warn!("Unable to unlink {:?}", e);
        }
    }
}

/// A connection to wpasupplicant / hostap
pub struct WpaCtrl(WpaCtrlInternal);

impl WpaCtrl {
    /// Creates a builder for a wpasupplicant / hostap connection
    ///
    /// # Examples
    ///
    /// ```
    /// let wpa = wpactrl::WpaCtrl::new().open().unwrap();
    /// ```
    pub fn new() -> WpaCtrlBuilder {
        WpaCtrlBuilder::default()
    }

    /// Register as an event monitor for control interface messages
    /// 
    /// # Examples
    ///
    /// ```
    /// let mut wpa = wpactrl::WpaCtrl::new().open().unwrap();
    /// let wpa_attached = wpa.attach().unwrap();
    /// ```
    pub fn attach(mut self) -> Result<WpaCtrlAttached> {
        // FIXME: None closure would be better
        if self.0.request("ATTACH", |_: &str|())? != "OK\n" {
            Err(WpaError::Failure.into())
        } else {
            Ok(WpaCtrlAttached(self.0, VecDeque::new()))
        }
    }

    /// Send a command to wpa_supplicant/hostapd.
    ///
    /// Commands are generally identical to those used in wpa_cli,
    /// except all uppercase (eg LIST_NETWORKS, SCAN, etc)
    /// 
    /// # Examples
    ///
    /// ```
    /// let mut wpa = wpactrl::WpaCtrl::new().open().unwrap();
    /// assert_eq!(wpa.request("PING").unwrap(), "PONG\n");
    /// ```
    pub fn request(&mut self, cmd: &str) -> Result<String> {
        self.0.request(cmd, |_: &str|())
    }
}

/// A connection to wpasupplicant / hostap that receives status messages
pub struct WpaCtrlAttached(WpaCtrlInternal, VecDeque<String>);

impl WpaCtrlAttached {

    /// Stop listening for and discard any remaining control interface messages
    /// 
    /// # Examples
    ///
    /// ```
    /// let mut wpa = wpactrl::WpaCtrl::new().open().unwrap().attach().unwrap();
    /// wpa.detach().unwrap();
    /// ```
    pub fn detach(mut self) -> Result<WpaCtrl> {
        if self.0.request("DETACH", |_: &str|())? != "OK\n" {
            Err(WpaError::Failure.into())
        } else {
            Ok(WpaCtrl(self.0))
        }
    }

    /// Receive the next control interface message.
    ///
    /// Note that multiple control interface messages can be pending;
    /// call this function repeatedly until it returns None to get all of them.
    /// 
    /// # Examples
    ///
    /// ```
    /// let mut wpa = wpactrl::WpaCtrl::new().open().unwrap().attach().unwrap();
    /// assert_eq!(wpa.recv().unwrap(), None);
    /// ```
    pub fn recv(&mut self) -> Result<Option<String>> {
        if let Some(s) = self.1.pop_back() {
            Ok(Some(s))
        } else {
            self.0.recv()
        }
    }

    /// Send a command to wpa_supplicant/hostapd.
    ///
    /// Commands are generally identical to those used in wpa_cli,
    /// except all uppercase (eg LIST_NETWORKS, SCAN, etc)
    ///
    /// Control interface messages will be buffered as the command
    /// runs, and will be returned on the next call to recv.
    /// 
    /// # Examples
    ///
    /// ```
    /// let mut wpa = wpactrl::WpaCtrl::new().open().unwrap();
    /// assert_eq!(wpa.request("PING").unwrap(), "PONG\n");
    /// ```
    pub fn request(&mut self, cmd: &str) -> Result<String> {
        let mut messages = VecDeque::new();
        let r = self.0.request(cmd, |s: &str|{
            messages.push_front(s.into())
        });
        self.1.extend(messages);
        r
    }
}

#[cfg(test)]
mod test {
    use super::*;

    fn wpa_ctrl() -> WpaCtrl {
        WpaCtrl::new().open().unwrap()
    }

    #[test]
    fn attach() {
        wpa_ctrl().attach().unwrap().detach().unwrap().attach().unwrap().detach().unwrap();
    }

    #[test]
    fn detach() {
        let wpa = wpa_ctrl().attach().unwrap();
        wpa.detach().unwrap();
    }

    #[test]
    fn new() {
        wpa_ctrl();
    }

    #[test]
    fn request() {
        let mut wpa = wpa_ctrl();
        assert_eq!(wpa.request("PING").unwrap(), "PONG\n");
        let mut wpa_attached = wpa.attach().unwrap();
        // FIXME: This may not trigger the callback
        assert_eq!(wpa_attached.request("PING").unwrap(), "PONG\n");
    }

    #[test]
    fn recv() {
        let mut wpa = wpa_ctrl().attach().unwrap();
        assert_eq!(wpa.recv().unwrap(), None);
        assert_eq!(wpa.request("SCAN").unwrap(), "OK\n");
        loop {
            match wpa.recv().unwrap() {
                Some(s) => {
                    assert_eq!(&s[3..], "CTRL-EVENT-SCAN-STARTED ");
                    break;
                }
                None => std::thread::sleep(std::time::Duration::from_millis(10)),
            }
        }
        wpa.detach().unwrap();
    }
}