• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 /// A D-Bus "NameOwnerChanged" handler that continuously monitors client disconnects.
58 ///
59 /// When the watched bus address disconnects, all the callbacks associated with it are called with
60 /// their associated ids.
61 pub struct DisconnectWatcher {
62     /// Global counter to provide a unique id every time `get_next_id` is called.
63     next_id: u32,
64 
65     /// Map of disconnect callbacks by bus address and callback id.
66     callbacks: Arc<Mutex<HashMap<BusName<'static>, HashMap<u32, Box<dyn Fn(u32) + Send>>>>>,
67 }
68 
69 impl DisconnectWatcher {
70     /// Creates a new DisconnectWatcher with empty callbacks.
new() -> DisconnectWatcher71     pub fn new() -> DisconnectWatcher {
72         DisconnectWatcher { next_id: 0, callbacks: Arc::new(Mutex::new(HashMap::new())) }
73     }
74 
75     /// Get the next unique id for this watcher.
get_next_id(&mut self) -> u3276     fn get_next_id(&mut self) -> u32 {
77         self.next_id = self.next_id + 1;
78         self.next_id
79     }
80 }
81 
82 impl DisconnectWatcher {
83     /// Adds a client address to be monitored for disconnect events.
add(&mut self, address: BusName<'static>, callback: Box<dyn Fn(u32) + Send>) -> u3284     pub fn add(&mut self, address: BusName<'static>, callback: Box<dyn Fn(u32) + Send>) -> u32 {
85         if !self.callbacks.lock().unwrap().contains_key(&address) {
86             self.callbacks.lock().unwrap().insert(address.clone(), HashMap::new());
87         }
88 
89         let id = self.get_next_id();
90         (*self.callbacks.lock().unwrap().get_mut(&address).unwrap()).insert(id, callback);
91 
92         return id;
93     }
94 
95     /// Sets up the D-Bus handler that monitors client disconnects.
setup_watch(&mut self, conn: Arc<SyncConnection>)96     pub async fn setup_watch(&mut self, conn: Arc<SyncConnection>) {
97         let mr = MatchRule::new_signal("org.freedesktop.DBus", "NameOwnerChanged");
98 
99         conn.add_match_no_cb(&mr.match_str()).await.unwrap();
100         let callbacks_map = self.callbacks.clone();
101         conn.start_receive(
102             mr,
103             Box::new(move |msg, _conn| {
104                 // The args are "address", "old address", "new address".
105                 // https://dbus.freedesktop.org/doc/dbus-specification.html#bus-messages-name-owner-changed
106                 let (addr, old, new) = msg.get3::<String, String, String>();
107 
108                 if addr.is_none() || old.is_none() || new.is_none() {
109                     return true;
110                 }
111 
112                 if old.unwrap().eq("") || !new.unwrap().eq("") {
113                     return true;
114                 }
115 
116                 // If old address exists but new address is empty, that means that client is
117                 // disconnected. So call the registered callbacks to be notified of this client
118                 // disconnect.
119                 let addr = BusName::new(addr.unwrap()).unwrap().into_static();
120                 if !callbacks_map.lock().unwrap().contains_key(&addr) {
121                     return true;
122                 }
123 
124                 for (id, callback) in callbacks_map.lock().unwrap()[&addr].iter() {
125                     callback(*id);
126                 }
127 
128                 callbacks_map.lock().unwrap().remove(&addr);
129 
130                 true
131             }),
132         );
133     }
134 
135     /// Removes callback by id if owned by the specific busname.
136     ///
137     /// If the callback can be removed, the callback will be called before being removed.
remove(&mut self, address: BusName<'static>, target_id: u32) -> bool138     pub fn remove(&mut self, address: BusName<'static>, target_id: u32) -> bool {
139         if !self.callbacks.lock().unwrap().contains_key(&address) {
140             return false;
141         }
142 
143         let mut callbacks = self.callbacks.lock().unwrap();
144         match callbacks.get(&address).and_then(|m| m.get(&target_id)) {
145             Some(cb) => {
146                 cb(target_id);
147                 let _ = callbacks.get_mut(&address).and_then(|m| m.remove(&target_id));
148                 true
149             }
150             None => false,
151         }
152     }
153 }
154 
155 /// A client proxy to conveniently call API methods generated with the
156 /// [`generate_dbus_interface_client`](dbus_macros::generate_dbus_interface_client) macro.
157 #[derive(Clone)]
158 pub struct ClientDBusProxy {
159     conn: Arc<SyncConnection>,
160     bus_name: String,
161     objpath: dbus::Path<'static>,
162     interface: String,
163 }
164 
165 impl ClientDBusProxy {
new( conn: Arc<SyncConnection>, bus_name: String, objpath: dbus::Path<'static>, interface: String, ) -> Self166     pub fn new(
167         conn: Arc<SyncConnection>,
168         bus_name: String,
169         objpath: dbus::Path<'static>,
170         interface: String,
171     ) -> Self {
172         Self { conn, bus_name, objpath, interface }
173     }
174 
create_proxy(&self) -> dbus::nonblock::Proxy<Arc<SyncConnection>>175     fn create_proxy(&self) -> dbus::nonblock::Proxy<Arc<SyncConnection>> {
176         let conn = self.conn.clone();
177         dbus::nonblock::Proxy::new(
178             self.bus_name.clone(),
179             self.objpath.clone(),
180             std::time::Duration::from_secs(2),
181             conn,
182         )
183     }
184 
185     /// 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>186     pub async fn async_method<
187         A: AppendAll,
188         T: 'static + dbus::arg::Arg + for<'z> dbus::arg::Get<'z>,
189     >(
190         &self,
191         member: &str,
192         args: A,
193     ) -> Result<(T,), dbus::Error> {
194         let proxy = self.create_proxy();
195         proxy.method_call(self.interface.clone(), member, args).await
196     }
197 
198     /// 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>199     pub async fn async_method_noreturn<A: AppendAll>(
200         &self,
201         member: &str,
202         args: A,
203     ) -> Result<(), dbus::Error> {
204         let proxy = self.create_proxy();
205         proxy.method_call(self.interface.clone(), member, args).await
206     }
207 
208     /// 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>209     pub fn method_withresult<
210         A: AppendAll,
211         T: 'static + dbus::arg::Arg + for<'z> dbus::arg::Get<'z>,
212     >(
213         &self,
214         member: &str,
215         args: A,
216     ) -> Result<(T,), dbus::Error> {
217         let proxy = self.create_proxy();
218         // We know that all APIs return immediately, so we can block on it for simplicity.
219         return futures::executor::block_on(async {
220             proxy.method_call(self.interface.clone(), member, args).await
221         });
222     }
223 
224     /// 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, ) -> T225     pub fn method<A: AppendAll, T: 'static + dbus::arg::Arg + for<'z> dbus::arg::Get<'z>>(
226         &self,
227         member: &str,
228         args: A,
229     ) -> T {
230         let (ret,): (T,) = self.method_withresult(member, args).unwrap();
231         return ret;
232     }
233 
234     /// Calls the void method and does not need to unwrap the result.
method_noreturn<A: AppendAll>(&self, member: &str, args: A)235     pub fn method_noreturn<A: AppendAll>(&self, member: &str, args: A) {
236         // The real type should be Result<((),), _> since there is no return value. However, to
237         // meet trait constraints, we just use bool and never unwrap the result. This calls the
238         // method, waits for the response but doesn't actually attempt to parse the result (on
239         // unwrap).
240         let _: Result<(bool,), _> = self.method_withresult(member, args);
241     }
242 }
243 
244 /// Implements `DBusArg` for an enum.
245 ///
246 /// A Rust enum is converted to D-Bus INT32 type.
247 #[macro_export]
248 macro_rules! impl_dbus_arg_enum {
249     ($enum_type:ty) => {
250         impl DBusArg for $enum_type {
251             type DBusType = u32;
252             fn from_dbus(
253                 data: u32,
254                 _conn: Option<Arc<SyncConnection>>,
255                 _remote: Option<dbus::strings::BusName<'static>>,
256                 _disconnect_watcher: Option<
257                     Arc<std::sync::Mutex<dbus_projection::DisconnectWatcher>>,
258                 >,
259             ) -> Result<$enum_type, Box<dyn std::error::Error>> {
260                 match <$enum_type>::from_u32(data) {
261                     Some(x) => Ok(x),
262                     None => Err(Box::new(DBusArgError::new(String::from(format!(
263                         "error converting {} to {}",
264                         data,
265                         stringify!($enum_type)
266                     ))))),
267                 }
268             }
269 
270             fn to_dbus(data: $enum_type) -> Result<u32, Box<dyn std::error::Error>> {
271                 return Ok(data.to_u32().unwrap());
272             }
273         }
274     };
275 }
276 
277 /// Implements `DBusArg` for a type which implements TryFrom and TryInto.
278 #[macro_export]
279 macro_rules! impl_dbus_arg_from_into {
280     ($rust_type:ty, $dbus_type:ty) => {
281         impl DBusArg for $rust_type {
282             type DBusType = $dbus_type;
283             fn from_dbus(
284                 data: $dbus_type,
285                 _conn: Option<Arc<SyncConnection>>,
286                 _remote: Option<dbus::strings::BusName<'static>>,
287                 _disconnect_watcher: Option<
288                     Arc<std::sync::Mutex<dbus_projection::DisconnectWatcher>>,
289                 >,
290             ) -> Result<$rust_type, Box<dyn std::error::Error>> {
291                 match <$rust_type>::try_from(data.clone()) {
292                     Err(e) => Err(Box::new(DBusArgError::new(String::from(format!(
293                         "error converting {:?} to {:?}",
294                         data,
295                         stringify!($rust_type),
296                     ))))),
297                     Ok(result) => Ok(result),
298                 }
299             }
300 
301             fn to_dbus(data: $rust_type) -> Result<$dbus_type, Box<dyn std::error::Error>> {
302                 match data.clone().try_into() {
303                     Err(e) => Err(Box::new(DBusArgError::new(String::from(format!(
304                         "error converting {:?} to {:?}",
305                         data,
306                         stringify!($dbus_type)
307                     ))))),
308                     Ok(result) => Ok(result),
309                 }
310             }
311         }
312     };
313 }
314 /// Marks a function to be implemented by dbus_projection macros.
315 #[macro_export]
316 macro_rules! dbus_generated {
317     () => {
318         // The implementation is not used but replaced by generated code.
319         // This uses panic! so that the compiler can accept it for any function
320         // return type.
321         panic!("To be implemented by dbus_projection macros");
322     };
323 }
324