1 //! This crate provides tools to automatically project generic API to D-Bus RPC.
2 //!
3 //! For D-Bus projection to work automatically, the API needs to follow certain restrictions:
4 //!
5 //! * API does not use D-Bus specific features: Signals, Properties, ObjectManager.
6 //! * Interfaces (contain Methods) are hosted on statically allocated D-Bus objects.
7 //! * When the service needs to notify the client about changes, callback objects are used. The
8 //!   client can pass a callback object obeying a specified Interface by passing the D-Bus object
9 //!   path.
10 //!
11 //! A good example is in
12 //! [`manager_service`](https://android.googlesource.com/platform/packages/modules/Bluetooth/+/refs/heads/master/system/gd/rust/linux/mgmt)
13 //! crate:
14 //!
15 //! * Define RPCProxy like in
16 //! [here](https://android.googlesource.com/platform/packages/modules/Bluetooth/+/refs/heads/master/system/gd/rust/linux/mgmt/src/lib.rs)
17 //! (TODO: We should remove this requirement in the future).
18 //! * Generate `DBusArg` trait like in
19 //! [here](https://android.googlesource.com/platform/packages/modules/Bluetooth/+/refs/heads/master/system/gd/rust/linux/mgmt/src/bin/btmanagerd/dbus_arg.rs).
20 //! This trait is generated by a macro and cannot simply be imported because of Rust's
21 //! [Orphan Rule](https://github.com/Ixrec/rust-orphan-rules).
22 //! * Define D-Bus-agnostic traits like in
23 //! [here](https://android.googlesource.com/platform/packages/modules/Bluetooth/+/refs/heads/master/system/gd/rust/linux/mgmt/src/iface_bluetooth_manager.rs).
24 //! These traits can be projected into D-Bus Interfaces on D-Bus objects.  A method parameter can
25 //! be of a Rust primitive type, structure, enum, or a callback specially typed as
26 //! `Box<dyn SomeCallbackTrait + Send>`. Callback traits implement `RPCProxy`.
27 //! * Implement the traits like in
28 //! [here](https://android.googlesource.com/platform/packages/modules/Bluetooth/+/refs/heads/master/system/gd/rust/linux/mgmt/src/bin/btmanagerd/bluetooth_manager.rs),
29 //! also D-Bus-agnostic.
30 //! * Define D-Bus projection mappings like in
31 //! [here](https://android.googlesource.com/platform/packages/modules/Bluetooth/+/refs/heads/master/system/gd/rust/linux/mgmt/src/bin/btmanagerd/bluetooth_manager_dbus.rs).
32 //!   * Add [`generate_dbus_exporter`](dbus_macros::generate_dbus_exporter) macro to an `impl` of a
33 //!     trait.
34 //!   * Define a method name of each method with [`dbus_method`](dbus_macros::dbus_method) macro.
35 //!   * Similarly, for callbacks use [`dbus_proxy_obj`](dbus_macros::dbus_proxy_obj) macro to define
36 //!     the method mappings.
37 //!   * Rust primitive types can be converted automatically to and from D-Bus types.
38 //!   * Rust structures require implementations of `DBusArg` for the conversion. This is made easy
39 //!     with the [`dbus_propmap`](dbus_macros::dbus_propmap) macro.
40 //!   * Rust enums require implementations of `DBusArg` for the conversion. This is made easy with
41 //!     the [`impl_dbus_arg_enum`](impl_dbus_arg_enum) macro.
42 //! * To project a Rust object to a D-Bus, call the function generated by
43 //!   [`generate_dbus_exporter`](dbus_macros::generate_dbus_exporter) like in
44 //!   [here](https://android.googlesource.com/platform/packages/modules/Bluetooth/+/refs/heads/master/system/gd/rust/linux/mgmt/src/bin/btmanagerd/main.rs)
45 //!   passing in the object path, D-Bus connection, Crossroads object, the Rust object to be
46 //!   projected, and a [`DisconnectWatcher`](DisconnectWatcher) object.
47 
48 use dbus::arg::AppendAll;
49 use dbus::channel::MatchingReceiver;
50 use dbus::message::MatchRule;
51 use dbus::nonblock::SyncConnection;
52 use dbus::strings::BusName;
53 
54 use std::collections::HashMap;
55 use std::sync::{Arc, Mutex};
56 
57 pub mod prelude {
58     pub use super::{
59         dbus_generated, impl_dbus_arg_enum, impl_dbus_arg_from_into, ClientDBusProxy, DBusLog,
60         DBusLogOptions, DBusLogVerbosity, DisconnectWatcher,
61     };
62 }
63 
64 /// A D-Bus "NameOwnerChanged" handler that continuously monitors client disconnects.
65 ///
66 /// When the watched bus address disconnects, all the callbacks associated with it are called with
67 /// their associated ids.
68 pub struct DisconnectWatcher {
69     /// Global counter to provide a unique id every time `get_next_id` is called.
70     next_id: u32,
71 
72     /// Map of disconnect callbacks by bus address and callback id.
73     callbacks: Arc<Mutex<HashMap<BusName<'static>, HashMap<u32, Box<dyn Fn(u32) + Send>>>>>,
74 }
75 
76 impl DisconnectWatcher {
77     /// Creates a new DisconnectWatcher with empty callbacks.
new() -> DisconnectWatcher78     pub fn new() -> DisconnectWatcher {
79         DisconnectWatcher { next_id: 0, callbacks: Arc::new(Mutex::new(HashMap::new())) }
80     }
81 
82     /// Get the next unique id for this watcher.
get_next_id(&mut self) -> u3283     fn get_next_id(&mut self) -> u32 {
84         self.next_id = self.next_id + 1;
85         self.next_id
86     }
87 }
88 
89 impl DisconnectWatcher {
90     /// Adds a client address to be monitored for disconnect events.
add(&mut self, address: BusName<'static>, callback: Box<dyn Fn(u32) + Send>) -> u3291     pub fn add(&mut self, address: BusName<'static>, callback: Box<dyn Fn(u32) + Send>) -> u32 {
92         if !self.callbacks.lock().unwrap().contains_key(&address) {
93             self.callbacks.lock().unwrap().insert(address.clone(), HashMap::new());
94         }
95 
96         let id = self.get_next_id();
97         (*self.callbacks.lock().unwrap().get_mut(&address).unwrap()).insert(id, callback);
98 
99         return id;
100     }
101 
102     /// Sets up the D-Bus handler that monitors client disconnects.
setup_watch(&mut self, conn: Arc<SyncConnection>)103     pub async fn setup_watch(&mut self, conn: Arc<SyncConnection>) {
104         let mr = MatchRule::new_signal("org.freedesktop.DBus", "NameOwnerChanged");
105 
106         conn.add_match_no_cb(&mr.match_str()).await.unwrap();
107         let callbacks_map = self.callbacks.clone();
108         conn.start_receive(
109             mr,
110             Box::new(move |msg, _conn| {
111                 // The args are "address", "old address", "new address".
112                 // https://dbus.freedesktop.org/doc/dbus-specification.html#bus-messages-name-owner-changed
113                 let (addr, old, new) = msg.get3::<String, String, String>();
114 
115                 if addr.is_none() || old.is_none() || new.is_none() {
116                     return true;
117                 }
118 
119                 if old.unwrap().eq("") || !new.unwrap().eq("") {
120                     return true;
121                 }
122 
123                 // If old address exists but new address is empty, that means that client is
124                 // disconnected. So call the registered callbacks to be notified of this client
125                 // disconnect.
126                 let addr = BusName::new(addr.unwrap()).unwrap().into_static();
127                 if !callbacks_map.lock().unwrap().contains_key(&addr) {
128                     return true;
129                 }
130 
131                 for (id, callback) in callbacks_map.lock().unwrap()[&addr].iter() {
132                     callback(*id);
133                 }
134 
135                 callbacks_map.lock().unwrap().remove(&addr);
136 
137                 true
138             }),
139         );
140     }
141 
142     /// Removes callback by id if owned by the specific busname.
143     ///
144     /// If the callback can be removed, the callback will be called before being removed.
remove(&mut self, address: BusName<'static>, target_id: u32) -> bool145     pub fn remove(&mut self, address: BusName<'static>, target_id: u32) -> bool {
146         if !self.callbacks.lock().unwrap().contains_key(&address) {
147             return false;
148         }
149 
150         let mut callbacks = self.callbacks.lock().unwrap();
151         match callbacks.get(&address).and_then(|m| m.get(&target_id)) {
152             Some(cb) => {
153                 cb(target_id);
154                 let _ = callbacks.get_mut(&address).and_then(|m| m.remove(&target_id));
155                 true
156             }
157             None => false,
158         }
159     }
160 }
161 
162 /// A client proxy to conveniently call API methods generated with the
163 /// [`generate_dbus_interface_client`](dbus_macros::generate_dbus_interface_client) macro.
164 #[derive(Clone)]
165 pub struct ClientDBusProxy {
166     conn: Arc<SyncConnection>,
167     bus_name: String,
168     objpath: dbus::Path<'static>,
169     interface: String,
170 }
171 
172 impl ClientDBusProxy {
new( conn: Arc<SyncConnection>, bus_name: String, objpath: dbus::Path<'static>, interface: String, ) -> Self173     pub fn new(
174         conn: Arc<SyncConnection>,
175         bus_name: String,
176         objpath: dbus::Path<'static>,
177         interface: String,
178     ) -> Self {
179         Self { conn, bus_name, objpath, interface }
180     }
181 
create_proxy(&self) -> dbus::nonblock::Proxy<Arc<SyncConnection>>182     fn create_proxy(&self) -> dbus::nonblock::Proxy<Arc<SyncConnection>> {
183         let conn = self.conn.clone();
184         dbus::nonblock::Proxy::new(
185             self.bus_name.clone(),
186             self.objpath.clone(),
187             std::time::Duration::from_secs(2),
188             conn,
189         )
190     }
191 
192     /// Asynchronously calls the method and returns the D-Bus result and lets the caller unwrap.
async_method< A: AppendAll, T: 'static + dbus::arg::Arg + for<'z> dbus::arg::Get<'z>, >( &self, member: &str, args: A, ) -> Result<(T,), dbus::Error>193     pub async fn async_method<
194         A: AppendAll,
195         T: 'static + dbus::arg::Arg + for<'z> dbus::arg::Get<'z>,
196     >(
197         &self,
198         member: &str,
199         args: A,
200     ) -> Result<(T,), dbus::Error> {
201         let proxy = self.create_proxy();
202         proxy.method_call(self.interface.clone(), member, args).await
203     }
204 
205     /// Asynchronously calls the method and returns the D-Bus result with empty return data.
async_method_noreturn<A: AppendAll>( &self, member: &str, args: A, ) -> Result<(), dbus::Error>206     pub async fn async_method_noreturn<A: AppendAll>(
207         &self,
208         member: &str,
209         args: A,
210     ) -> Result<(), dbus::Error> {
211         let proxy = self.create_proxy();
212         proxy.method_call(self.interface.clone(), member, args).await
213     }
214 
215     /// Calls the method and returns the D-Bus result and lets the caller unwrap.
method_withresult< A: AppendAll, T: 'static + dbus::arg::Arg + for<'z> dbus::arg::Get<'z>, >( &self, member: &str, args: A, ) -> Result<(T,), dbus::Error>216     pub fn method_withresult<
217         A: AppendAll,
218         T: 'static + dbus::arg::Arg + for<'z> dbus::arg::Get<'z>,
219     >(
220         &self,
221         member: &str,
222         args: A,
223     ) -> Result<(T,), dbus::Error> {
224         let proxy = self.create_proxy();
225         // We know that all APIs return immediately, so we can block on it for simplicity.
226         return futures::executor::block_on(async {
227             proxy.method_call(self.interface.clone(), member, args).await
228         });
229     }
230 
231     /// Calls the method and unwrap the returned D-Bus result.
method<A: AppendAll, T: 'static + dbus::arg::Arg + for<'z> dbus::arg::Get<'z>>( &self, member: &str, args: A, ) -> T232     pub fn method<A: AppendAll, T: 'static + dbus::arg::Arg + for<'z> dbus::arg::Get<'z>>(
233         &self,
234         member: &str,
235         args: A,
236     ) -> T {
237         let (ret,): (T,) = self.method_withresult(member, args).unwrap();
238         return ret;
239     }
240 
241     /// Calls the void method and does not need to unwrap the result.
method_noreturn<A: AppendAll>(&self, member: &str, args: A)242     pub fn method_noreturn<A: AppendAll>(&self, member: &str, args: A) {
243         // The real type should be Result<((),), _> since there is no return value. However, to
244         // meet trait constraints, we just use bool and never unwrap the result. This calls the
245         // method, waits for the response but doesn't actually attempt to parse the result (on
246         // unwrap).
247         let _: Result<(bool,), _> = self.method_withresult(member, args);
248     }
249 }
250 
251 /// Implements `DBusArg` for an enum.
252 ///
253 /// A Rust enum is converted to D-Bus UINT32 type.
254 #[macro_export]
255 macro_rules! impl_dbus_arg_enum {
256     ($enum_type:ty) => {
257         impl DBusArg for $enum_type {
258             type DBusType = u32;
259             fn from_dbus(
260                 data: u32,
261                 _conn: Option<Arc<SyncConnection>>,
262                 _remote: Option<dbus::strings::BusName<'static>>,
263                 _disconnect_watcher: Option<
264                     Arc<std::sync::Mutex<dbus_projection::DisconnectWatcher>>,
265                 >,
266             ) -> Result<$enum_type, Box<dyn std::error::Error>> {
267                 match <$enum_type>::from_u32(data) {
268                     Some(x) => Ok(x),
269                     None => Err(Box::new(DBusArgError::new(format!(
270                         "error converting {} to {}",
271                         data,
272                         stringify!($enum_type)
273                     )))),
274                 }
275             }
276 
277             fn to_dbus(data: $enum_type) -> Result<u32, Box<dyn std::error::Error>> {
278                 return Ok(data.to_u32().unwrap());
279             }
280 
281             fn log(data: &$enum_type) -> String {
282                 format!("{:?}", data)
283             }
284         }
285     };
286 }
287 
288 /// Implements `DBusArg` for a type which implements TryFrom and TryInto.
289 #[macro_export]
290 macro_rules! impl_dbus_arg_from_into {
291     ($rust_type:ty, $dbus_type:ty) => {
292         impl DBusArg for $rust_type {
293             type DBusType = $dbus_type;
294             fn from_dbus(
295                 data: $dbus_type,
296                 _conn: Option<Arc<SyncConnection>>,
297                 _remote: Option<dbus::strings::BusName<'static>>,
298                 _disconnect_watcher: Option<
299                     Arc<std::sync::Mutex<dbus_projection::DisconnectWatcher>>,
300                 >,
301             ) -> Result<$rust_type, Box<dyn std::error::Error>> {
302                 match <$rust_type>::try_from(data.clone()) {
303                     Err(e) => Err(Box::new(DBusArgError::new(format!(
304                         "error converting {:?} to {:?}",
305                         data,
306                         stringify!($rust_type),
307                     )))),
308                     Ok(result) => Ok(result),
309                 }
310             }
311 
312             fn to_dbus(data: $rust_type) -> Result<$dbus_type, Box<dyn std::error::Error>> {
313                 match data.clone().try_into() {
314                     Err(e) => Err(Box::new(DBusArgError::new(format!(
315                         "error converting {:?} to {:?}",
316                         data,
317                         stringify!($dbus_type)
318                     )))),
319                     Ok(result) => Ok(result),
320                 }
321             }
322 
323             fn log(data: &$rust_type) -> String {
324                 format!("{:?}", data)
325             }
326         }
327     };
328 }
329 /// Marks a function to be implemented by dbus_projection macros.
330 #[macro_export]
331 macro_rules! dbus_generated {
332     () => {
333         // The implementation is not used but replaced by generated code.
334         // This uses panic! so that the compiler can accept it for any function
335         // return type.
336         panic!("To be implemented by dbus_projection macros");
337     };
338 }
339 
340 pub enum DBusLogOptions {
341     LogAll,
342     LogMethodNameOnly,
343 }
344 
345 pub enum DBusLogVerbosity {
346     Error,
347     Warn,
348     Info,
349     Verbose,
350 }
351 
352 pub enum DBusLog {
353     Enable(DBusLogOptions, DBusLogVerbosity),
354     Disable,
355 }
356 
357 impl DBusLog {
log(logging: DBusLog, prefix: &str, iface_name: &str, func_name: &str, param: &str)358     pub fn log(logging: DBusLog, prefix: &str, iface_name: &str, func_name: &str, param: &str) {
359         match logging {
360             Self::Enable(option, verbosity) => {
361                 let part_before_param = format!("{}: {}: {}", prefix, iface_name, func_name);
362                 let output = match option {
363                     DBusLogOptions::LogAll => format!("{}: {}", part_before_param, param),
364                     DBusLogOptions::LogMethodNameOnly => part_before_param,
365                 };
366 
367                 match verbosity {
368                     DBusLogVerbosity::Error => log::error!("{}", output),
369                     DBusLogVerbosity::Warn => log::warn!("{}", output),
370                     DBusLogVerbosity::Info => log::info!("{}", output),
371                     DBusLogVerbosity::Verbose => log::debug!("{}", output),
372                 }
373             }
374             Self::Disable => {}
375         }
376     }
377 }
378