Debian Codegraph @

src/backend/xdg_desktop_portal/portal/libdbus.rs

raw
1 use std::{
2 ffi::{c_char, c_void, CStr, CString},
3 fmt,
4 marker::PhantomData,
5 ptr::NonNull,
6 };
7
8 use super::ffi;
9 use libc::c_int;
10
11 macro_rules! f {
12 ($f: ident) => {
13 (ffi::Libdbus::get().$f)
14 };
15 }
16
17 pub struct DbusError(ffi::DBusError);
18
19 impl DbusError {
20 pub fn new() -> Self {
21 unsafe {
22 let mut err: ffi::DBusError = std::mem::zeroed();
23 f!(dbus_error_init)(&mut err);
24 Self(err)
25 }
26 }
27
28 pub fn as_ptr(&mut self) -> &mut ffi::DBusError {
29 &mut self.0
30 }
31
32 pub fn is_err(&self) -> bool {
33 self.name().is_some()
34 }
35
36 pub fn name(&self) -> Option<&CStr> {
37 if self.0.name.is_null() {
38 None
39 } else {
40 unsafe { Some(CStr::from_ptr(self.0.name)) }
41 }
42 }
43
44 pub fn message(&self) -> Option<&CStr> {
45 if self.0.message.is_null() {
46 None
47 } else {
48 unsafe { Some(CStr::from_ptr(self.0.message)) }
49 }
50 }
51 }
52
53 impl fmt::Display for DbusError {
54 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55 let name = self.name();
56 let message = self.message();
57 write!(f, "{name:?}: {message:?}")
58 }
59 }
60
61 impl Drop for DbusError {
62 fn drop(&mut self) {
63 unsafe {
64 f!(dbus_error_free)(self.as_ptr());
65 }
66 }
67 }
68
69 pub struct Connection {
70 conn: NonNull<ffi::DBusConnection>,
71 err: DbusError,
72 }
73
74 impl Connection {
75 pub fn new() -> Option<Self> {
76 if ffi::Libdbus::open_libdbus().is_none() {
77 log::error!("Can't connect to a portal: libdbus-1.so not found");
78 return None;
79 }
80
81 let mut err = DbusError::new();
82 unsafe {
83 let ptr = f!(dbus_bus_get_private)(ffi::DBusBusType::Session, err.as_ptr());
84
85 if err.is_err() {
86 log::error!("Failed to connect to session bus: {err}");
87 return None;
88 }
89
90 Some(Self {
91 conn: NonNull::new(ptr)?,
92 err,
93 })
94 }
95 }
96
97 pub fn err(&mut self) -> &mut DbusError {
98 &mut self.err
99 }
100
101 pub fn err_ptr(&mut self) -> &mut ffi::DBusError {
102 self.err.as_ptr()
103 }
104
105 pub fn as_ptr(&self) -> *mut ffi::DBusConnection {
106 self.conn.as_ptr()
107 }
108
109 pub fn get_unique_name(&mut self) -> CString {
110 unsafe { CStr::from_ptr(f!(dbus_bus_get_unique_name)(self.as_ptr())).to_owned() }
111 }
112
113 pub fn add_match(&mut self, match_rule: &CStr) {
114 unsafe {
115 f!(dbus_bus_add_match)(self.as_ptr(), match_rule.as_ptr(), self.err_ptr());
116 }
117 }
118
119 pub fn flush(&self) {
120 unsafe {
121 f!(dbus_connection_flush)(self.as_ptr());
122 }
123 }
124
125 pub fn read_write(&self, timeout_milliseconds: c_int) {
126 unsafe {
127 f!(dbus_connection_read_write)(self.as_ptr(), timeout_milliseconds);
128 }
129 }
130
131 pub fn pop_message(&self) -> Option<Message> {
132 unsafe { Message::new(f!(dbus_connection_pop_message)(self.as_ptr())) }
133 }
134
135 pub fn send_and_block(&mut self, msg: &Message) -> Option<Message> {
136 unsafe {
137 Message::new(f!(dbus_connection_send_with_reply_and_block)(
138 self.as_ptr(),
139 msg.as_ptr(),
140 -1,
141 self.err_ptr(),
142 ))
143 }
144 }
145 }
146
147 impl Drop for Connection {
148 fn drop(&mut self) {
149 unsafe {
150 f!(dbus_connection_close)(self.as_ptr());
151 }
152 }
153 }
154
155 pub struct Message(NonNull<ffi::DBusMessage>);
156
157 impl Message {
158 pub fn new(ptr: *mut ffi::DBusMessage) -> Option<Self> {
159 NonNull::new(ptr).map(Self)
160 }
161
162 pub fn new_method_call(
163 destination: &CStr,
164 path: &CStr,
165 iface: &CStr,
166 method: &CStr,
167 ) -> Option<Self> {
168 unsafe {
169 Self::new(f!(dbus_message_new_method_call)(
170 destination.as_ptr(),
171 path.as_ptr(),
172 iface.as_ptr(),
173 method.as_ptr(),
174 ))
175 }
176 }
177
178 pub fn as_ptr(&self) -> *mut ffi::DBusMessage {
179 self.0.as_ptr()
180 }
181
182 pub fn is_signal(&self, iface: &CStr, signal_name: &CStr) -> bool {
183 unsafe {
184 f!(dbus_message_is_signal)(self.as_ptr(), iface.as_ptr(), signal_name.as_ptr()) == 1
185 }
186 }
187
188 pub fn get_path(&self) -> Option<&CStr> {
189 unsafe {
190 let path = f!(dbus_message_get_path)(self.as_ptr());
191 if path.is_null() {
192 None
193 } else {
194 Some(CStr::from_ptr(path))
195 }
196 }
197 }
198 }
199
200 impl Drop for Message {
201 fn drop(&mut self) {
202 unsafe {
203 f!(dbus_message_unref)(self.as_ptr());
204 }
205 }
206 }
207
208 pub struct MessageIter<'a>(ffi::DBusMessageIter, #[allow(unused)] &'a PhantomData<()>);
209
210 impl<'a> MessageIter<'a> {
211 pub fn new() -> Self {
212 Self(unsafe { std::mem::zeroed() }, &PhantomData)
213 }
214
215 pub fn from_msg(msg: &'a Message) -> Self {
216 let mut iter = Self::new();
217 iter.init(msg);
218 iter
219 }
220
221 pub fn iter_recurse(&mut self) -> Self {
222 unsafe {
223 let mut new = Self::new();
224 f!(dbus_message_iter_recurse)(self.as_ptr(), new.as_ptr());
225 new
226 }
227 }
228
229 pub fn init(&mut self, msg: &'a Message) {
230 unsafe {
231 assert_eq!(f!(dbus_message_iter_init)(msg.as_ptr(), self.as_ptr()), 1);
232 }
233 }
234
235 pub fn as_ptr(&mut self) -> &mut ffi::DBusMessageIter {
236 &mut self.0
237 }
238
239 pub fn next(&mut self) -> bool {
240 unsafe { f!(dbus_message_iter_next)(self.as_ptr()) != 0 }
241 }
242
243 pub fn get_arg_type(&mut self) -> c_int {
244 unsafe { f!(dbus_message_iter_get_arg_type)(self.as_ptr()) }
245 }
246
247 pub unsafe fn get_basic(&mut self, out: *mut c_void) {
248 unsafe {
249 f!(dbus_message_iter_get_basic)(self.as_ptr(), out);
250 }
251 }
252
253 pub fn get_u32(&mut self) -> Option<u32> {
254 if self.get_arg_type() != ffi::DBUS_TYPE_UINT32 {
255 return None;
256 }
257 let mut out = u32::MAX;
258 unsafe {
259 self.get_basic(&mut out as *mut u32 as *mut _);
260 }
261 Some(out)
262 }
263
264 pub fn get_object_path(&mut self) -> Option<CString> {
265 if self.get_arg_type() != ffi::DBUS_TYPE_OBJECT_PATH {
266 return None;
267 }
268 unsafe { self.get_basic_str() }
269 }
270
271 pub fn get_string(&mut self) -> Option<CString> {
272 if self.get_arg_type() != ffi::DBUS_TYPE_STRING {
273 return None;
274 }
275 unsafe { self.get_basic_str() }
276 }
277
278 pub fn get_string_array(&mut self) -> Vec<CString> {
279 let mut out = Vec::new();
280
281 if self.get_arg_type() == ffi::DBUS_TYPE_ARRAY {
282 let mut array_iter = self.iter_recurse();
283 while array_iter.get_arg_type() == ffi::DBUS_TYPE_STRING {
284 if let Some(item) = array_iter.get_string() {
285 out.push(item);
286 } else {
287 log::error!("Wrong type in a string array")
288 }
289 array_iter.next();
290 }
291 }
292
293 out
294 }
295
296 unsafe fn get_basic_str(&mut self) -> Option<CString> {
297 unsafe {
298 let mut out: *const c_char = std::ptr::null_mut();
299 self.get_basic(&mut out as *mut *const c_char as *mut _);
300
301 if out.is_null() {
302 None
303 } else {
304 Some(CStr::from_ptr(out).to_owned())
305 }
306 }
307 }
308
309 pub fn init_append(msg: &'a mut Message) -> Self {
310 let mut new = Self::new();
311 unsafe { f!(dbus_message_iter_init_append)(msg.as_ptr(), new.as_ptr()) };
312 new
313 }
314
315 pub fn append_basic(&mut self, ty: c_int, value: *const c_void) {
316 unsafe {
317 assert_eq!(
318 f!(dbus_message_iter_append_basic)(self.as_ptr(), ty, value,),
319 1
320 );
321 }
322 }
323
324 pub fn append_string(&mut self, value: &CStr) {
325 self.append_basic(
326 ffi::DBUS_TYPE_STRING,
327 &value.as_ptr() as *const _ as *const _,
328 );
329 }
330
331 pub fn append_byte(&mut self, value: u8) {
332 self.append_basic(ffi::DBUS_TYPE_BYTE, &value as *const u8 as *const _);
333 }
334
335 pub fn append_u32(&mut self, value: u32) {
336 self.append_basic(ffi::DBUS_TYPE_UINT32, &value as *const _ as *const _);
337 }
338
339 pub fn append_bool(&mut self, value: bool) {
340 let value: u32 = if value { 1 } else { 0 };
341 self.append_basic(ffi::DBUS_TYPE_BOOLEAN, &value as *const _ as *const _);
342 }
343
344 pub fn open_container(&mut self, ty: c_int, signature: Option<&CStr>) -> Self {
345 unsafe {
346 let mut out = Self::new();
347 assert_eq!(
348 f!(dbus_message_iter_open_container)(
349 self.as_ptr(),
350 ty,
351 signature.map(|s| s.as_ptr()).unwrap_or_default(),
352 out.as_ptr(),
353 ),
354 1
355 );
356 out
357 }
358 }
359
360 pub fn close_container(&mut self, mut sub: Self) {
361 unsafe {
362 assert_eq!(
363 f!(dbus_message_iter_close_container)(self.as_ptr(), sub.as_ptr()),
364 1
365 );
366 }
367 }
368
369 pub fn with_container<T>(
370 &mut self,
371 ty: c_int,
372 signature: Option<&CStr>,
373 f: impl FnOnce(&mut Self) -> T,
374 ) -> T {
375 let mut container = self.open_container(ty, signature);
376 let res = f(&mut container);
377 self.close_container(container);
378 res
379 }
380
381 pub fn with_dict_entry<T>(
382 &mut self,
383 key: &CStr,
384 variant_signature: &CStr,
385 f: impl FnOnce(&mut Self) -> T,
386 ) -> T {
387 self.with_container(ffi::DBUS_TYPE_DICT_ENTRY, None, |entry| {
388 entry.append_string(key);
389 entry.with_container(ffi::DBUS_TYPE_VARIANT, Some(variant_signature), |variant| {
390 f(variant)
391 })
392 })
393 }
394 }