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
use crate::{Error, Message, to_c_str};
use std::{str, time::Duration, collections::HashMap};
use std::sync::{Mutex, atomic::AtomicU8, atomic::Ordering};
use std::ffi::CStr;
use std::os::raw::{c_void, c_int};
use super::{BusType, Watch, WatchFd};
#[derive(Debug)]
struct ConnHandle(*mut ffi::DBusConnection, bool);
unsafe impl Send for ConnHandle {}
unsafe impl Sync for ConnHandle {}
impl Drop for ConnHandle {
fn drop(&mut self) {
if self.1 { unsafe {
ffi::dbus_connection_close(self.0);
ffi::dbus_connection_unref(self.0);
}}
}
}
#[derive(Debug, Eq, PartialEq, Hash)]
struct WatchHandle(*mut ffi::DBusWatch);
unsafe impl Send for WatchHandle {}
unsafe impl Sync for WatchHandle {}
#[derive(Debug)]
struct WatchMap {
conn: ConnHandle,
list: Mutex<HashMap<WatchHandle, (Watch, bool)>>,
current_rw: AtomicU8,
current_fd: Option<WatchFd>,
}
fn calc_rw(list: &HashMap<WatchHandle, (Watch, bool)>) -> u8 {
let mut r = 0;
for (w, b) in list.values() {
if *b && w.read { r |= 1; }
if *b && w.write { r |= 2; }
}
r
}
impl WatchMap {
fn new(conn: ConnHandle) -> Box<WatchMap> {
extern "C" fn add_watch_cb(watch: *mut ffi::DBusWatch, data: *mut c_void) -> u32 { unsafe {
let wm: &WatchMap = &*(data as *mut _);
wm.list.lock().unwrap().insert(WatchHandle(watch), Watch::from_raw_enabled(watch));
1
}}
extern "C" fn remove_watch_cb(watch: *mut ffi::DBusWatch, data: *mut c_void) { unsafe {
let wm: &WatchMap = &*(data as *mut _);
wm.list.lock().unwrap().remove(&WatchHandle(watch));
}}
extern "C" fn toggled_watch_cb(watch: *mut ffi::DBusWatch, data: *mut c_void) { unsafe {
let wm: &WatchMap = &*(data as *mut _);
let mut list = wm.list.lock().unwrap();
let (_, ref mut b) = list.get_mut(&WatchHandle(watch)).unwrap();
*b = ffi::dbus_watch_get_enabled(watch) != 0;
wm.current_rw.store(calc_rw(&list), Ordering::Release);
}}
let mut wm = Box::new(WatchMap {
conn, list: Default::default(), current_rw: Default::default(), current_fd: None
});
let wptr: &WatchMap = &wm;
if unsafe { ffi::dbus_connection_set_watch_functions(wm.conn.0,
Some(add_watch_cb), Some(remove_watch_cb), Some(toggled_watch_cb), wptr as *const _ as *mut _, None) } == 0 {
panic!("Cannot enable watch tracking (OOM?)")
}
{
let list = wm.list.lock().unwrap();
wm.current_rw.store(calc_rw(&list), Ordering::Release);
for (w, _) in list.values() {
if let Some(ref fd) = &wm.current_fd {
assert_eq!(*fd, w.fd);
} else {
wm.current_fd = Some(w.fd);
}
}
}
wm
}
}
impl Drop for WatchMap {
fn drop(&mut self) {
let wptr: &WatchMap = &self;
if unsafe { ffi::dbus_connection_set_watch_functions(self.conn.0,
None, None, None, wptr as *const _ as *mut _, None) } == 0 {
panic!("Cannot disable watch tracking (OOM?)")
}
}
}
#[derive(Debug)]
pub struct Channel {
handle: ConnHandle,
watchmap: Option<Box<WatchMap>>,
}
impl Drop for Channel {
fn drop(&mut self) {
self.set_watch_enabled(false); }
}
impl Channel {
#[inline(always)]
pub (crate) fn conn(&self) -> *mut ffi::DBusConnection {
self.handle.0
}
fn conn_from_ptr(ptr: *mut ffi::DBusConnection) -> Result<Channel, Error> {
let handle = ConnHandle(ptr, true);
unsafe { ffi::dbus_connection_set_exit_on_disconnect(ptr, 0) };
let c = Channel { handle, watchmap: None };
Ok(c)
}
pub fn get_private(bus: BusType) -> Result<Channel, Error> {
let mut e = Error::empty();
let b = match bus {
BusType::Session => ffi::DBusBusType::Session,
BusType::System => ffi::DBusBusType::System,
BusType::Starter => ffi::DBusBusType::Starter,
};
let conn = unsafe { ffi::dbus_bus_get_private(b, e.get_mut()) };
if conn.is_null() {
return Err(e)
}
Self::conn_from_ptr(conn)
}
pub fn open_private(address: &str) -> Result<Channel, Error> {
let mut e = Error::empty();
let conn = unsafe { ffi::dbus_connection_open_private(to_c_str(address).as_ptr(), e.get_mut()) };
if conn.is_null() {
return Err(e)
}
Self::conn_from_ptr(conn)
}
pub fn register(&mut self) -> Result<(), Error> {
let mut e = Error::empty();
if unsafe { ffi::dbus_bus_register(self.conn(), e.get_mut()) == 0 } {
Err(e)
} else {
Ok(())
}
}
pub fn is_connected(&self) -> bool {
unsafe { ffi::dbus_connection_get_is_connected(self.conn()) != 0 }
}
pub fn unique_name(&self) -> Option<&str> {
let c = unsafe { ffi::dbus_bus_get_unique_name(self.conn()) };
if c.is_null() { return None; }
let s = unsafe { CStr::from_ptr(c) };
str::from_utf8(s.to_bytes()).ok()
}
pub fn send(&self, msg: Message) -> Result<u32, ()> {
let mut serial = 0u32;
let r = unsafe { ffi::dbus_connection_send(self.conn(), msg.ptr(), &mut serial) };
if r == 0 { return Err(()); }
Ok(serial)
}
pub fn send_with_reply_and_block(&self, msg: Message, timeout: Duration) -> Result<Message, Error> {
let mut e = Error::empty();
let response = unsafe {
ffi::dbus_connection_send_with_reply_and_block(self.conn(), msg.ptr(),
timeout.as_millis() as c_int, e.get_mut())
};
if response.is_null() {
return Err(e);
}
Ok(Message::from_ptr(response, false))
}
pub fn flush(&self) { unsafe { ffi::dbus_connection_flush(self.conn()) } }
pub fn read_write(&self, timeout: Option<Duration>) -> Result<(), ()> {
let t = timeout.map_or(-1, |t| t.as_millis() as c_int);
if unsafe { ffi::dbus_connection_read_write(self.conn(), t) == 0 } {
Err(())
} else {
Ok(())
}
}
pub fn has_messages_to_send(&self) -> bool {
unsafe { ffi::dbus_connection_has_messages_to_send(self.conn()) == 1 }
}
pub fn pop_message(&self) -> Option<Message> {
let mptr = unsafe { ffi::dbus_connection_pop_message(self.conn()) };
if mptr.is_null() {
None
} else {
let msg = Message::from_ptr(mptr, false);
Some(msg)
}
}
pub fn blocking_pop_message(&self, timeout: Duration) -> Result<Option<Message>, Error> {
if let Some(msg) = self.pop_message() { return Ok(Some(msg)) }
self.read_write(Some(timeout)).map_err(|_|
Error::new_failed("Failed to read/write data, disconnected from D-Bus?")
)?;
Ok(self.pop_message())
}
pub fn set_watch_enabled(&mut self, enable: bool) {
if enable == self.watchmap.is_some() { return }
if enable {
self.watchmap = Some(WatchMap::new(ConnHandle(self.conn(), false)));
} else {
self.watchmap = None;
}
}
pub fn watch(&self) -> Watch {
let wm = self.watchmap.as_ref().unwrap();
let rw = wm.current_rw.load(Ordering::Acquire);
Watch {
fd: wm.current_fd.unwrap(),
read: (rw & 1) != 0,
write: (rw & 2) != 0,
}
}
#[deprecated]
pub fn watch_fds(&mut self) -> Result<Vec<Watch>, ()> {
let en = self.watchmap.is_some();
self.set_watch_enabled(true);
let mut wlist: Vec<Watch> = self.watchmap.as_ref().unwrap().list.lock().unwrap().values()
.map(|&(w, b)| Watch { fd: w.fd, read: b && w.read, write: b && w.write })
.collect();
self.set_watch_enabled(en);
if wlist.len() == 2 && wlist[0].fd == wlist[1].fd {
wlist = vec!(Watch {
fd: wlist[0].fd,
read: wlist[0].read || wlist[1].read,
write: wlist[0].write || wlist[1].write
});
}
Ok(wlist)
}
}
impl Watch {
unsafe fn from_raw_enabled(watch: *mut ffi::DBusWatch) -> (Self, bool) {
#[cfg(unix)]
let mut w = Watch {fd: ffi::dbus_watch_get_unix_fd(watch), read: false, write: false};
#[cfg(windows)]
let mut w = Watch {fd: ffi::dbus_watch_get_socket(watch) as WatchFd, read: false, write: false};
let enabled = ffi::dbus_watch_get_enabled(watch) != 0;
let flags = ffi::dbus_watch_get_flags(watch);
use std::os::raw::c_uint;
w.read = (flags & ffi::DBUS_WATCH_READABLE as c_uint) != 0;
w.write = (flags & ffi::DBUS_WATCH_WRITABLE as c_uint) != 0;
(w, enabled)
}
}