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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use std::rc::Rc;
use std::fmt;
use std::net::Ipv4Addr;
use ascii::AsAsciiStr;
use dbus_nm::DBusNetworkManager;
use wifi::Security;
use device::{get_active_connection_devices, Device};
use ssid::{AsSsidSlice, Ssid, SsidSlice};
#[derive(Clone)]
pub struct Connection {
dbus_manager: Rc<DBusNetworkManager>,
path: String,
settings: ConnectionSettings,
}
impl Connection {
fn init(dbus_manager: &Rc<DBusNetworkManager>, path: &str) -> Result<Self, String> {
let settings = dbus_manager.get_connection_settings(path)?;
Ok(Connection {
dbus_manager: Rc::clone(dbus_manager),
path: path.to_string(),
settings: settings,
})
}
pub fn settings(&self) -> &ConnectionSettings {
&self.settings
}
pub fn get_state(&self) -> Result<ConnectionState, String> {
let active_path_option = get_connection_active_path(&self.dbus_manager, &self.path)?;
if let Some(active_path) = active_path_option {
let state = self.dbus_manager.get_connection_state(&active_path)?;
Ok(state)
} else {
Ok(ConnectionState::Deactivated)
}
}
pub fn delete(&self) -> Result<(), String> {
self.dbus_manager.delete_connection(&self.path)
}
pub fn activate(&self) -> Result<ConnectionState, String> {
let state = self.get_state()?;
match state {
ConnectionState::Activated => Ok(ConnectionState::Activated),
ConnectionState::Activating => wait(
self,
&ConnectionState::Activated,
self.dbus_manager.method_timeout(),
),
ConnectionState::Unknown => Err("Unable to get connection state".to_string()),
_ => {
self.dbus_manager.activate_connection(&self.path)?;
wait(
self,
&ConnectionState::Activated,
self.dbus_manager.method_timeout(),
)
},
}
}
pub fn deactivate(&self) -> Result<ConnectionState, String> {
let state = self.get_state()?;
match state {
ConnectionState::Deactivated => Ok(ConnectionState::Deactivated),
ConnectionState::Deactivating => wait(
self,
&ConnectionState::Deactivated,
self.dbus_manager.method_timeout(),
),
ConnectionState::Unknown => Err("Unable to get connection state".to_string()),
_ => {
let active_path_option =
get_connection_active_path(&self.dbus_manager, &self.path)?;
if let Some(active_path) = active_path_option {
self.dbus_manager.deactivate_connection(&active_path)?;
wait(
self,
&ConnectionState::Deactivated,
self.dbus_manager.method_timeout(),
)
} else {
Ok(ConnectionState::Deactivated)
}
},
}
}
pub fn get_devices(&self) -> Result<Vec<Device>, String> {
let active_path_option = get_connection_active_path(&self.dbus_manager, &self.path)?;
if let Some(active_path) = active_path_option {
get_active_connection_devices(&self.dbus_manager, &active_path)
} else {
Ok(vec![])
}
}
}
impl Ord for Connection {
fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
i32::from(self).cmp(&i32::from(other))
}
}
impl PartialOrd for Connection {
fn partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Connection {
fn eq(&self, other: &Connection) -> bool {
i32::from(self) == i32::from(other)
}
}
impl Eq for Connection {}
impl fmt::Debug for Connection {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Connection {{ path: {:?}, settings: {:?} }}",
self.path, self.settings
)
}
}
impl<'a> From<&'a Connection> for i32 {
fn from(val: &Connection) -> i32 {
val.clone()
.path
.rsplit('/')
.nth(0)
.unwrap()
.parse::<i32>()
.unwrap()
}
}
#[derive(Default, Debug, Clone, Eq, PartialEq)]
pub struct ConnectionSettings {
pub kind: String,
pub id: String,
pub uuid: String,
pub ssid: Ssid,
pub mode: String,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ConnectionState {
Unknown = 0,
Activating = 1,
Activated = 2,
Deactivating = 3,
Deactivated = 4,
}
impl From<i64> for ConnectionState {
fn from(state: i64) -> Self {
match state {
0 => ConnectionState::Unknown,
1 => ConnectionState::Activating,
2 => ConnectionState::Activated,
3 => ConnectionState::Deactivating,
4 => ConnectionState::Deactivated,
_ => {
warn!("Undefined connection state: {}", state);
ConnectionState::Unknown
},
}
}
}
pub fn get_connections(dbus_manager: &Rc<DBusNetworkManager>) -> Result<Vec<Connection>, String> {
let paths = dbus_manager.list_connections()?;
let mut connections = Vec::with_capacity(paths.len());
for path in &paths {
connections.push(Connection::init(dbus_manager, path)?)
}
connections.sort();
Ok(connections)
}
pub fn get_active_connections(
dbus_manager: &Rc<DBusNetworkManager>,
) -> Result<Vec<Connection>, String> {
let active_paths = dbus_manager.get_active_connections()?;
let mut connections = Vec::with_capacity(active_paths.len());
for active_path in active_paths {
if let Some(path) = dbus_manager.get_active_connection_path(&active_path) {
connections.push(Connection::init(dbus_manager, &path)?)
}
}
connections.sort();
Ok(connections)
}
pub fn connect_to_access_point<P>(
dbus_manager: &Rc<DBusNetworkManager>,
device_path: &str,
access_point_path: &str,
ssid: &SsidSlice,
security: &Security,
password: &P,
) -> Result<(Connection, ConnectionState), String>
where
P: AsAsciiStr + ?Sized,
{
let (path, _) = dbus_manager.connect_to_access_point(
device_path,
access_point_path,
ssid,
security,
password,
)?;
let connection = Connection::init(dbus_manager, &path)?;
let state = wait(
&connection,
&ConnectionState::Activated,
dbus_manager.method_timeout(),
)?;
Ok((connection, state))
}
pub fn create_hotspot<S, P>(
dbus_manager: &Rc<DBusNetworkManager>,
device_path: &str,
interface: &str,
ssid: &S,
password: Option<&P>,
address: Option<Ipv4Addr>,
) -> Result<(Connection, ConnectionState), String>
where
S: AsSsidSlice + ?Sized,
P: AsAsciiStr + ?Sized,
{
let (path, _) = dbus_manager.create_hotspot(device_path, interface, ssid, password, address)?;
let connection = Connection::init(dbus_manager, &path)?;
let state = wait(
&connection,
&ConnectionState::Activated,
dbus_manager.method_timeout(),
)?;
Ok((connection, state))
}
fn get_connection_active_path(
dbus_manager: &DBusNetworkManager,
connection_path: &str,
) -> Result<Option<String>, String> {
let active_paths = dbus_manager.get_active_connections()?;
for active_path in active_paths {
if let Some(settings_path) = dbus_manager.get_active_connection_path(&active_path) {
if connection_path == settings_path {
return Ok(Some(active_path));
}
}
}
Ok(None)
}
fn wait(
connection: &Connection,
target_state: &ConnectionState,
timeout: u64,
) -> Result<ConnectionState, String> {
if timeout == 0 {
return connection.get_state();
}
debug!("Waiting for connection state: {:?}", target_state);
let mut total_time = 0;
loop {
::std::thread::sleep(::std::time::Duration::from_secs(1));
let state = connection.get_state()?;
total_time += 1;
if state == *target_state {
debug!(
"Connection target state reached: {:?} / {}s elapsed",
state, total_time
);
return Ok(state);
} else if total_time >= timeout {
debug!(
"Timeout reached in waiting for connection state ({:?}): {:?} / {}s elapsed",
target_state, state, total_time
);
return Ok(state);
}
debug!(
"Still waiting for connection state ({:?}): {:?} / {}s elapsed",
target_state, state, total_time
);
}
}
#[cfg(test)]
mod tests {
use super::super::NetworkManager;
use super::*;
#[test]
fn test_connection_enable_disable() {
let manager = NetworkManager::new();
let connections = manager.get_connections().unwrap();
let wifi_env_var = "TEST_WIFI_SSID";
let connection = match ::std::env::var(wifi_env_var) {
Ok(ssid) => connections
.iter()
.filter(|c| c.settings().ssid.as_str().unwrap() == ssid)
.nth(0)
.unwrap()
.clone(),
Err(e) => panic!(
"couldn't retrieve environment variable {}: {}",
wifi_env_var, e
),
};
let state = connection.get_state().unwrap();
if state == ConnectionState::Activated {
let state = connection.deactivate().unwrap();
assert_eq!(ConnectionState::Deactivated, state);
::std::thread::sleep(::std::time::Duration::from_secs(5));
let state = connection.activate().unwrap();
assert_eq!(ConnectionState::Activated, state);
::std::thread::sleep(::std::time::Duration::from_secs(5));
} else {
let state = connection.activate().unwrap();
assert_eq!(ConnectionState::Activated, state);
::std::thread::sleep(::std::time::Duration::from_secs(5));
let state = connection.deactivate().unwrap();
assert_eq!(ConnectionState::Deactivated, state);
::std::thread::sleep(::std::time::Duration::from_secs(5));
}
}
}