1 //! D-Bus bindings for Rust
2 //!
3 //! [D-Bus](http://dbus.freedesktop.org/) is a message bus, and is mainly used in Linux
4 //! for communication between processes. It is present by default on almost every
5 //! Linux distribution out there, and runs in two instances - one per session, and one
6 //! system-wide.
7 //!
8 //! In addition to the API documentation, which you're currently reading, you might want to
9 //! look in the examples directory, which contains many examples and an argument guide.
10 //! README.md also contain a few quick "getting started" examples.
11 //!
12 //! In addition to this crate, there are two companion crates, dbus-codegen for generating Rust
13 //! code from D-Bus introspection data, and dbus-tokio for integrating D-Bus with [Tokio](http://tokio.rs).
14 //! However, at the time of this writing, these are far less mature than this crate.
15 
16 #![warn(missing_docs)]
17 
18 extern crate libc;
19 
20 pub use ffi::DBusBusType as BusType;
21 pub use connection::DBusNameFlag as NameFlag;
22 pub use ffi::DBusRequestNameReply as RequestNameReply;
23 pub use ffi::DBusReleaseNameReply as ReleaseNameReply;
24 pub use ffi::DBusMessageType as MessageType;
25 
26 pub use message::{Message, MessageItem, MessageItemArray, FromMessageItem, OwnedFd, ArrayError, ConnPath};
27 pub use connection::{Connection, ConnectionItems, ConnectionItem, ConnMsgs, MsgHandler, MsgHandlerResult, MsgHandlerType, MessageCallback};
28 pub use prop::PropHandler;
29 pub use prop::Props;
30 pub use watch::{Watch, WatchEvent};
31 pub use signalargs::SignalArgs;
32 
33 /// A TypeSig describes the type of a MessageItem.
34 #[deprecated(note="Use Signature instead")]
35 pub type TypeSig<'a> = std::borrow::Cow<'a, str>;
36 
37 use std::ffi::{CString, CStr};
38 use std::ptr;
39 use std::os::raw::c_char;
40 
41 #[allow(missing_docs)]
42 extern crate libdbus_sys as ffi;
43 mod message;
44 mod prop;
45 mod watch;
46 mod connection;
47 mod signalargs;
48 
49 mod strings;
50 pub use strings::{Signature, Path, Interface, Member, ErrorName, BusName};
51 
52 pub mod arg;
53 
54 pub mod stdintf;
55 
56 pub mod tree;
57 
58 static INITDBUS: std::sync::Once = std::sync::ONCE_INIT;
59 
init_dbus()60 fn init_dbus() {
61     INITDBUS.call_once(|| {
62         if unsafe { ffi::dbus_threads_init_default() } == 0 {
63             panic!("Out of memory when trying to initialize D-Bus library!");
64         }
65     });
66 }
67 
68 /// D-Bus Error wrapper.
69 pub struct Error {
70     e: ffi::DBusError,
71 }
72 
73 unsafe impl Send for Error {}
74 
75 // Note! For this Sync impl to be safe, it requires that no functions that take &self,
76 // actually calls into FFI. All functions that call into FFI with a ffi::DBusError
77 // must take &mut self.
78 
79 unsafe impl Sync for Error {}
80 
c_str_to_slice(c: & *const c_char) -> Option<&str>81 fn c_str_to_slice(c: & *const c_char) -> Option<&str> {
82     if *c == ptr::null() { None }
83     else { std::str::from_utf8( unsafe { CStr::from_ptr(*c).to_bytes() }).ok() }
84 }
85 
to_c_str(n: &str) -> CString86 fn to_c_str(n: &str) -> CString { CString::new(n.as_bytes()).unwrap() }
87 
88 impl Error {
89 
90     /// Create a new custom D-Bus Error.
new_custom(name: &str, message: &str) -> Error91     pub fn new_custom(name: &str, message: &str) -> Error {
92         let n = to_c_str(name);
93         let m = to_c_str(&message.replace("%","%%"));
94         let mut e = Error::empty();
95 
96         unsafe { ffi::dbus_set_error(e.get_mut(), n.as_ptr(), m.as_ptr()) };
97         e
98     }
99 
empty() -> Error100     fn empty() -> Error {
101         init_dbus();
102         let mut e = ffi::DBusError {
103             name: ptr::null(),
104             message: ptr::null(),
105             dummy: 0,
106             padding1: ptr::null()
107         };
108         unsafe { ffi::dbus_error_init(&mut e); }
109         Error{ e: e }
110     }
111 
112     /// Error name/type, e g 'org.freedesktop.DBus.Error.Failed'
name(&self) -> Option<&str>113     pub fn name(&self) -> Option<&str> {
114         c_str_to_slice(&self.e.name)
115     }
116 
117     /// Custom message, e g 'Could not find a matching object path'
message(&self) -> Option<&str>118     pub fn message(&self) -> Option<&str> {
119         c_str_to_slice(&self.e.message)
120     }
121 
get_mut(&mut self) -> &mut ffi::DBusError122     fn get_mut(&mut self) -> &mut ffi::DBusError { &mut self.e }
123 }
124 
125 impl Drop for Error {
drop(&mut self)126     fn drop(&mut self) {
127         unsafe { ffi::dbus_error_free(&mut self.e); }
128     }
129 }
130 
131 impl std::fmt::Debug for Error {
fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error>132     fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
133         write!(f, "D-Bus error: {} ({})", self.message().unwrap_or(""),
134             self.name().unwrap_or(""))
135     }
136 }
137 
138 impl std::error::Error for Error {
description(&self) -> &str139     fn description(&self) -> &str { "D-Bus error" }
140 }
141 
142 impl std::fmt::Display for Error {
fmt(&self, f: &mut std::fmt::Formatter) -> Result<(),std::fmt::Error>143     fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(),std::fmt::Error> {
144         if let Some(x) = self.message() {
145              write!(f, "{:?}", x.to_string())
146         } else { Ok(()) }
147     }
148 }
149 
150 impl From<arg::TypeMismatchError> for Error {
from(t: arg::TypeMismatchError) -> Error151     fn from(t: arg::TypeMismatchError) -> Error {
152         Error::new_custom("org.freedesktop.DBus.Error.Failed", &format!("{}", t))
153     }
154 }
155 
156 impl From<tree::MethodErr> for Error {
from(t: tree::MethodErr) -> Error157     fn from(t: tree::MethodErr) -> Error {
158         Error::new_custom(t.errorname(), t.description())
159     }
160 }
161 
162 #[cfg(test)]
163 mod test {
164     use super::{Connection, Message, BusType, MessageItem, ConnectionItem, NameFlag,
165         RequestNameReply, ReleaseNameReply};
166 
167     #[test]
connection()168     fn connection() {
169         let c = Connection::get_private(BusType::Session).unwrap();
170         let n = c.unique_name();
171         assert!(n.starts_with(":1."));
172         println!("Connected to DBus, unique name: {}", n);
173     }
174 
175     #[test]
invalid_message()176     fn invalid_message() {
177         let c = Connection::get_private(BusType::Session).unwrap();
178         let m = Message::new_method_call("foo.bar", "/", "foo.bar", "FooBar").unwrap();
179         let e = c.send_with_reply_and_block(m, 2000).err().unwrap();
180         assert!(e.name().unwrap() == "org.freedesktop.DBus.Error.ServiceUnknown");
181     }
182 
183     #[test]
message_listnames()184     fn message_listnames() {
185         let c = Connection::get_private(BusType::Session).unwrap();
186         let m = Message::method_call(&"org.freedesktop.DBus".into(), &"/".into(),
187             &"org.freedesktop.DBus".into(), &"ListNames".into());
188         let r = c.send_with_reply_and_block(m, 2000).unwrap();
189         let reply = r.get_items();
190         println!("{:?}", reply);
191     }
192 
193     #[test]
message_namehasowner()194     fn message_namehasowner() {
195         let c = Connection::get_private(BusType::Session).unwrap();
196         let mut m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "NameHasOwner").unwrap();
197         m.append_items(&[MessageItem::Str("org.freedesktop.DBus".to_string())]);
198         let r = c.send_with_reply_and_block(m, 2000).unwrap();
199         let reply = r.get_items();
200         println!("{:?}", reply);
201         assert_eq!(reply, vec!(MessageItem::Bool(true)));
202     }
203 
204     #[test]
object_path()205     fn object_path() {
206         use  std::sync::mpsc;
207         let (tx, rx) = mpsc::channel();
208         let thread = ::std::thread::spawn(move || {
209             let c = Connection::get_private(BusType::Session).unwrap();
210             c.register_object_path("/hello").unwrap();
211             // println!("Waiting...");
212             tx.send(c.unique_name()).unwrap();
213             for n in c.iter(1000) {
214                 // println!("Found message... ({})", n);
215                 match n {
216                     ConnectionItem::MethodCall(ref m) => {
217                         let reply = Message::new_method_return(m).unwrap();
218                         c.send(reply).unwrap();
219                         break;
220                     }
221                     _ => {}
222                 }
223             }
224             c.unregister_object_path("/hello");
225         });
226 
227         let c = Connection::get_private(BusType::Session).unwrap();
228         let n = rx.recv().unwrap();
229         let m = Message::new_method_call(&n, "/hello", "com.example.hello", "Hello").unwrap();
230         println!("Sending...");
231         let r = c.send_with_reply_and_block(m, 8000).unwrap();
232         let reply = r.get_items();
233         println!("{:?}", reply);
234         thread.join().unwrap();
235 
236     }
237 
238     #[test]
register_name()239     fn register_name() {
240         let c = Connection::get_private(BusType::Session).unwrap();
241         let n = format!("com.example.hello.test.register_name");
242         assert_eq!(c.register_name(&n, NameFlag::ReplaceExisting as u32).unwrap(), RequestNameReply::PrimaryOwner);
243         assert_eq!(c.release_name(&n).unwrap(), ReleaseNameReply::Released);
244     }
245 
246     #[test]
signal()247     fn signal() {
248         let c = Connection::get_private(BusType::Session).unwrap();
249         let iface = "com.example.signaltest";
250         let mstr = format!("interface='{}',member='ThisIsASignal'", iface);
251         c.add_match(&mstr).unwrap();
252         let m = Message::new_signal("/mysignal", iface, "ThisIsASignal").unwrap();
253         let uname = c.unique_name();
254         c.send(m).unwrap();
255         for n in c.iter(1000) {
256             match n {
257                 ConnectionItem::Signal(s) => {
258                     let (_, p, i, m) = s.headers();
259                     match (&*p.unwrap(), &*i.unwrap(), &*m.unwrap()) {
260                         ("/mysignal", "com.example.signaltest", "ThisIsASignal") => {
261                             assert_eq!(&*s.sender().unwrap(), &*uname);
262                             break;
263                         },
264                         (_, _, _) => println!("Other signal: {:?}", s.headers()),
265                     }
266                 }
267                 _ => {},
268             }
269         }
270         c.remove_match(&mstr).unwrap();
271     }
272 
273 
274     #[test]
watch()275     fn watch() {
276         let c = Connection::get_private(BusType::Session).unwrap();
277         let d = c.watch_fds();
278         assert!(d.len() > 0);
279         println!("Fds to watch: {:?}", d);
280     }
281 }
282