1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-transport-kdbus.c kdbus subclasses of DBusTransport
4 * Copyright (C) 2002, 2003, 2004, 2006 Red Hat Inc
5 * Copyright (C) 2013 Samsung Electronics
7 * Licensed under the Academic Free License version 2.1
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version and under the terms of the GNU
13 * Lesser General Public License as published by the
14 * Free Software Foundation; either version 2.1 of the License, or (at
15 * your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 #include "dbus-transport.h"
29 #include "dbus-transport-kdbus.h"
30 #include "dbus-transport-protected.h"
31 #include "dbus-connection-internal.h"
32 #include "dbus-marshal-gvariant.h"
33 #include "dbus-marshal-validate.h"
34 #include "dbus-asv-util.h"
36 #include "dbus-watch.h"
37 #include "dbus-errors.h"
39 #include "kdbus-common.h"
40 #include "dbus-protocol-gvariant.h"
41 #include <linux/types.h>
49 #include <sys/syscall.h>
52 #include <dbuspolicy/libdbuspolicy1.h>
53 #include "dbus-marshal-header.h"
54 #include "dbus-protocol-gvariant.h"
56 #include "dbus-sysdeps-unix.h"
58 #include <linux/version.h>
59 #if LINUX_VERSION_CODE < KERNEL_VERSION(3, 17, 0)
60 # if defined(__arm__) || defined(__aarch64__)
61 # define __NR_memfd_create 385
62 # elif defined(__i386__)
63 # define __NR_memfd_create 279
65 # error "Architecture not supported"
68 # include <linux/memfd.h>
71 #ifdef DBUS_ENABLE_VERBOSE_MODE
75 /* FIXME shouldn't it be in fcntl.h header file? copied from systemd's missing.h */
76 #ifndef F_LINUX_SPECIFIC_BASE
77 #define F_LINUX_SPECIFIC_BASE 1024
81 #define F_ADD_SEALS (F_LINUX_SPECIFIC_BASE + 9)
82 #define F_GET_SEALS (F_LINUX_SPECIFIC_BASE + 10)
84 #define F_SEAL_SEAL 0x0001 /* prevent further seals from being set */
85 #define F_SEAL_SHRINK 0x0002 /* prevent file from shrinking */
86 #define F_SEAL_GROW 0x0004 /* prevent file from growing */
87 #define F_SEAL_WRITE 0x0008 /* prevent writes */
91 #define MFD_CLOEXEC 0x0001U
94 #ifndef MFD_ALLOW_SEALING
95 #define MFD_ALLOW_SEALING 0x0002U
98 /* ALIGN8 and KDBUS_FOREACH taken from systemd */
99 #define ALIGN8(l) (((l) + 7) & ~7)
100 #define KDBUS_FOREACH(iter, first, _size) \
101 for (iter = (first); \
102 ((uint8_t *)(iter) < (uint8_t *)(first) + (_size)) && \
103 ((uint8_t *)(iter) >= (uint8_t *)(first)); \
104 iter = (void*)(((uint8_t *)iter) + ALIGN8((iter)->size)))
105 #define KDBUS_DEFAULT_TIMEOUT_NS 50000000000LLU
108 * @defgroup DBusTransportKdbus DBusTransport implementations for kdbus
109 * @ingroup DBusInternals
110 * @brief Implementation details of DBusTransport on kdbus
115 /** Default Size of the memory area for received non-memfd messages. */
116 #define RECEIVE_POOL_SIZE_DEFAULT_SIZE (16 * 1024LU * 1024LU)
117 /** Name of environmental variable to define receive pool size*/
118 #define RECEIVE_POOL_SIZE_ENV_VAR_NAME "KDBUS_MEMORY_POOL_SIZE"
119 /** Max size of pool size in megabytes*/
120 #define RECEIVE_POOL_SIZE_MAX_MBYTES 64
121 /** Min size of pool size in kilobytes*/
122 #define RECEIVE_POOL_SIZE_MIN_KBYTES 16
124 /** Over this memfd is used to send (if it is not broadcast). */
125 #define MEMFD_SIZE_THRESHOLD (512 * 1024LU)
127 /** Define max bytes read or written in one iteration.
128 * This is to avoid blocking on reading or writing for too long. It is checked after each message is sent or received,
129 * so if message is bigger than MAX_BYTES_PER_ITERATION it will be handled in one iteration, but sending/writing
130 * will break after that message.
132 #define MAX_BYTES_PER_ITERATION 16384
134 #if (MEMFD_SIZE_THRESHOLD > KDBUS_MSG_MAX_PAYLOAD_VEC_SIZE)
135 #error Memfd size threshold higher than max kdbus message payload vector size
138 /** Enables verbosing more information about kdbus message.
139 * Works only if DBUS_VERBOSE=1 is used.
141 #define KDBUS_MSG_DECODE_DEBUG 0
144 * Opaque object representing a transport.
146 typedef struct DBusTransportKdbus DBusTransportKdbus;
149 * Implementation details of DBusTransportKdbus. All members are private.
151 struct DBusTransportKdbus
153 DBusTransport base; /**< Parent instance */
154 kdbus_t *kdbus; /**< kdbus data for low level operations */
155 DBusWatch *read_watch; /**< Watch for readability. */
156 DBusWatch *write_watch; /**< Watch for writability. */
158 int max_bytes_read_per_iteration; /**< To avoid blocking too long. */
159 int max_bytes_written_per_iteration; /**< To avoid blocking too long. */
161 char* my_DBus_unique_name; /**< unique name in DBus string format - :1.x , where x is kdbus id*/
162 char* activator; /**< well known name for activator */
163 Matchmaker *matchmaker; /**< for match rules management */
164 dbus_uint32_t client_serial; /**< serial number for messages synthesized by library*/
171 * Creates unique name string frong unique id.
173 * @param id unique id
174 * @returns allocated string with unique name
176 * Caller has to free allocated string with free.
179 create_unique_name_from_unique_id (unsigned long long id)
182 if (asprintf (&str, ":1.%llu", id) == -1)
188 * Puts locally generated message into received messages queue
189 * @param message message that will be added
190 * @param connection connection to which message will be added
191 * @returns TRUE on success, FALSE on memory allocation error
194 add_message_to_received (DBusMessage *message,
195 DBusConnection *connection)
197 DBusList *message_link;
199 message_link = _dbus_list_alloc_link (message);
200 if (message_link == NULL)
202 dbus_message_unref (message);
206 dbus_message_lock (message);
208 _dbus_connection_queue_synthesized_message_link (connection, message_link);
213 reply_with_error_preset_sender (const char *error_type,
214 const char *template,
216 DBusMessage *message,
219 DBusMessage *errMessage;
220 char* error_msg = "";
224 size_t len = strlen (template) + strlen (object) + 1;
225 error_msg = alloca (len);
226 snprintf (error_msg, len, template, object);
229 error_msg = (char*)object;
231 errMessage = _dbus_generate_local_error_message ( dbus_message_get_serial (message),
235 if (errMessage == NULL)
239 dbus_message_set_sender (errMessage, sender);
245 * Generates local error message as a reply to message given as parameter
246 * and adds generated error message to received messages queue.
247 * @param error_type type of error, preferably DBUS_ERROR_(...)
248 * @param template Template of error description. It can has formatting
249 * characters to print object string into it. Can be NULL.
250 * @param object String to print into error description. Can be NULL.
251 * If object is not NULL while template is NULL, the object string
252 * will be the only error description.
253 * @param message Message for which the error reply is generated.
254 * @returns local error message on success, otherwise NULL
257 reply_with_error (const char *error_type,
258 const char *template,
260 DBusMessage *message)
262 return reply_with_error_preset_sender (error_type, template,
263 object, message, NULL);
267 * Generates reply to the message given as a parameter with one item in the reply body
268 * and adds generated reply message to received messages queue.
269 * @param message The message we are replying to.
270 * @param data_type Type of data sent in the reply.Use DBUS_TYPE_(...)
271 * @param pData Address of data sent in the reply.
272 * @returns generated reply on success, otherwise NULL
275 reply_1_data (DBusMessage *message,
279 DBusMessageIter args;
282 reply = dbus_message_new_method_return (message);
286 if (!dbus_message_set_sender (reply, DBUS_SERVICE_DBUS))
289 dbus_message_iter_init_append (reply, &args);
290 if (!dbus_message_iter_append_basic (&args, data_type, pData))
296 dbus_message_unref (reply);
302 reply_fixed_array (DBusMessage *message,
307 DBusMessageIter args, array_iter;
310 reply = dbus_message_new_method_return (message);
314 if (!dbus_message_set_sender (reply, DBUS_SERVICE_DBUS))
317 dbus_message_iter_init_append (reply, &args);
319 if (!dbus_message_iter_open_container (&args,
321 DBUS_TYPE_BYTE_AS_STRING,
325 if (!dbus_message_iter_append_fixed_array (&array_iter, element_type, &data, n_elements))
328 if (!dbus_message_iter_close_container (&args, &array_iter))
334 dbus_message_iter_abandon_container (&args, &array_iter);
337 dbus_message_unref (reply);
342 * Retrieves file descriptor to memory pool from kdbus module and stores
343 * it in kdbus_transport->memfd. It is then used to send large message.
344 * Triggered when message payload is over MEMFD_SIZE_THRESHOLD
345 * @param kdbus_transport DBusTransportKdbus transport structure
346 * @returns 0 on success, otherwise -1
349 kdbus_acquire_memfd ( void )
353 /* FIXME add HAVE_MEMFD_CREATE */
354 if ((fd = syscall (__NR_memfd_create, "kdbus", MFD_ALLOW_SEALING | MFD_CLOEXEC )) < 0)
356 _dbus_verbose ("memfd_create failed (%d): %m\n", fd);
359 _dbus_verbose ("%s: memfd=%d\n", __FUNCTION__, fd);
364 bloom_add_pair (kdbus_bloom_data_t *bloom_data,
366 const char *parameter,
375 size = strlen (parameter) + strlen (value) + 1;
379 snprintf (buf, size + 1, "%s:%s", parameter, value);
380 _kdbus_bloom_add_data (kdbus, bloom_data, buf, size);
384 bloom_add_prefixes (kdbus_bloom_data_t *bloom_data,
386 const char *parameter,
393 size = strlen (parameter) + strlen (value) + 1;
397 snprintf (buf, size + 1, "%s:%s", parameter, value);
402 last_sep = strrchr (buf, separator);
403 if (!last_sep || last_sep == buf)
407 _kdbus_bloom_add_data (kdbus, bloom_data, buf, last_sep-buf);
412 setup_bloom_filter_for_message (DBusMessage *msg,
414 struct kdbus_bloom_filter *bloom_filter)
416 kdbus_bloom_data_t *bloom_data;
419 DBusMessageIter args;
422 _dbus_assert (bloom_filter);
424 bloom_data = _kdbus_bloom_filter_get_data (bloom_filter);
426 bloom_add_pair (bloom_data,
429 dbus_message_type_to_string (dbus_message_get_type (msg)));
431 bloom_add_pair (bloom_data, kdbus, "interface", dbus_message_get_interface (msg));
432 bloom_add_pair (bloom_data, kdbus, "member", dbus_message_get_member (msg));
433 str = dbus_message_get_path (msg);
436 bloom_add_pair (bloom_data, kdbus, "path", str);
437 bloom_add_pair (bloom_data, kdbus, "path-slash-prefix", str);
438 bloom_add_prefixes (bloom_data, kdbus, "path-slash-prefix", str, '/');
441 if (!dbus_message_iter_init (msg, &args))
444 for (i = 0; i < 64; i++)
447 char buf[sizeof ("arg")-1 + 2 + sizeof ("-slash-prefix")];
451 type = dbus_message_iter_get_arg_type (&args);
452 if (type != DBUS_TYPE_STRING &&
453 type != DBUS_TYPE_OBJECT_PATH &&
454 type != DBUS_TYPE_SIGNATURE)
457 dbus_message_iter_get_basic (&args, &str);
459 snprintf (buf, sizeof (buf), "arg%d", i);
461 bloom_add_pair (bloom_data, kdbus, buf, str);
463 /* point e to end of string, we will add suffixes */
466 /* we need remaining length of the buffer */
467 len = sizeof (buf) - len;
469 strncpy (e, "-dot-prefix", len);
470 bloom_add_prefixes (bloom_data, kdbus, buf, str, '.');
471 strncpy (e, "-slash-prefix", len);
472 bloom_add_prefixes (bloom_data, kdbus, buf, str, '/');
474 if (!dbus_message_iter_next (&args))
482 * Checks if a string is a unique name or well known name.
484 * @param name a valid D-Bus name
485 * @returns 0 for well-known names, otherwise unique id
488 parse_name (const char *name)
490 dbus_uint64_t unique_id = 0;
492 /* if name is unique name it must be converted to unique id */
493 if (strncmp (name, ":1.", 3) == 0)
496 unique_id = strtoull (&name[3], &endptr, 10);
498 if (unique_id == 0 || *endptr != '\0' || errno == ERANGE)
506 prepare_mfd (int memfd,
512 _dbus_verbose ("sending data via memfd\n");
515 wr = write (memfd, body, body_size);
518 _dbus_verbose ("writing to memfd failed: (%d) %m\n", errno);
525 // seal data - kdbus module needs it
526 if (fcntl (memfd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE | F_SEAL_SEAL) < 0)
528 _dbus_verbose ("memfd sealing failed: %d (%m)\n", errno);
535 send_message (DBusTransportKdbus *transport,
536 struct kdbus_msg *kdbus_msg,
538 const char *destination,
539 dbus_bool_t is_auto_start,
540 struct kdbus_msg **kdbus_msg_reply,
544 dbus_uint64_t flags = 0;
547 flags |= KDBUS_SEND_SYNC_REPLY;
549 ret = _kdbus_send (transport->kdbus,
555 _dbus_verbose ("kdbus error sending message: err %d (%s)\n", ret, _dbus_strerror (ret) );
559 case ENXIO: /* no such id on the bus */
561 dbus_set_error (error,
562 DBUS_ERROR_NAME_HAS_NO_OWNER,
563 "Name \"%s\" does not exist",
569 /* when well known name is not available on the bus */
571 dbus_set_error (error,
572 DBUS_ERROR_SERVICE_UNKNOWN,
573 "The name %s was not provided by any .service files",
576 dbus_set_error (error,
577 DBUS_ERROR_NAME_HAS_NO_OWNER,
578 "Name \"%s\" does not exist",
583 dbus_set_error (error,
584 DBUS_ERROR_LIMITS_EXCEEDED,
585 "The maximum number of pending replies per connection has been reached");
590 dbus_set_error (error,
591 DBUS_ERROR_LIMITS_EXCEEDED,
592 "No space in receiver's buffer");
596 dbus_set_error (error,
598 "Connection does not receive a reply");
602 dbus_set_error (error,
604 "Something went wrong: %s",
605 _dbus_strerror (ret));
615 kdbus_close_message (DBusTransportKdbus *transport, struct kdbus_msg *msg)
617 struct kdbus_item *item;
619 KDBUS_ITEM_FOREACH (item, msg, items)
621 if (item->type == KDBUS_ITEM_PAYLOAD_MEMFD)
622 close (item->memfd.fd);
625 _kdbus_free_mem (transport->kdbus, msg);
628 #ifdef DBUS_ENABLE_VERBOSE_MODE
630 debug_c_str (const char *msg, const char *str, int len)
633 fprintf (stderr, "%s\n", msg);
634 for (i = 0; i < len; i++)
636 fprintf (stderr, "%02x ", (unsigned char)str[i]);
637 if (i%16==15) fprintf (stderr, "\n");
639 fprintf (stderr, "\n");
643 debug_str (const char *msg, const DBusString *str)
645 debug_c_str (msg, _dbus_string_get_const_data (str), _dbus_string_get_length (str));
650 can_send (DBusTransportKdbus *transport,
651 DBusMessage *message)
653 int ret = DBUSPOLICY_RESULT_ALLOW;
656 if (NULL != transport->policy)
658 dbus_uint32_t reply_serial = dbus_message_get_reply_serial (message);
660 /* If reply_serial is non-zero, then it is a reply - just send it.
661 * Otherwise - check the policy.
663 if (0 == reply_serial)
664 ret = dbuspolicy1_check_out (transport->policy,
665 dbus_message_get_destination (message),
666 dbus_message_get_sender (message),
667 dbus_message_get_path (message),
668 dbus_message_get_interface (message),
669 dbus_message_get_member (message),
670 dbus_message_get_type (message),
671 dbus_message_get_error_name (message),
673 !dbus_message_get_no_reply (message));
680 /* function prototypes */
681 static int kdbus_message_size (const struct kdbus_msg *msg,
683 static int kdbus_decode_dbus_message (const struct kdbus_msg *msg,
685 DBusTransportKdbus *kdbus_transport,
690 kdbus_write_msg_internal (DBusTransportKdbus *transport,
691 DBusMessage *message,
692 const char *destination,
693 DBusMessage **sync_reply,
694 dbus_bool_t check_privileges)
696 struct kdbus_msg *msg = NULL;
697 struct kdbus_msg *msg_reply = NULL;
698 struct kdbus_item *item;
699 uint64_t dst_id = KDBUS_DST_ID_BROADCAST;
700 const DBusString *header;
701 const DBusString *body;
702 int64_t ret_size = -1;
703 uint64_t body_size = 0;
704 uint64_t header_size = 0;
708 const char* header_data;
711 dbus_uint64_t items_size;
712 dbus_uint64_t flags = 0;
713 dbus_uint64_t timeout_ns_or_cookie_reply = 0;
714 dbus_bool_t check_sync_reply = FALSE;
716 dbus_error_init (&error);
718 if (sync_reply != NULL)
719 check_sync_reply = TRUE;
721 // determine destination and destination id
726 _dbus_string_init_const (&str, destination);
727 if (!_dbus_validate_bus_name (&str, 0, _dbus_string_get_length (&str)))
729 _dbus_verbose ("error: unique name is not valid: %s\n", destination);
733 dst_id = parse_name (destination);
737 dst_id = KDBUS_DST_ID_NAME; /* OK, this is zero anyway
738 * but leave it in case
739 * the kdbus constant changes
743 _dbus_message_get_network_data (message, &header, &body);
744 header_size = _dbus_string_get_length (header);
745 body_size = _dbus_string_get_length (body);
746 ret_size = header_size + body_size;
748 /* check whether we can and should use memfd */
749 if ((dst_id != KDBUS_DST_ID_BROADCAST) && (ret_size > MEMFD_SIZE_THRESHOLD))
750 memfd = kdbus_acquire_memfd ();
752 _dbus_message_get_unix_fds (message, &unix_fds, &fds_count);
754 items_size = _kdbus_compute_msg_items_size (transport->kdbus,
761 if (!dbus_message_get_auto_start (message))
762 flags |= KDBUS_MSG_NO_AUTO_START;
764 if (KDBUS_DST_ID_BROADCAST == dst_id) /* signals */
765 flags |= KDBUS_MSG_SIGNAL;
768 if (dbus_message_get_no_reply (message)) /* method replies and errors */
769 timeout_ns_or_cookie_reply = dbus_message_get_reply_serial (message);
770 else /* method calls */
772 long tv_sec, tv_usec;
774 _dbus_get_monotonic_time (&tv_sec, &tv_usec);
776 timeout_ns_or_cookie_reply = (dbus_uint64_t)tv_sec * 1000ULL * 1000ULL * 1000ULL
778 + KDBUS_DEFAULT_TIMEOUT_NS;
780 flags |= KDBUS_MSG_EXPECT_REPLY;
784 msg = _kdbus_new_msg (transport->kdbus,
791 dbus_message_get_serial (message),
792 timeout_ns_or_cookie_reply);
796 /* build message contents */
799 header_data = _dbus_string_get_const_data (header);
801 _dbus_verbose ("sending data by vec\n");
802 item = _kdbus_item_add_payload_vec (item,
804 (uintptr_t)header_data);
807 const char* body_data = _dbus_string_get_const_data (body);
809 #ifdef DBUS_ENABLE_VERBOSE_MODE
812 debug_str ("Header to send:", header);
813 debug_str ("Body to send:", body);
820 size_t body_offsets_size;
821 const char *footer_ptr;
823 /* determine body offsets size */
824 if (ret_size <= 0xFF)
825 body_offsets_size = 1;
826 else if (ret_size <= 0xFFFF)
827 body_offsets_size = 2;
828 else if (ret_size <= 0xFFFFFFFF)
829 body_offsets_size = 4;
831 body_offsets_size = 8;
833 /* check footer size */
834 footer_ptr = body_data + body_size - body_offsets_size -1;
835 while (footer_ptr >= body_data && (*footer_ptr) != 0)
838 if (footer_ptr < body_data)
844 /* prepare memfd for body */
845 if (prepare_mfd (memfd,
847 (footer_ptr - body_data) * sizeof(char)) == -1)
854 item = _kdbus_item_add_payload_memfd (item,
856 (footer_ptr - body_data) * sizeof(char),
860 item = _kdbus_item_add_payload_vec (item,
861 (body_data + body_size - footer_ptr) * sizeof(char),
862 (uintptr_t)footer_ptr);
866 while (body_size > 0)
868 dbus_uint64_t part_size = body_size;
870 if (part_size > KDBUS_MSG_MAX_PAYLOAD_VEC_SIZE)
871 part_size = KDBUS_MSG_MAX_PAYLOAD_VEC_SIZE;
873 _dbus_verbose ("attaching body part\n");
874 item = _kdbus_item_add_payload_vec (item,
876 (uintptr_t)body_data);
877 body_data += part_size;
878 body_size -= part_size;
884 item = _kdbus_item_add_fds (item, unix_fds, fds_count);
886 if (NULL != destination)
887 item = _kdbus_item_add_string (item,
890 strlen (destination) + 1);
891 else if (dst_id == KDBUS_DST_ID_BROADCAST)
893 struct kdbus_bloom_filter *filter = NULL;
894 item = _kdbus_item_add_bloom_filter (item,
897 setup_bloom_filter_for_message (message, transport->kdbus, filter);
900 if (check_privileges)
904 check = can_send (transport, message);
906 if (check != DBUSPOLICY_RESULT_ALLOW)
912 case DBUSPOLICY_RESULT_DENY:
913 reply = reply_with_error (DBUS_ERROR_ACCESS_DENIED, NULL,
914 "Cannot send message - message rejected due to XML security policies",
918 case DBUSPOLICY_RESULT_DEST_NOT_AVAILABLE:
919 reply = reply_with_error (DBUS_ERROR_SERVICE_UNKNOWN, NULL,
920 "Cannot send message - destination not known",
924 case DBUSPOLICY_RESULT_KDBUS_ERROR:
925 reply = reply_with_error (DBUS_ERROR_ACCESS_DENIED, NULL,
926 "Cannot send message - message rejected due to internal libdbuspolicy error (kdbus)",
930 case DBUSPOLICY_RESULT_CYNARA_ERROR:
931 reply = reply_with_error (DBUS_ERROR_ACCESS_DENIED, NULL,
932 "Cannot send message - message rejected due to internal libdbuspolicy error (Cynara)",
937 reply = reply_with_error (DBUS_ERROR_ACCESS_DENIED, NULL,
938 "Cannot send message - unknown libdbuspolicy error",
949 if (check_sync_reply)
955 /* puts locally generated reply into received messages queue */
956 if (!add_message_to_received (reply, transport->base.connection))
961 } /* ret != DBUSPOLICY_RESULT_ALLOW */
962 } /* check_privileges */
964 if (send_message (transport,
967 dbus_message_get_destination (message),
968 dbus_message_get_auto_start (message),
972 DBusMessage *reply = NULL;
974 if (dbus_error_is_set (&error))
976 reply = reply_with_error (error.name,
988 if (check_sync_reply)
994 /* puts locally generated reply into received messages queue */
995 if (!add_message_to_received (reply, transport->base.connection))
1002 if (check_sync_reply)
1005 int size, ret, *fds;
1009 /* check message size */
1010 size = kdbus_message_size (msg_reply, &n_fds);
1014 kdbus_close_message (transport, msg_reply);
1018 /* alloc buffer for decoded message */
1019 data = dbus_malloc (sizeof (char) * size);
1023 kdbus_close_message (transport, msg_reply);
1027 /* alloc palce for fds */
1028 fds = dbus_malloc (sizeof (int) * (n_fds + 1));
1030 /* decode dbus message */
1031 ret = kdbus_decode_dbus_message (msg_reply, data,
1032 transport, fds, &n_fds);
1036 kdbus_close_message (transport, msg_reply);
1040 _dbus_string_init_const_len (&str, data, ret);
1042 /* create DBusMessage from kmsg */
1043 *sync_reply = _dbus_decode_kmsg (&str, msg_reply->src_id, fds, n_fds);
1044 if (*sync_reply == NULL)
1047 kdbus_close_message (transport, msg_reply);
1054 _kdbus_free_msg (msg);
1062 * Sends DBus message using kdbus.
1063 * Handles broadcasts and unicast messages, and passing of Unix fds.
1064 * Also can locally generate error replies on some error returned by kernel.
1066 * TODO refactor to be more compact - maybe we can send header always as a payload vector
1067 * and only message body as memfd if needed.
1069 * @param transport Transport.
1070 * @param message DBus message to be sent
1071 * @param destination Destination of the message.
1072 * @returns bytes sent or -1 if sending failed
1075 kdbus_write_msg (DBusTransportKdbus *transport,
1076 DBusMessage *message,
1077 const char *destination)
1079 return kdbus_write_msg_internal (transport, message, destination, NULL, TRUE);
1082 static dbus_uint64_t
1083 get_pool_size (void)
1085 dbus_uint64_t receive_pool_size = RECEIVE_POOL_SIZE_DEFAULT_SIZE;
1086 const char *env_pool;
1088 env_pool = _dbus_getenv (RECEIVE_POOL_SIZE_ENV_VAR_NAME);
1091 dbus_uint64_t size = 0;
1092 unsigned int multiply = 1;
1095 page_size = sysconf (_SC_PAGESIZE);
1096 if (page_size == -1)
1102 size = strtoul (env_pool, (char**)&env_pool, 10);
1103 if ((errno == EINVAL) || size == 0)
1109 if (*env_pool == 'k')
1114 else if (*env_pool == 'M')
1116 multiply = 1024 * 1024;
1120 if (*env_pool != '\0')
1126 receive_pool_size = size * multiply;
1128 if ((receive_pool_size > RECEIVE_POOL_SIZE_MAX_MBYTES * 1024 * 1024) ||
1129 (receive_pool_size < RECEIVE_POOL_SIZE_MIN_KBYTES * 1024) ||
1130 ((receive_pool_size & (page_size - 1)) != 0)) //pool size must be aligned to page size
1136 _dbus_warn ("%s value is invalid, default value %luB will be used.\n", RECEIVE_POOL_SIZE_ENV_VAR_NAME,
1137 RECEIVE_POOL_SIZE_DEFAULT_SIZE);
1138 _dbus_warn ("Correct value must be between %ukB and %uMB and must be aligned to page size: %ldB.\n",
1139 RECEIVE_POOL_SIZE_MIN_KBYTES, RECEIVE_POOL_SIZE_MAX_MBYTES, page_size);
1141 receive_pool_size = RECEIVE_POOL_SIZE_DEFAULT_SIZE;
1145 _dbus_verbose ("Receive pool size set to %llu.\n", (unsigned long long)receive_pool_size);
1146 return receive_pool_size;
1149 static dbus_uint64_t
1150 get_attach_flags_recv (DBusTransportKdbus *transport)
1152 dbus_uint64_t attach_flags_recv = 0;
1154 #ifdef LIBDBUSPOLICY
1155 attach_flags_recv = KDBUS_ATTACH_CREDS | KDBUS_ATTACH_NAMES | KDBUS_ATTACH_SECLABEL;
1158 return attach_flags_recv;
1162 * Performs kdbus hello - registration on the kdbus bus
1163 * needed to send and receive messages on the bus,
1164 * and configures transport.
1165 * As a result unique id on he bus is obtained.
1167 * @see KDBUS_HELLO_* flags in kdbus.h
1169 * @param transport transport structure
1170 * @param registration_flags aditional flags to modify registration process
1171 * @returns #TRUE on success
1174 bus_register_kdbus (DBusTransportKdbus *transport,
1175 dbus_uint32_t registration_flags,
1179 dbus_uint64_t flags;
1181 flags = KDBUS_HELLO_ACCEPT_FD;
1182 if (registration_flags & REGISTER_FLAG_MONITOR)
1183 flags |= KDBUS_HELLO_MONITOR;
1185 ret = _kdbus_hello (transport->kdbus,
1188 get_attach_flags_recv (transport),
1190 transport->activator,
1194 dbus_set_error (error, DBUS_ERROR_FAILED, "Hello failed: %d", -ret);
1198 transport->my_DBus_unique_name = create_unique_name_from_unique_id (_kdbus_get_id (transport->kdbus));
1199 if (NULL == transport->my_DBus_unique_name)
1201 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, "Hello post failed: %d", -ret);
1205 _dbus_verbose ("-- Our peer ID is: %llu\n", (unsigned long long)_kdbus_get_id (transport->kdbus));
1211 can_own (DBusTransportKdbus *transport,
1214 dbus_bool_t result = TRUE;
1216 #ifdef LIBDBUSPOLICY
1217 if (NULL != transport->policy)
1218 result = (dbuspolicy1_can_own (transport->policy, name) == 1);
1225 request_DBus_name (DBusTransportKdbus *transport,
1230 DBusString service_name_real;
1231 const DBusString *service_name = &service_name_real;
1233 dbus_uint32_t flags;
1235 if (!dbus_message_get_args (msg, error,
1236 DBUS_TYPE_STRING, &name,
1237 DBUS_TYPE_UINT32, &flags,
1241 _dbus_string_init_const (&service_name_real, name);
1243 if (!_dbus_validate_bus_name (service_name, 0,
1244 _dbus_string_get_length (service_name)))
1246 dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1247 "Requested bus name \"%s\" is not valid", name);
1249 _dbus_verbose ("Attempt to acquire invalid service name\n");
1254 if (_dbus_string_get_byte (service_name, 0) == ':')
1256 /* Not allowed; only base services can start with ':' */
1257 dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1258 "Cannot acquire a service starting with ':' such as \"%s\"", name);
1260 _dbus_verbose ("Attempt to acquire invalid base service name \"%s\"", name);
1265 if (_dbus_string_equal_c_str (service_name, DBUS_SERVICE_DBUS))
1267 dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1268 "Connection is not allowed to own the service \"%s\"because "
1269 "it is reserved for D-Bus' use only", DBUS_SERVICE_DBUS);
1273 if (!can_own (transport, name))
1275 dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1276 "Connection \"%s\" is not allowed to own the "
1277 "service \"%s\" due to security policies",
1278 transport->my_DBus_unique_name,
1283 *result = _kdbus_request_name (transport->kdbus, name, flags);
1284 if (*result == -EPERM)
1286 dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1287 "Kdbus doesn't allow %s to own the service \"%s\"",
1288 transport->my_DBus_unique_name, _dbus_string_get_const_data (service_name));
1291 else if (*result < 0)
1293 dbus_set_error (error, DBUS_ERROR_FAILED , "Name \"%s\" could not be acquired, %d, %m", name, errno);
1301 release_DBus_name (DBusTransportKdbus *transport,
1307 DBusString service_name;
1309 if (!dbus_message_get_args (msg, error,
1310 DBUS_TYPE_STRING, &name,
1314 _dbus_string_init_const (&service_name, name);
1316 if (!_dbus_validate_bus_name (&service_name, 0,
1317 _dbus_string_get_length (&service_name)))
1319 dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1320 "Given bus name \"%s\" is not valid",
1321 _dbus_string_get_const_data (&service_name));
1323 _dbus_verbose ("Attempt to release invalid service name\n");
1327 if (_dbus_string_get_byte (&service_name, 0) == ':')
1329 /* Not allowed; the base service name cannot be created or released */
1330 dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1331 "Cannot release a service starting with ':' such as \"%s\"",
1332 _dbus_string_get_const_data (&service_name));
1334 _dbus_verbose ("Attempt to release invalid base service name \"%s\"",
1335 _dbus_string_get_const_data (&service_name));
1339 if (_dbus_string_equal_c_str (&service_name, DBUS_SERVICE_DBUS))
1341 /* Not allowed; the base service name cannot be created or released */
1342 dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1343 "Cannot release the %s service because it is owned by the bus",
1346 _dbus_verbose ("Attempt to release service name \"%s\"",
1351 *result = _kdbus_release_name (transport->kdbus, name);
1354 dbus_set_error (error, DBUS_ERROR_FAILED , "Name \"%s\" could not be released, %d, %m", name, errno);
1362 strcmp_existing (const char *str1, const char *str2)
1364 if (NULL == str1 || NULL == str2)
1366 return strcmp (str1, str2);
1370 kernel_match_needed (MatchRule *rule)
1374 /* Allow only NameOwnerChanged member */
1375 if (strcmp_existing (_match_rule_get_member (rule), "NameOwnerChanged") != 0)
1378 /* Allow only signals */
1379 message_type = _match_rule_get_message_type (rule);
1380 if (message_type != DBUS_MESSAGE_TYPE_INVALID && message_type != DBUS_MESSAGE_TYPE_SIGNAL)
1383 /* Check if from DBus */
1384 if (strcmp_existing (_match_rule_get_sender (rule), DBUS_SERVICE_DBUS) != 0)
1387 if (strcmp_existing (_match_rule_get_interface (rule), DBUS_INTERFACE_DBUS) != 0)
1390 if (strcmp_existing (_match_rule_get_path (rule), DBUS_PATH_DBUS) != 0)
1397 is_bloom_needed (MatchRule *rule)
1402 if (_match_rule_get_message_type (rule) != DBUS_TYPE_INVALID
1403 || _match_rule_get_interface (rule) != NULL
1404 || _match_rule_get_member (rule) != NULL
1405 || _match_rule_get_path (rule) != NULL
1406 || _match_rule_get_path_namespace (rule) != NULL)
1409 rule_int = _match_rule_get_args_len (rule);
1410 for (i = 0; i < rule_int; i++)
1412 if (_match_rule_get_args (rule, i) != NULL)
1420 get_bloom (kdbus_t *kdbus, MatchRule *rule, kdbus_bloom_data_t *bloom_data)
1423 const char *rule_string;
1425 char argument_buf[sizeof ("arg")-1 + 2 + sizeof ("-slash-prefix") +1];
1427 rule_int = _match_rule_get_message_type (rule);
1428 if (rule_int != DBUS_MESSAGE_TYPE_INVALID)
1430 bloom_add_pair (bloom_data, kdbus, "message-type", dbus_message_type_to_string (rule_int));
1431 _dbus_verbose ("Adding type %s \n", dbus_message_type_to_string (rule_int));
1434 rule_string = _match_rule_get_interface (rule);
1435 if (rule_string != NULL)
1437 bloom_add_pair (bloom_data, kdbus, "interface", rule_string);
1438 _dbus_verbose ("Adding interface %s \n", rule_string);
1441 rule_string = _match_rule_get_member (rule);
1442 if (rule_string != NULL)
1444 bloom_add_pair (bloom_data, kdbus, "member", rule_string);
1445 _dbus_verbose ("Adding member %s \n", rule_string);
1448 rule_string = _match_rule_get_path (rule);
1449 if (rule_string != NULL)
1451 bloom_add_pair (bloom_data, kdbus, "path", rule_string);
1452 _dbus_verbose ("Adding path %s \n", rule_string);
1455 rule_string = _match_rule_get_path_namespace (rule);
1456 if (rule_string != NULL)
1458 bloom_add_pair (bloom_data, kdbus, "path-slash-prefix", rule_string);
1459 _dbus_verbose ("Adding path-slash-prefix %s \n", rule_string);
1462 rule_int = _match_rule_get_args_len (rule);
1463 for (i = 0; i < rule_int; i++)
1465 rule_string = _match_rule_get_args (rule, i);
1466 if (rule_string != NULL)
1468 unsigned int rule_arg_lens = _match_rule_get_arg_lens (rule, i);
1469 if (rule_arg_lens & MATCH_ARG_IS_PATH)
1471 snprintf (argument_buf, sizeof (argument_buf), "arg%d-slash-prefix", i);
1472 bloom_add_prefixes (bloom_data, kdbus, argument_buf, rule_string, '/');
1474 else if (rule_arg_lens & MATCH_ARG_NAMESPACE)
1476 snprintf (argument_buf, sizeof (argument_buf), "arg%d-dot-prefix", i);
1477 bloom_add_prefixes (bloom_data, kdbus, argument_buf, rule_string, '.');
1481 snprintf (argument_buf, sizeof (argument_buf), "arg%d", i);
1482 bloom_add_pair (bloom_data, kdbus, argument_buf, rule_string);
1489 * Adds a match rule to match broadcast messages going through the message bus.
1490 * Do no affect messages addressed directly.
1492 * TODO add error reporting
1494 * @param transport transport
1498 add_match_kdbus (DBusTransportKdbus *transport,
1501 struct kdbus_cmd_match *cmd;
1502 struct kdbus_item *item;
1504 uint64_t src_id = KDBUS_MATCH_ID_ANY;
1506 dbus_bool_t need_bloom = FALSE;
1508 const char *rule_sender;
1511 rule_cookie = match_rule_get_cookie (rule);
1514 * First check if it is org.freedesktop.DBus's NameOwnerChanged or any
1515 * org.freedesktop.DBus combination that includes this,
1516 * because it must be converted to special kdbus rule (kdbus has separate rules
1517 * for kdbus (kernel) generated broadcasts).
1519 if (kernel_match_needed (rule))
1521 ret = _kdbus_add_match_name_change (transport->kdbus,
1530 _dbus_verbose ("Failed adding match rule for name removal for daemon, error: %d, %s\n",
1531 ret, _dbus_strerror (ret));
1535 ret = _kdbus_add_match_id_change (transport->kdbus,
1542 _dbus_verbose ("Failed adding match rule for adding id for daemon, error: %d, %s\n",
1543 ret, _dbus_strerror (ret));
1547 _dbus_verbose ("Added match rule for kernel correctly.\n");
1550 * In case all of sender, interface and path are NULL, the rule
1551 * says simply about NameHasOwner signal from any object, any interface, any sender.
1552 * So, we need to consider that.
1553 * Otherwise, our job is finished here.
1555 if (_match_rule_get_sender (rule) != NULL
1556 || _match_rule_get_interface (rule) != NULL
1557 || _match_rule_get_path (rule) != NULL)
1562 * standard rule - registered in general way, for non-kernel broadcasts
1563 * kdbus doesn't use it to check kdbus (kernel) generated broadcasts
1566 need_bloom = is_bloom_needed (rule);
1568 rule_sender = _match_rule_get_sender (rule);
1569 if (rule_sender != NULL)
1572 _dbus_string_init_const (&str, rule_sender);
1574 if (!_dbus_validate_bus_name (&str, 0, _dbus_string_get_length (&str)))
1577 src_id = parse_name (rule_sender);
1579 /* well-known name */
1580 src_id = KDBUS_MATCH_ID_ANY;
1586 items_size = _kdbus_compute_match_items_size (transport->kdbus,
1591 cmd = _kdbus_new_cmd_match (transport->kdbus,
1600 if (NULL != rule_sender) /* well-known name */
1602 item = _kdbus_item_add_string (item,
1605 strlen (rule_sender) + 1);
1606 _dbus_verbose ("Adding sender %s \n", rule_sender);
1608 else if (KDBUS_MATCH_ID_ANY != src_id) /* unique id */
1610 item = _kdbus_item_add_id (item, src_id);
1611 _dbus_verbose ("Adding src_id %llu \n", (unsigned long long)src_id);
1617 item = _kdbus_item_add_bloom_mask (item, transport->kdbus, &bloom);
1618 get_bloom (transport->kdbus, rule, bloom);
1621 ret = _kdbus_add_match (transport->kdbus, cmd);
1623 _kdbus_free_cmd_match (cmd);
1628 _dbus_verbose ("Failed adding match bus rule cookie %llu,\nerror: %d, %s\n",
1629 rule_cookie, ret, _dbus_strerror (ret));
1633 _dbus_verbose ("Added match bus rule %llu\n", rule_cookie);
1637 static DBusMessage *
1638 capture_org_freedesktop_DBus_Hello (DBusTransportKdbus *transport,
1639 DBusMessage *message,
1642 DBusMessageIter args;
1643 dbus_uint32_t registration_flags = 0;
1645 dbus_message_iter_init (message, &args);
1646 if (dbus_message_iter_get_arg_type (&args) == DBUS_TYPE_UINT32)
1647 dbus_message_iter_get_basic (&args, ®istration_flags);
1649 if (!bus_register_kdbus (transport, registration_flags, error))
1652 return reply_1_data (message, DBUS_TYPE_STRING, &transport->my_DBus_unique_name);
1655 free (transport->my_DBus_unique_name);
1659 static DBusMessage *
1660 capture_org_freedesktop_DBus_RequestName (DBusTransportKdbus *transport,
1661 DBusMessage *message,
1666 if (!request_DBus_name (transport, message, &result, error))
1669 return reply_1_data (message, DBUS_TYPE_UINT32, &result);
1672 static DBusMessage *
1673 capture_org_freedesktop_DBus_ReleaseName (DBusTransportKdbus *transport,
1674 DBusMessage *message,
1679 if (!release_DBus_name (transport, message, &result, error))
1682 return reply_1_data (message, DBUS_TYPE_UINT32, &result);
1685 static DBusMessage *
1686 capture_org_freedesktop_DBus_AddMatch (DBusTransportKdbus *transport,
1687 DBusMessage *message,
1692 MatchRule *rule = NULL;
1693 DBusConnection *connection = transport->base.connection;
1695 if (!dbus_message_get_args (message, error,
1696 DBUS_TYPE_STRING, &arg,
1700 _dbus_string_init_const (&arg_str, arg);
1702 rule = match_rule_parse (connection, &arg_str, error);
1706 if (!matchmaker_add_rule (transport->matchmaker, rule))
1708 dbus_set_error_const (error, DBUS_ERROR_NO_MEMORY, "No memory to store match rule");
1712 if (!add_match_kdbus (transport, rule))
1714 dbus_set_error (error, _dbus_error_from_errno (errno), "Could not add match rule, %s",
1715 _dbus_strerror_from_errno ());
1719 match_rule_unref (rule);
1720 return dbus_message_new_method_return (message);
1724 match_rule_unref (rule);
1725 _dbus_verbose ("Error during AddMatch in lib: %s, %s\n", error->name, error->message);
1729 static dbus_uint64_t
1730 get_match_cookie_for_remove (Matchmaker *matchmaker, MatchRule *rule_to_remove)
1732 DBusList *rules = matchmaker_get_rules_list (matchmaker, rule_to_remove);
1735 DBusList *link = _dbus_list_get_last_link (&rules);
1736 while (NULL != link)
1738 if (match_rule_equal_lib (link->data, rule_to_remove))
1740 return match_rule_get_cookie (link->data);
1742 link = _dbus_list_get_prev_link (&rules, link);
1748 static DBusMessage *
1749 capture_org_freedesktop_DBus_RemoveMatch (DBusTransportKdbus *transport,
1750 DBusMessage *message,
1755 MatchRule *rule = NULL;
1756 DBusConnection *connection = transport->base.connection;
1757 dbus_uint64_t cookie;
1759 if (!dbus_message_get_args (message, error,
1760 DBUS_TYPE_STRING, &arg,
1764 _dbus_string_init_const (&arg_str, arg);
1766 rule = match_rule_parse (connection, &arg_str, error);
1769 cookie = get_match_cookie_for_remove (transport->matchmaker, rule);
1772 dbus_set_error (error,
1773 DBUS_ERROR_MATCH_RULE_NOT_FOUND,
1774 "The given match rule wasn't found and can't be removed");
1778 int ret = _kdbus_remove_match (transport->kdbus, cookie);
1780 dbus_set_error (error,
1781 _dbus_error_from_errno (ret),
1782 "Could not remove match rule");
1784 if (!dbus_error_is_set (error))
1785 matchmaker_remove_rule_by_value (transport->matchmaker, rule, error);
1788 match_rule_unref (rule);
1791 if (dbus_error_is_set (error))
1793 _dbus_verbose ("Error during RemoveMatch in lib: %s, %s\n",
1799 return dbus_message_new_method_return (message);
1803 get_connection_info_by_name (DBusMessage *message,
1805 struct nameInfo *info,
1806 DBusTransportKdbus *transport,
1808 dbus_bool_t getLabel)
1811 if (!dbus_validate_bus_name (name, error))
1814 if ((ret = _kdbus_connection_info_by_name (transport->kdbus, name, getLabel, info)) != 0)
1816 if (ESRCH == ret || ENXIO == ret)
1817 dbus_set_error (error, DBUS_ERROR_NAME_HAS_NO_OWNER,
1818 "Could not get owner of name '%s': no such name", name);
1820 dbus_set_error (error, DBUS_ERROR_FAILED,
1821 "Unable to query name %s, returned %d, errno = %d (%m).",
1825 if (info->flags & KDBUS_HELLO_ACTIVATOR)
1827 dbus_set_error (error, DBUS_ERROR_NAME_HAS_NO_OWNER,
1828 "Could not get owner of name '%s'", name);
1829 /* we return ESRCH - this is an indicator that name has an activator */
1835 /* This local function handles common case for org.freedesktop.DBus method handlers:
1836 * 1. gets string argument from incoming message;
1837 * 2. gets connection info for such name.
1838 * Note: if getLabel argument is set to TRUE, the caller must free info.sec_label.
1841 get_connection_info_from_message_argument (DBusMessage *message,
1843 struct nameInfo *info,
1844 DBusTransportKdbus *transport,
1845 dbus_bool_t getLabel)
1849 if (!dbus_message_get_args (message, error,
1850 DBUS_TYPE_STRING, &arg,
1854 return get_connection_info_by_name (message, error, info, transport, arg, getLabel);
1857 static DBusMessage *
1858 capture_org_freedesktop_DBus_GetConnectionCredentials (DBusTransportKdbus *transport,
1859 DBusMessage *message,
1862 DBusMessage *reply = NULL;
1863 DBusMessageIter reply_iter;
1864 DBusMessageIter array_iter;
1865 struct nameInfo info;
1867 if (get_connection_info_from_message_argument (message, error, &info, transport, TRUE) != 0)
1870 reply = _dbus_asv_new_method_return (message, &reply_iter, &array_iter);
1874 /* we can't represent > 32-bit pids; if your system needs them, please
1875 * add ProcessID64 to the spec or something */
1876 if (info.processId <= _DBUS_UINT32_MAX)
1878 if (!_dbus_asv_add_uint32 (&array_iter, "ProcessID", info.processId))
1881 /* we can't represent > 32-bit uids; if your system needs them, please
1882 * add UnixUserID64 to the spec or something */
1883 if (info.userId <= _DBUS_UINT32_MAX)
1885 if (!_dbus_asv_add_uint32 (&array_iter, "UnixUserID", info.userId))
1889 if (info.sec_label != NULL)
1891 dbus_bool_t res = _dbus_asv_add_byte_array (&array_iter,
1892 "LinuxSecurityLabel",
1894 strlen (info.sec_label)+1);
1896 dbus_free (info.sec_label);
1902 if (!_dbus_asv_close (&reply_iter, &array_iter))
1905 if (!dbus_message_set_sender (reply, DBUS_SERVICE_DBUS))
1911 _dbus_asv_abandon (&reply_iter, &array_iter);
1912 dbus_message_unref (reply);
1917 static DBusMessage *
1918 capture_org_freedesktop_DBus_GetConnectionSELinuxSecurityContext (DBusTransportKdbus *transport,
1919 DBusMessage *message,
1922 struct nameInfo info;
1924 if (get_connection_info_from_message_argument (message, error, &info, transport, TRUE) != 0)
1927 if (info.sec_label != NULL)
1931 reply = reply_fixed_array (message, DBUS_TYPE_BYTE,
1933 strlen (info.sec_label)+1);
1935 dbus_free (info.sec_label);
1940 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED, "Operation not supported");
1946 static DBusMessage *
1947 capture_org_freedesktop_DBus_GetConnectionUnixProcessID (DBusTransportKdbus *transport,
1948 DBusMessage *message,
1951 struct nameInfo info;
1952 dbus_uint32_t processId;
1954 if (get_connection_info_from_message_argument (message, error, &info, transport, FALSE) != 0 ||
1955 info.processId > _DBUS_UINT32_MAX)
1958 processId = info.processId;
1960 return reply_1_data (message, DBUS_TYPE_UINT32, &processId);
1963 static DBusMessage *
1964 capture_org_freedesktop_DBus_GetConnectionUnixUser (DBusTransportKdbus *transport,
1965 DBusMessage *message,
1968 struct nameInfo info;
1969 dbus_uint32_t userId;
1971 if (get_connection_info_from_message_argument (message, error, &info, transport, FALSE) != 0 ||
1972 info.userId > _DBUS_UINT32_MAX)
1975 userId = info.userId;
1977 return reply_1_data (message, DBUS_TYPE_UINT32, &userId);
1980 static DBusMessage *
1981 capture_org_freedesktop_DBus_GetId (DBusTransportKdbus *transport,
1982 DBusMessage *message,
1985 dbus_uint64_t bus_id_size = _kdbus_get_bus_id_size ();
1986 char bus_id[bus_id_size*2+1];
1987 char *bus_id_ptr = bus_id;
1988 char *bus_id_original = _kdbus_get_bus_id (transport->kdbus);
1989 dbus_uint64_t i = 0;
1990 for (; i < bus_id_size; i++)
1991 snprintf (bus_id + 2*i, sizeof (bus_id) - 2*i, "%02x", bus_id_original[i]);
1992 return reply_1_data (message, DBUS_TYPE_STRING, &bus_id_ptr);
1995 static DBusMessage *
1996 capture_org_freedesktop_DBus_GetNameOwner (DBusTransportKdbus *transport,
1997 DBusMessage *message,
2001 struct nameInfo info;
2005 if (!dbus_message_get_args (message, error,
2006 DBUS_TYPE_STRING, &arg,
2010 if (strcmp (arg, DBUS_SERVICE_DBUS) == 0)
2012 if (-1 == asprintf (&unique_name, "%s", DBUS_SERVICE_DBUS))
2017 if (get_connection_info_by_name (message, error, &info, transport, arg, FALSE) != 0)
2020 unique_name = create_unique_name_from_unique_id (info.uniqueId);
2021 if (NULL == unique_name)
2025 reply = reply_1_data (message, DBUS_TYPE_STRING, &unique_name);
2032 static DBusMessage *
2033 reply_listNames (DBusTransportKdbus *transport,
2034 DBusMessage *message,
2036 dbus_uint64_t flags)
2038 DBusMessage *reply = NULL;
2039 dbus_uint64_t prev_id = 0;
2041 /* First, get the list from kdbus */
2043 struct kdbus_info *name_list, *name;
2046 DBusMessageIter iter;
2047 DBusMessageIter array_iter;
2049 ret = _kdbus_list (transport->kdbus,
2055 dbus_set_error (error, DBUS_ERROR_FAILED, "Error listing names");
2059 /* Compose the reply on the fly */
2060 reply = dbus_message_new_method_return (message);
2064 dbus_message_iter_init_append (reply, &iter);
2065 if (!dbus_message_iter_open_container (&iter,
2067 DBUS_TYPE_STRING_AS_STRING,
2071 KDBUS_FOREACH (name, name_list, list_size)
2073 struct kdbus_item *item;
2075 if ((flags & KDBUS_LIST_UNIQUE) && name->id != prev_id)
2079 char *unique_name = create_unique_name_from_unique_id (name->id);
2081 if (NULL == unique_name)
2084 res = dbus_message_iter_append_basic (&array_iter,
2093 KDBUS_ITEM_FOREACH (item, name, items)
2095 if (item->type == KDBUS_ITEM_OWNED_NAME)
2097 DBusError local_error;
2098 char *name_ptr = item->name.name;
2100 dbus_error_init ( &local_error );
2101 if (!dbus_validate_bus_name (name_ptr, &local_error))
2104 if (flags & KDBUS_LIST_QUEUED)
2105 name_ptr = create_unique_name_from_unique_id (name->id);
2107 if (NULL == name_ptr)
2110 if (!dbus_message_iter_append_basic (&array_iter,
2115 if (flags & KDBUS_LIST_QUEUED)
2121 if (!dbus_message_iter_close_container (&iter, &array_iter))
2124 if (!dbus_message_set_sender (reply, DBUS_SERVICE_DBUS))
2130 dbus_message_iter_abandon_container (&iter, &array_iter);
2133 dbus_message_unref (reply);
2135 _kdbus_free_mem (transport->kdbus, name_list);
2139 static DBusMessage *
2140 capture_org_freedesktop_DBus_ListActivatableNames (DBusTransportKdbus *transport,
2141 DBusMessage *message,
2144 return reply_listNames (transport, message, error, KDBUS_LIST_ACTIVATORS);
2147 static DBusMessage *
2148 capture_org_freedesktop_DBus_ListNames (DBusTransportKdbus *transport,
2149 DBusMessage *message,
2152 return reply_listNames (transport, message, error, KDBUS_LIST_UNIQUE | KDBUS_LIST_NAMES);
2155 static DBusMessage *
2156 capture_org_freedesktop_DBus_ListQueuedOwners (DBusTransportKdbus *transport,
2157 DBusMessage *message,
2160 struct nameInfo info;
2162 if (get_connection_info_from_message_argument (message, error, &info, transport, FALSE) != 0)
2165 return reply_listNames (transport, message, error, KDBUS_LIST_QUEUED);
2168 static DBusMessage *
2169 capture_org_freedesktop_DBus_NameHasOwner (DBusTransportKdbus *transport,
2170 DBusMessage *message,
2173 struct nameInfo info;
2174 dbus_bool_t result = TRUE;
2176 if (get_connection_info_from_message_argument (message, error, &info, transport, FALSE) != 0)
2178 if (dbus_error_is_set (error) && dbus_error_has_name (error, DBUS_ERROR_NAME_HAS_NO_OWNER))
2181 dbus_error_free (error);
2187 return reply_1_data (message, DBUS_TYPE_BOOLEAN, &result);
2190 static DBusMessage *
2191 capture_org_freedesktop_DBus_ReloadConfig (DBusTransportKdbus *transport,
2192 DBusMessage *message,
2195 DBusMessageIter iter;
2196 DBusMessage *reply = NULL;
2198 dbus_message_iter_init (message, &iter);
2199 if (dbus_message_iter_get_arg_type (&iter) != DBUS_TYPE_STRUCT)
2201 dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
2202 "Call to 'ReloadConfig' has wrong args");
2206 reply = dbus_message_new_method_return (message);
2210 if (!dbus_message_set_sender (reply, DBUS_SERVICE_DBUS))
2216 dbus_message_unref (reply);
2220 static DBusMessage *
2221 capture_org_freedesktop_DBus_StartServiceByName (DBusTransportKdbus *transport,
2222 DBusMessage *message,
2225 struct nameInfo info;
2227 dbus_uint32_t flags; /* Spec says: not used, but we check the syntax anyway */
2229 dbus_bool_t dbus_service = FALSE;
2231 if (!dbus_message_get_args (message, error,
2232 DBUS_TYPE_STRING, &name,
2233 DBUS_TYPE_UINT32, &flags,
2237 dbus_service = (strncmp (name, DBUS_SERVICE_DBUS, strlen (DBUS_SERVICE_DBUS) + 1) == 0);
2240 ret = get_connection_info_by_name (message,
2247 if (dbus_service || 0 == ret)
2249 dbus_uint32_t status = DBUS_START_REPLY_ALREADY_RUNNING;
2250 return reply_1_data (message, DBUS_TYPE_UINT32, &status);
2252 else if (-ESRCH == ret) /* there is an activator */
2254 DBusMessage *sub_message;
2256 /* if we are here, then we have error set - free place for possible real error */
2257 dbus_error_free (error);
2259 /* send method call to org.freedesktop.DBus.Peer.Ping */
2260 sub_message = dbus_message_new_method_call (name, "/", DBUS_INTERFACE_PEER, "Ping");
2261 if (sub_message == NULL)
2264 /* The serial number here is set to -1. A message needs a valid serial number.
2265 * We do not have access to connection's serial numbers counter, so we need to make up one.
2266 * -1 is the last valid serial, so we hope that we'll never get there, especially with 64-bit
2269 dbus_message_set_serial (sub_message, -1);
2271 dbus_message_lock (sub_message);
2273 if (kdbus_write_msg_internal (transport, sub_message, name, NULL, FALSE) == -1)
2277 dbus_uint32_t status = DBUS_START_REPLY_SUCCESS;
2278 return reply_1_data (message, DBUS_TYPE_UINT32, &status);
2284 * There was an error set in get_connection_info_by_name()
2285 * We want to have another error return from StartServiceByName.
2287 dbus_error_free (error);
2288 dbus_set_error (error,
2289 DBUS_ERROR_SERVICE_UNKNOWN,
2290 "The name %s was not provided by any .service files",
2297 static DBusMessage *
2298 capture_org_freedesktop_DBus_UpdateActivationEnvironment (DBusTransportKdbus *transport,
2299 DBusMessage *message,
2302 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
2303 "'%s' method not supported", dbus_message_get_member (message));
2307 typedef DBusMessage * (*CaptureHandler)(DBusTransportKdbus *, DBusMessage *, DBusError *);
2308 struct CaptureHandlers {
2309 const char *method_name;
2310 CaptureHandler handler;
2313 #define HANDLER_ELEMENT(x) {#x, capture_org_freedesktop_DBus_##x}
2315 /* This is to cut the code to parts, and keep it organized:
2316 * an array of elements of type, as in example:
2317 * { "RequestName", capture_org_freedesktop_DBus_RequestName }
2318 * That is, a method of name RequestName will be handled by capture_org_freedesktop_DBus_RequestName ().
2320 static struct CaptureHandlers capture_handlers[] =
2322 // "Hello" is handled separately
2323 // HANDLER_ELEMENT (Hello),
2324 HANDLER_ELEMENT (RequestName),
2325 HANDLER_ELEMENT (ReleaseName),
2326 HANDLER_ELEMENT (AddMatch),
2327 HANDLER_ELEMENT (RemoveMatch),
2328 HANDLER_ELEMENT (GetConnectionCredentials),
2329 HANDLER_ELEMENT (GetConnectionSELinuxSecurityContext),
2330 HANDLER_ELEMENT (GetConnectionUnixProcessID),
2331 HANDLER_ELEMENT (GetConnectionUnixUser),
2332 HANDLER_ELEMENT (GetId),
2333 HANDLER_ELEMENT (GetNameOwner),
2334 HANDLER_ELEMENT (ListActivatableNames),
2335 HANDLER_ELEMENT (ListNames),
2336 HANDLER_ELEMENT (ListQueuedOwners),
2337 HANDLER_ELEMENT (NameHasOwner),
2338 HANDLER_ELEMENT (ReloadConfig),
2339 HANDLER_ELEMENT (StartServiceByName),
2340 HANDLER_ELEMENT (UpdateActivationEnvironment)
2344 * Looks over messages sent to org.freedesktop.DBus. Hello message, which performs
2345 * registration on the bus, is captured as it must be locally converted into
2346 * appropriate ioctl. AddMatch and RemoveMatch are captured to store match rules
2347 * locally in case of false positive result of kdbus bloom filters, but after
2348 * being read they are passed to org.freedesktop.DBus to register these rules
2350 * All the rest org.freedesktop.DBus methods are left untouched
2351 * and they are sent to dbus-daemon in the same way as every other messages.
2353 * @param transport Transport
2354 * @param message Message being sent.
2356 1 if message is not captured and should be passed to kdbus
2357 * 0 if message was handled locally and correctly (it includes proper return of error reply),
2358 * -1 message to org.freedesktop.DBus was not handled correctly.
2361 capture_org_freedesktop_DBus (DBusTransportKdbus *transport,
2362 const char *destination,
2363 DBusMessage *message,
2364 DBusMessage **reply)
2367 if (!strcmp (destination, DBUS_SERVICE_DBUS))
2369 if (!strcmp (dbus_message_get_interface (message), DBUS_INTERFACE_DBUS))
2372 const char *member = dbus_message_get_member (message);
2374 dbus_error_init (&error);
2376 if (!strcmp (member, "Hello"))
2378 *reply = capture_org_freedesktop_DBus_Hello (transport, message, &error);
2383 int handlers_size = sizeof (capture_handlers)/sizeof (capture_handlers[0]);
2385 while (i < handlers_size && strcmp (member, capture_handlers[i].method_name) != 0)
2388 if (i < handlers_size)
2390 *reply = capture_handlers[i].handler (transport, message, &error);
2394 dbus_set_error (&error, DBUS_ERROR_UNKNOWN_METHOD,
2395 "org.freedesktop.DBus does not understand message %s", member);
2399 if (*reply == NULL && dbus_error_is_set (&error))
2401 *reply = reply_with_error ((char*)error.name,
2405 dbus_error_free (&error);
2413 } /* id DBUS_INTERFACE_DBUS */
2414 } /* if DBUS_SERVICE_DBUS */
2419 #ifdef DBUS_ENABLE_VERBOSE_MODE
2420 #define ENUM_NAME_ITEM(x) case x : return #x
2423 enum_MSG (long long id)
2427 ENUM_NAME_ITEM (_KDBUS_ITEM_NULL);
2428 ENUM_NAME_ITEM (KDBUS_ITEM_PAYLOAD_VEC);
2429 ENUM_NAME_ITEM (KDBUS_ITEM_PAYLOAD_OFF);
2430 ENUM_NAME_ITEM (KDBUS_ITEM_PAYLOAD_MEMFD);
2431 ENUM_NAME_ITEM (KDBUS_ITEM_FDS);
2432 ENUM_NAME_ITEM (KDBUS_ITEM_BLOOM_PARAMETER);
2433 ENUM_NAME_ITEM (KDBUS_ITEM_BLOOM_FILTER);
2434 ENUM_NAME_ITEM (KDBUS_ITEM_DST_NAME);
2435 ENUM_NAME_ITEM (KDBUS_ITEM_CREDS);
2436 ENUM_NAME_ITEM (KDBUS_ITEM_PID_COMM);
2437 ENUM_NAME_ITEM (KDBUS_ITEM_TID_COMM);
2438 ENUM_NAME_ITEM (KDBUS_ITEM_EXE);
2439 ENUM_NAME_ITEM (KDBUS_ITEM_CMDLINE);
2440 ENUM_NAME_ITEM (KDBUS_ITEM_CGROUP);
2441 ENUM_NAME_ITEM (KDBUS_ITEM_CAPS);
2442 ENUM_NAME_ITEM (KDBUS_ITEM_SECLABEL);
2443 ENUM_NAME_ITEM (KDBUS_ITEM_AUDIT);
2444 ENUM_NAME_ITEM (KDBUS_ITEM_CONN_DESCRIPTION);
2445 ENUM_NAME_ITEM (KDBUS_ITEM_NAME);
2446 ENUM_NAME_ITEM (KDBUS_ITEM_TIMESTAMP);
2447 ENUM_NAME_ITEM (KDBUS_ITEM_NAME_ADD);
2448 ENUM_NAME_ITEM (KDBUS_ITEM_NAME_REMOVE);
2449 ENUM_NAME_ITEM (KDBUS_ITEM_NAME_CHANGE);
2450 ENUM_NAME_ITEM (KDBUS_ITEM_ID_ADD);
2451 ENUM_NAME_ITEM (KDBUS_ITEM_ID_REMOVE);
2452 ENUM_NAME_ITEM (KDBUS_ITEM_REPLY_TIMEOUT);
2453 ENUM_NAME_ITEM (KDBUS_ITEM_REPLY_DEAD);
2458 #if KDBUS_MSG_DECODE_DEBUG == 1
2460 enum_PAYLOAD (long long id)
2464 ENUM_NAME_ITEM (KDBUS_PAYLOAD_KERNEL);
2465 ENUM_NAME_ITEM (KDBUS_PAYLOAD_DBUS);
2471 msg_id (uint64_t id)
2474 const char* const_ptr;
2481 snprintf (buf, sizeof (buf), "%llu", (unsigned long long)id);
2489 static dbus_uint32_t
2490 get_next_client_serial (DBusTransportKdbus *transport)
2492 dbus_uint32_t serial;
2494 serial = transport->client_serial++;
2496 if (transport->client_serial == 0)
2497 transport->client_serial = 1;
2503 * Calculates length of the kdbus message content (payload).
2505 * @param msg kdbus message
2506 * @return the length of the kdbus message's payload.
2509 kdbus_message_size (const struct kdbus_msg *msg,
2512 const struct kdbus_item *item;
2516 KDBUS_ITEM_FOREACH (item, msg, items)
2518 if (item->size < KDBUS_ITEM_HEADER_SIZE)
2520 _dbus_verbose (" +%s (%llu bytes) invalid data record\n", enum_MSG (item->type), item->size);
2525 case KDBUS_ITEM_PAYLOAD_OFF:
2526 ret_size += item->vec.size;
2528 case KDBUS_ITEM_PAYLOAD_MEMFD:
2529 ret_size += item->memfd.size;
2531 case KDBUS_ITEM_FDS:
2532 *n_fds = (item->size - KDBUS_ITEM_HEADER_SIZE) / sizeof (int);
2543 generate_NameSignal (const char *signal,
2545 DBusTransportKdbus *transport)
2547 DBusMessage *message;
2549 _dbus_verbose ("Generating %s for %s.\n", signal, name);
2551 message = dbus_message_new_signal (DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, signal);
2552 if (message == NULL)
2555 if (!dbus_message_append_args (message, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID))
2557 if (!dbus_message_set_destination (message, transport->my_DBus_unique_name))
2559 if (!dbus_message_set_sender (message, DBUS_SERVICE_DBUS))
2561 dbus_message_set_serial (message, get_next_client_serial (transport));
2563 if (!add_message_to_received (message, transport->base.connection))
2569 dbus_message_unref (message);
2574 * The NameOwnerChanged signals take three parameters with
2575 * unique or well-known names, but only some forms actually
2578 * WELLKNOWN, "", UNIQUE → KDBUS_ITEM_NAME_ADD
2579 * WELLKNOWN, UNIQUE, "" → KDBUS_ITEM_NAME_REMOVE
2580 * WELLKNOWN, UNIQUE, UNIQUE → KDBUS_ITEM_NAME_CHANGE
2581 * UNIQUE, "", UNIQUE → KDBUS_ITEM_ID_ADD
2582 * UNIQUE, UNIQUE, "" → KDBUS_ITEM_ID_REMOVE
2584 * For the latter two the two unique names must be identical.
2587 kdbus_handle_name_owner_changed (__u64 type,
2588 const char *bus_name,
2591 DBusTransportKdbus *transport)
2593 DBusMessage *message = NULL;
2594 DBusMessageIter args;
2596 const char *const_ptr;
2598 if ((message = dbus_message_new_signal (DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged")) == NULL)
2601 dbus_message_iter_init_append (message, &args);
2603 // for ID_ADD and ID_REMOVE this function takes NULL as bus_name
2604 if (bus_name == NULL)
2606 snprintf (tmp_str, sizeof (tmp_str), ":1.%llu", old != 0 ? old : new);
2607 const_ptr = tmp_str;
2610 const_ptr = bus_name;
2612 if (!dbus_message_iter_append_basic (&args, DBUS_TYPE_STRING, &const_ptr))
2615 _dbus_verbose ("%s\n", const_ptr);
2618 if ((old==0) && (new==0))
2620 /* kdbus generates its own set of events that can not be passed to
2621 * client without translation. */
2622 const char *src = "org.freedesktop.DBus";
2623 const char *dst = "org.freedesktop.DBus";
2625 if (type == KDBUS_ITEM_NAME_ADD || type == KDBUS_ITEM_ID_ADD)
2627 else if (type == KDBUS_ITEM_NAME_REMOVE || type == KDBUS_ITEM_ID_REMOVE)
2630 if (!dbus_message_iter_append_basic (&args, DBUS_TYPE_STRING, &src))
2632 if (!dbus_message_iter_append_basic (&args, DBUS_TYPE_STRING, &dst))
2635 _dbus_verbose ("[NameOwnerChanged:%s, old=%lld, new=%lld\n", __func__, old, new);
2639 // determine and append old_id
2642 snprintf (tmp_str, sizeof (tmp_str), ":1.%llu", old);
2643 const_ptr = tmp_str;
2648 if (!dbus_message_iter_append_basic (&args, DBUS_TYPE_STRING, &const_ptr))
2651 _dbus_verbose ("%s\n", const_ptr);
2652 // determine and append new_id
2655 snprintf (tmp_str, sizeof (tmp_str), ":1.%llu", new);
2656 const_ptr = tmp_str;
2661 if (!dbus_message_iter_append_basic (&args, DBUS_TYPE_STRING, &const_ptr))
2664 _dbus_verbose ("%s\n", const_ptr);
2667 dbus_message_set_sender (message, DBUS_SERVICE_DBUS);
2668 dbus_message_set_serial (message, get_next_client_serial (transport));
2670 if (!add_message_to_received (message, transport->base.connection))
2676 dbus_message_unref (message);
2682 handle_item_timestamp (const struct kdbus_item *item)
2684 #if KDBUS_MSG_DECODE_DEBUG == 1
2685 _dbus_verbose (" +%s (%llu bytes) realtime=%lluns monotonic=%lluns\n",
2686 enum_MSG (item->type), item->size,
2687 (unsigned long long)item->timestamp.realtime_ns,
2688 (unsigned long long)item->timestamp.monotonic_ns);
2693 handle_unexpected_item (const struct kdbus_item *item)
2695 _dbus_assert_not_reached ("unexpected item from kdbus");
2699 handle_padding (const struct kdbus_msg *msg,
2700 const struct kdbus_item *end_of_items)
2702 #if KDBUS_MSG_DECODE_DEBUG == 1
2703 if ((char *)end_of_items - ((char *)msg + msg->size) >= 8)
2704 _dbus_verbose ("invalid padding at end of message\n");
2708 #ifdef LIBDBUSPOLICY
2710 load_dbus_header (DBusTransportKdbus *transport,
2712 const char *message_data,
2713 dbus_uint32_t message_len)
2715 DBusValidity validity = DBUS_VALID;
2717 dbus_uint32_t fields_array_len_unsigned;
2718 dbus_uint32_t body_len_unsigned;
2721 if (0 == message_len)
2724 _dbus_string_init_const_len (&message, message_data, message_len);
2725 _dbus_gvariant_raw_get_lengths (&message,
2726 &fields_array_len_unsigned,
2730 _dbus_string_init_const_len (&header->data,
2732 fields_array_len_unsigned + FIRST_GVARIANT_FIELD_OFFSET);
2734 header->padding = 0;
2735 header->byte_order = message_data[0];
2736 header->protocol_version = DBUS_PROTOCOL_VERSION_GVARIANT;
2737 for (i = 0; i <= DBUS_HEADER_FIELD_LAST; i++)
2738 header->fields[i].value_pos = _DBUS_HEADER_FIELD_VALUE_NONEXISTENT;
2740 return _dbus_header_load_gvariant (header, &validity);
2745 can_receive (DBusTransportKdbus *transport,
2746 const struct kdbus_msg *msg,
2747 const char *message_data,
2748 dbus_uint32_t message_len)
2750 dbus_bool_t result = TRUE;
2752 #ifdef LIBDBUSPOLICY
2753 if (transport->policy)
2756 dbus_bool_t got_header = FALSE;
2757 dbus_bool_t got_creds = FALSE;
2758 dbus_bool_t got_seclabel = FALSE;
2760 if (KDBUS_PAYLOAD_DBUS == msg->payload_type)
2762 const struct kdbus_item *item;
2763 uid_t sender_euid = -1;
2764 gid_t sender_egid = -1;
2765 const char *seclabel = NULL;
2770 _dbus_string_init (&names);
2772 KDBUS_ITEM_FOREACH(item, msg, items)
2775 case KDBUS_ITEM_CREDS:
2776 sender_euid = (uid_t) item->creds.euid;
2777 sender_egid = (gid_t) item->creds.egid;
2778 got_creds = (sender_euid != (uid_t)-1) && (sender_egid != (gid_t)-1);
2780 case KDBUS_ITEM_SECLABEL:
2781 seclabel = item->str;
2782 got_seclabel = (seclabel != NULL);
2784 case KDBUS_ITEM_OWNED_NAME:
2787 _dbus_string_init_const (&name, item->name.name);
2788 if (_dbus_validate_bus_name (&name, 0, _dbus_string_get_length (&name)))
2790 if (_dbus_string_get_length (&names) != 0)
2791 _dbus_string_append_byte (&names, ' ');
2793 _dbus_string_copy (&name,
2796 _dbus_string_get_length (&names));
2801 break; /* ignore all other items */
2804 if (NULL != message_data && message_len > 0)
2806 if (load_dbus_header (transport, &header, message_data, message_len))
2810 if (got_header && _dbus_header_get_message_type (&header) != DBUS_MESSAGE_TYPE_METHOD_CALL)
2814 else if (got_header && got_creds && got_seclabel)
2816 const char *destination = NULL;
2817 const char *path = NULL;
2818 const char *interface = NULL;
2819 const char *member = NULL;
2820 const char *error_name = NULL;
2821 dbus_uint64_t reply_cookie = 0;
2822 dbus_bool_t requested_reply = FALSE;
2825 _dbus_header_get_field_basic (&header,
2826 DBUS_HEADER_FIELD_DESTINATION,
2830 _dbus_header_get_field_basic (&header,
2831 DBUS_HEADER_FIELD_PATH,
2835 _dbus_header_get_field_basic (&header,
2836 DBUS_HEADER_FIELD_INTERFACE,
2840 _dbus_header_get_field_basic (&header,
2841 DBUS_HEADER_FIELD_MEMBER,
2845 _dbus_header_get_field_basic (&header,
2846 DBUS_HEADER_FIELD_ERROR_NAME,
2850 _dbus_header_get_field_basic (&header,
2851 DBUS_HEADER_FIELD_REPLY_SERIAL,
2855 requested_reply = !(_dbus_header_get_flag (&header,
2856 DBUS_HEADER_FLAG_NO_REPLY_EXPECTED));
2858 ret = dbuspolicy1_check_in (transport->policy,
2860 _dbus_string_get_length (&names) > 0 ?
2861 _dbus_string_get_const_data (&names) :
2869 _dbus_header_get_message_type (&header),
2873 result = (1 == ret);
2876 _dbus_string_free (&names);
2885 kdbus_decode_dbus_message (const struct kdbus_msg *msg,
2887 DBusTransportKdbus *kdbus_transport,
2891 const struct kdbus_item *item;
2893 char *buffer = data;
2897 KDBUS_ITEM_FOREACH (item, msg, items)
2899 if (item->size < KDBUS_ITEM_HEADER_SIZE)
2901 _dbus_verbose (" +%s (%llu bytes) invalid data record\n", enum_MSG (item->type), item->size);
2908 case KDBUS_ITEM_PAYLOAD_OFF:
2909 memcpy (data, (char *)msg+item->vec.offset, item->vec.size);
2910 data += item->vec.size;
2911 ret_size += item->vec.size;
2913 #ifdef DBUS_ENABLE_VERBOSE_MODE
2916 debug_c_str ("Message part arrived:", (char *)msg+item->vec.offset, item->vec.size);
2920 _dbus_verbose (" +%s (%llu bytes) off=%llu size=%llu\n",
2921 enum_MSG (item->type), item->size,
2922 (unsigned long long)item->vec.offset,
2923 (unsigned long long)item->vec.size);
2926 case KDBUS_ITEM_PAYLOAD_MEMFD:
2931 size = item->memfd.size;
2932 _dbus_verbose ("memfd.size : %llu\n", (unsigned long long)size);
2934 buf = mmap (NULL, size, PROT_READ, MAP_PRIVATE, item->memfd.fd, 0);
2935 if (buf == MAP_FAILED)
2937 _dbus_verbose ("mmap () fd=%i failed:%m", item->memfd.fd);
2941 memcpy (data, buf, size);
2946 close (item->memfd.fd);
2948 _dbus_verbose (" +%s (%llu bytes) off=%llu size=%llu\n",
2949 enum_MSG (item->type), item->size,
2950 (unsigned long long)item->vec.offset,
2951 (unsigned long long)item->vec.size);
2955 case KDBUS_ITEM_FDS:
2959 *n_fds = (item->size - KDBUS_ITEM_HEADER_SIZE) / sizeof (int);
2960 memcpy (fds, item->fds, *n_fds * sizeof (int));
2961 for (i = 0; i < *n_fds; i++)
2962 _dbus_fd_set_close_on_exec (fds[i]);
2966 case KDBUS_ITEM_CREDS:
2967 #if KDBUS_MSG_DECODE_DEBUG == 1
2968 _dbus_verbose (" +%s (%llu bytes) uid=%lld, gid=%lld, pid=%lld, tid=%lld, starttime=%lld\n",
2969 enum_MSG (item->type), item->size,
2970 item->creds.uid, item->creds.gid,
2971 item->creds.pid, item->creds.tid,
2972 item->creds.starttime);
2976 case KDBUS_ITEM_PID_COMM:
2977 case KDBUS_ITEM_TID_COMM:
2978 case KDBUS_ITEM_EXE:
2979 case KDBUS_ITEM_CGROUP:
2980 case KDBUS_ITEM_SECLABEL:
2981 case KDBUS_ITEM_DST_NAME:
2982 #if KDBUS_MSG_DECODE_DEBUG == 1
2983 _dbus_verbose (" +%s (%llu bytes) '%s' (%zu)\n",
2984 enum_MSG (item->type), item->size, item->str, strlen (item->str));
2988 case KDBUS_ITEM_CMDLINE:
2989 case KDBUS_ITEM_NAME:
2990 #if KDBUS_MSG_DECODE_DEBUG == 1
2992 __u64 size = item->size - KDBUS_ITEM_HEADER_SIZE;
2993 const char *str = item->str;
2996 _dbus_verbose (" +%s (%llu bytes) ", enum_MSG (item->type), item->size);
2999 _dbus_verbose ("'%s' ", str);
3000 size -= strlen (str) + 1;
3001 str += strlen (str) + 1;
3005 _dbus_verbose ("(%d string%s)\n", count, (count == 1) ? "" : "s");
3010 case KDBUS_ITEM_AUDIT:
3011 #if KDBUS_MSG_DECODE_DEBUG == 1
3012 _dbus_verbose (" +%s (%llu bytes) loginuid=%llu sessionid=%llu\n",
3013 enum_MSG (item->type), item->size,
3014 (unsigned long long)item->data64[0],
3015 (unsigned long long)item->data64[1]);
3019 case KDBUS_ITEM_CAPS:
3020 #if KDBUS_MSG_DECODE_DEBUG == 1
3023 const uint32_t *cap;
3026 _dbus_verbose (" +%s (%llu bytes) len=%llu bytes)\n",
3027 enum_MSG (item->type), item->size,
3028 (unsigned long long)item->size - KDBUS_ITEM_HEADER_SIZE);
3031 n = (item->size - KDBUS_ITEM_HEADER_SIZE) / 4 / sizeof (uint32_t);
3033 _dbus_verbose (" CapInh=");
3034 for (i = 0; i < n; i++)
3035 _dbus_verbose ("%08x", cap[(0 * n) + (n - i - 1)]);
3037 _dbus_verbose (" CapPrm=");
3038 for (i = 0; i < n; i++)
3039 _dbus_verbose ("%08x", cap[(1 * n) + (n - i - 1)]);
3041 _dbus_verbose (" CapEff=");
3042 for (i = 0; i < n; i++)
3043 _dbus_verbose ("%08x", cap[(2 * n) + (n - i - 1)]);
3045 _dbus_verbose (" CapInh=");
3046 for (i = 0; i < n; i++)
3047 _dbus_verbose ("%08x", cap[(3 * n) + (n - i - 1)]);
3048 _dbus_verbose ("\n");
3053 case KDBUS_ITEM_TIMESTAMP:
3054 handle_item_timestamp (item);
3057 case KDBUS_ITEM_BLOOM_FILTER:
3062 handle_unexpected_item (item);
3067 handle_padding (msg, item);
3069 if (!can_receive (kdbus_transport, msg, buffer, ret_size))
3070 return 0; /* ignore message if not allowed */
3076 kdbus_decode_kernel_message (const struct kdbus_msg *msg,
3077 DBusTransportKdbus *kdbus_transport)
3079 const struct kdbus_item *item;
3082 KDBUS_ITEM_FOREACH (item, msg, items)
3084 if (item->size < KDBUS_ITEM_HEADER_SIZE)
3086 _dbus_verbose (" +%s (%llu bytes) invalid data record\n", enum_MSG (item->type), item->size);
3093 case KDBUS_ITEM_REPLY_TIMEOUT:
3094 case KDBUS_ITEM_REPLY_DEAD:
3096 DBusMessage *message = NULL;
3097 _dbus_verbose (" +%s (%llu bytes) cookie=%llu\n",
3098 enum_MSG (item->type), item->size, msg->cookie_reply);
3100 message = _dbus_generate_local_error_message (msg->cookie_reply,
3101 item->type == KDBUS_ITEM_REPLY_TIMEOUT ? DBUS_ERROR_NO_REPLY : DBUS_ERROR_NAME_HAS_NO_OWNER, NULL);
3102 if (message == NULL)
3108 dbus_message_set_serial (message, get_next_client_serial (kdbus_transport));
3110 if (!add_message_to_received (message, kdbus_transport->base.connection))
3115 case KDBUS_ITEM_NAME_ADD:
3116 case KDBUS_ITEM_NAME_REMOVE:
3117 case KDBUS_ITEM_NAME_CHANGE:
3121 _dbus_verbose (" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, old flags=0x%llx, new flags=0x%llx\n",
3122 enum_MSG (item->type), (unsigned long long) item->size,
3123 item->name_change.name, item->name_change.old_id.id,
3124 item->name_change.new_id.id, item->name_change.old_id.flags,
3125 item->name_change.new_id.flags);
3127 if (item->name_change.new_id.id == _kdbus_get_id (kdbus_transport->kdbus))
3128 ret_size = generate_NameSignal ("NameAcquired", item->name_change.name, kdbus_transport);
3129 else if (item->name_change.old_id.id == _kdbus_get_id (kdbus_transport->kdbus))
3130 ret_size = generate_NameSignal ("NameLost", item->name_change.name, kdbus_transport);
3135 if (item->name_change.new_id.flags & KDBUS_NAME_ACTIVATOR)
3136 local_ret = kdbus_handle_name_owner_changed (item->type,
3137 item->name_change.name,
3138 item->name_change.old_id.id, 0,
3140 else if (item->name_change.old_id.flags & KDBUS_NAME_ACTIVATOR)
3141 local_ret = kdbus_handle_name_owner_changed (item->type,
3142 item->name_change.name, 0,
3143 item->name_change.new_id.id,
3146 local_ret = kdbus_handle_name_owner_changed (item->type,
3147 item->name_change.name,
3148 item->name_change.old_id.id,
3149 item->name_change.new_id.id,
3151 if (local_ret == -1)
3154 ret_size += local_ret;
3158 case KDBUS_ITEM_ID_ADD:
3159 case KDBUS_ITEM_ID_REMOVE:
3160 _dbus_verbose (" +%s (%llu bytes) id=%llu flags=%llu\n",
3161 enum_MSG (item->type), (unsigned long long) item->size,
3162 (unsigned long long) item->id_change.id,
3163 (unsigned long long) item->id_change.flags);
3165 if (item->id_change.flags & KDBUS_HELLO_ACTIVATOR)
3166 ret_size = kdbus_handle_name_owner_changed (item->type, NULL, 0, 0,
3169 ret_size = kdbus_handle_name_owner_changed (item->type, NULL,
3170 item->type == KDBUS_ITEM_ID_ADD ? 0 : item->id_change.id,
3171 item->type == KDBUS_ITEM_ID_ADD ? item->id_change.id : 0,
3178 case KDBUS_ITEM_TIMESTAMP:
3179 handle_item_timestamp (item);
3183 handle_unexpected_item (item);
3188 handle_padding (msg, item);
3195 * Decodes kdbus message in order to extract DBus message and puts it into received data buffer
3196 * and file descriptor's buffer. Also captures kdbus error messages and kdbus kernel broadcasts
3197 * and converts all of them into appropriate DBus messages.
3199 * @param msg kdbus message
3200 * @param data place to copy DBus message to
3201 * @param kdbus_transport transport
3202 * @param fds place to store file descriptors received
3203 * @param n_fds place to store quantity of file descriptors received
3204 * @return number of DBus message's bytes received or -1 on error
3207 kdbus_decode_msg (const struct kdbus_msg *msg,
3209 DBusTransportKdbus *kdbus_transport,
3216 #if KDBUS_MSG_DECODE_DEBUG == 1
3217 _dbus_verbose ("MESSAGE: %s (%llu bytes) flags=0x%llx, %s → %s, cookie=%llu, timeout=%llu\n",
3218 enum_PAYLOAD (msg->payload_type),
3219 (unsigned long long) msg->size,
3220 (unsigned long long) msg->flags,
3221 msg_id (msg->src_id),
3222 msg_id (msg->dst_id),
3223 (unsigned long long) msg->cookie,
3224 (unsigned long long) msg->timeout_ns);
3227 switch (msg->payload_type)
3229 case KDBUS_PAYLOAD_DBUS:
3230 ret_size = kdbus_decode_dbus_message (msg, data, kdbus_transport, fds, n_fds);
3232 case KDBUS_PAYLOAD_KERNEL:
3233 ret_size = kdbus_decode_kernel_message (msg, kdbus_transport);
3236 _dbus_assert_not_reached ("unexpected payload type from kdbus");
3244 * Reads message from kdbus and puts it into DBus buffers
3246 * @param kdbus_transport transport
3247 * @param buffer place to copy received message to
3248 * @param fds place to store file descriptors received with the message
3249 * @param n_fds place to store quantity of file descriptors received
3250 * @return size of received message on success, -1 on error
3253 kdbus_read_message (DBusTransportKdbus *kdbus_transport,
3258 int ret_size, buf_size;
3259 struct kdbus_msg *msg;
3262 dbus_uint64_t flags = 0;
3266 dbus_error_init (&error);
3268 start = _dbus_string_get_length (buffer);
3270 if (kdbus_transport->activator != NULL)
3271 flags |= KDBUS_RECV_PEEK;
3273 ret = _kdbus_recv (kdbus_transport->kdbus, flags, 0, &msg);
3277 _dbus_verbose ("kdbus error receiving message: %d (%s)\n", ret, _dbus_strerror (ret));
3281 buf_size = kdbus_message_size (msg, n_fds);
3284 _dbus_verbose ("kdbus error - too short message: %d (%m)\n", errno);
3288 /* What is the maximum size of the locally generated message?
3289 I just assume 2048 bytes */
3290 buf_size = MAX (buf_size, 2048);
3292 if (!_dbus_string_lengthen (buffer, buf_size))
3297 data = _dbus_string_get_data_len (buffer, start, buf_size);
3299 ret_size = kdbus_decode_msg (msg, data, kdbus_transport, fds, n_fds, &error);
3301 if (ret_size == -1) /* error */
3302 _dbus_string_set_length (buffer, start);
3303 else if (ret_size >= 0 && buf_size != ret_size) /* case of locally generated message */
3304 _dbus_string_set_length (buffer, start + ret_size);
3307 _dbus_message_loader_set_unique_sender_id (kdbus_transport->base.loader, msg->src_id);
3309 if (kdbus_transport->activator != NULL)
3312 ret = _kdbus_free_mem (kdbus_transport->kdbus, msg);
3315 _dbus_verbose ("kdbus error freeing message: %d (%s)\n", ret, _dbus_strerror (ret));
3322 static DBusMessage *
3323 kdbus_send_sync_call (DBusTransportKdbus *transport,
3324 DBusMessage *message)
3326 DBusMessage *reply = NULL;
3328 const char *destination;
3330 dbus_message_lock (message);
3332 destination = dbus_message_get_destination (message);
3337 ret = capture_org_freedesktop_DBus ((DBusTransportKdbus*)transport, destination, message, &reply);
3344 kdbus_write_msg_internal (transport, message, destination, &reply, TRUE);
3352 dbus_error_init (&error);
3354 dbus_set_error (&error, DBUS_ERROR_FAILED,
3355 "Something went wrong");
3357 reply = reply_with_error ((char*)error.name,
3362 dbus_error_free (&error);
3366 _dbus_assert (reply != NULL);
3367 dbus_message_lock (reply);
3373 * Copy-paste from socket transport. Only renames done.
3376 free_watches (DBusTransportKdbus *kdbus_transport)
3378 DBusConnection *connection = kdbus_transport->base.connection;
3379 _dbus_verbose ("start\n");
3381 if (kdbus_transport->read_watch)
3384 _dbus_connection_remove_watch_unlocked (connection,
3385 kdbus_transport->read_watch);
3386 _dbus_watch_invalidate (kdbus_transport->read_watch);
3387 _dbus_watch_unref (kdbus_transport->read_watch);
3388 kdbus_transport->read_watch = NULL;
3391 if (kdbus_transport->write_watch)
3394 _dbus_connection_remove_watch_unlocked (connection,
3395 kdbus_transport->write_watch);
3396 _dbus_watch_invalidate (kdbus_transport->write_watch);
3397 _dbus_watch_unref (kdbus_transport->write_watch);
3398 kdbus_transport->write_watch = NULL;
3401 _dbus_verbose ("end\n");
3405 free_policies (DBusTransportKdbus *transport)
3407 #ifdef LIBDBUSPOLICY
3408 if (NULL != transport->policy)
3409 dbuspolicy1_free (transport->policy);
3414 * Copy-paste from socket transport. Only done needed renames and removed
3415 * lines related to encoded messages.
3418 transport_finalize (DBusTransport *transport)
3420 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus *)transport;
3421 _dbus_verbose ("\n");
3423 free_watches (kdbus_transport);
3425 _dbus_transport_finalize_base (transport);
3427 _dbus_assert (kdbus_transport->read_watch == NULL);
3428 _dbus_assert (kdbus_transport->write_watch == NULL);
3430 free_matchmaker (kdbus_transport->matchmaker);
3432 dbus_free (kdbus_transport->activator);
3434 free_policies ( kdbus_transport );
3436 _kdbus_free (kdbus_transport->kdbus);
3437 free (kdbus_transport->my_DBus_unique_name);
3439 dbus_free (transport);
3443 * Copy-paste from socket transport. Removed code related to authentication,
3444 * socket_transport replaced by kdbus_transport.
3447 check_write_watch (DBusTransportKdbus *kdbus_transport)
3450 DBusTransport *transport = &kdbus_transport->base;
3452 if (transport->connection == NULL)
3455 if (transport->disconnected)
3457 _dbus_assert (kdbus_transport->write_watch == NULL);
3461 _dbus_transport_ref (transport);
3463 needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection);
3465 _dbus_verbose ("check_write_watch (): needed = %d on connection %p watch %p fd = %d outgoing messages exist %d\n",
3466 needed, transport->connection, kdbus_transport->write_watch,
3467 _kdbus_get_fd (kdbus_transport->kdbus),
3468 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
3470 _dbus_connection_toggle_watch_unlocked (transport->connection,
3471 kdbus_transport->write_watch,
3474 _dbus_transport_unref (transport);
3478 * Copy-paste from socket transport. Removed code related to authentication,
3479 * socket_transport replaced by kdbus_transport.
3482 check_read_watch (DBusTransportKdbus *kdbus_transport)
3484 dbus_bool_t need_read_watch;
3485 DBusTransport *transport = &kdbus_transport->base;
3487 _dbus_verbose ("fd = %d\n",_kdbus_get_fd (kdbus_transport->kdbus));
3489 if (transport->connection == NULL)
3492 if (transport->disconnected)
3494 _dbus_assert (kdbus_transport->read_watch == NULL);
3498 _dbus_transport_ref (transport);
3501 (_dbus_counter_get_size_value (transport->live_messages) < transport->max_live_messages_size) &&
3502 (_dbus_counter_get_unix_fd_value (transport->live_messages) < transport->max_live_messages_unix_fds);
3504 _dbus_verbose (" setting read watch enabled = %d\n", need_read_watch);
3506 _dbus_connection_toggle_watch_unlocked (transport->connection,
3507 kdbus_transport->read_watch,
3510 _dbus_transport_unref (transport);
3514 * Copy-paste from socket transport.
3517 do_io_error (DBusTransport *transport)
3519 _dbus_transport_ref (transport);
3520 _dbus_transport_disconnect (transport);
3521 _dbus_transport_unref (transport);
3525 * Based on do_writing from socket transport.
3526 * Removed authentication code and code related to encoded messages
3527 * and adapted to kdbus transport.
3528 * In socket transport returns false on out-of-memory. Here this won't happen,
3529 * so it always returns TRUE.
3532 do_writing (DBusTransport *transport)
3534 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
3536 dbus_bool_t oom = FALSE;
3538 if (transport->disconnected)
3540 _dbus_verbose ("Not connected, not writing anything\n");
3544 _dbus_verbose ("do_writing (), have_messages = %d, fd = %d\n",
3545 _dbus_connection_has_messages_to_send_unlocked (transport->connection),
3546 _kdbus_get_fd (kdbus_transport->kdbus));
3548 while (!transport->disconnected && _dbus_connection_has_messages_to_send_unlocked (transport->connection))
3551 DBusMessage *message;
3553 const DBusString *header;
3554 const DBusString *body;
3555 const char* pDestination;
3557 if (total > kdbus_transport->max_bytes_written_per_iteration)
3559 _dbus_verbose ("%d bytes exceeds %d bytes written per iteration, returning\n",
3560 total, kdbus_transport->max_bytes_written_per_iteration);
3565 message = _dbus_connection_get_message_to_send (transport->connection);
3566 _dbus_assert (message != NULL);
3567 pDestination = dbus_message_get_destination (message);
3573 ret = capture_org_freedesktop_DBus ((DBusTransportKdbus*)transport, pDestination, message, &reply);
3574 if (ret < 0) //error
3579 else if (ret == 0) //message captured and handled correctly
3581 /* puts locally generated reply into received messages queue */
3582 if (!add_message_to_received (reply, kdbus_transport->base.connection))
3588 _dbus_message_get_network_data (message, &header, &body);
3589 bytes_written = _dbus_string_get_length (header) + _dbus_string_get_length (body);
3592 //else send as regular message
3595 bytes_written = kdbus_write_msg (kdbus_transport, message, pDestination);
3598 if (bytes_written < 0)
3600 if (errno == ENOMEM)
3606 /* EINTR already handled for us */
3608 /* For some discussion of why we also ignore EPIPE here, see
3609 * http://lists.freedesktop.org/archives/dbus/2008-March/009526.html
3612 if (_dbus_get_is_errno_eagain_or_ewouldblock (errno) || _dbus_get_is_errno_epipe (errno))
3616 _dbus_verbose ("Error writing to remote app: %s\n", _dbus_strerror_from_errno ());
3617 do_io_error (transport);
3623 #if defined (DBUS_ENABLE_VERBOSE_MODE) || !defined (DBUS_DISABLE_ASSERT)
3624 int total_bytes_to_write;
3626 _dbus_message_get_network_data (message, &header, &body);
3627 total_bytes_to_write = _dbus_string_get_length (header)
3628 + _dbus_string_get_length (body);
3629 _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
3630 total_bytes_to_write);
3632 _dbus_assert (bytes_written == total_bytes_to_write);
3634 total += bytes_written;
3636 _dbus_connection_message_sent_unlocked (transport->connection,
3649 * Based on do_reading from socket transport.
3650 * Removed authentication code and code related to encoded messages
3651 * and adapted to kdbus transport.
3652 * returns false on out-of-memory
3655 do_reading (DBusTransport *transport)
3657 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
3660 dbus_bool_t oom = FALSE;
3664 _dbus_verbose ("fd = %d\n", _kdbus_get_fd (kdbus_transport->kdbus));
3668 /* See if we've exceeded max messages and need to disable reading */
3669 if (kdbus_transport->activator == NULL)
3670 check_read_watch (kdbus_transport);
3672 if (total > kdbus_transport->max_bytes_read_per_iteration)
3674 _dbus_verbose ("%d bytes exceeds %d bytes read per iteration, returning\n",
3675 total, kdbus_transport->max_bytes_read_per_iteration);
3679 _dbus_assert (kdbus_transport->read_watch != NULL ||
3680 transport->disconnected);
3682 if (transport->disconnected)
3685 if (!dbus_watch_get_enabled (kdbus_transport->read_watch))
3688 if (!_dbus_message_loader_get_unix_fds (transport->loader, &fds, &n_fds))
3690 _dbus_verbose ("Out of memory reading file descriptors\n");
3694 _dbus_message_loader_get_buffer (transport->loader, &buffer);
3696 bytes_read = kdbus_read_message (kdbus_transport, buffer, fds, &n_fds);
3698 if (bytes_read >= 0 && n_fds > 0)
3699 _dbus_verbose ("Read %i unix fds\n", n_fds);
3701 _dbus_message_loader_return_buffer (transport->loader,
3703 _dbus_message_loader_return_unix_fds (transport->loader, fds, bytes_read < 0 ? 0 : n_fds);
3707 /* EINTR already handled for us */
3709 if (_dbus_get_is_errno_enomem (errno))
3711 _dbus_verbose ("Out of memory in read()/do_reading()\n");
3715 else if (_dbus_get_is_errno_eagain_or_ewouldblock (errno))
3719 _dbus_verbose ("Error reading from remote app: %s\n",
3720 _dbus_strerror_from_errno ());
3721 do_io_error (transport);
3725 else if (bytes_read > 0)
3727 _dbus_verbose (" read %d bytes\n", bytes_read);
3729 total += bytes_read;
3731 if (!_dbus_transport_queue_messages (transport))
3734 _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
3738 /* Try reading more data until we get EAGAIN and return, or
3739 * exceed max bytes per iteration. If in blocking mode of
3740 * course we'll block instead of returning.
3744 /* 0 == bytes_read is for kernel and ignored messages */
3753 * Copy-paste from socket transport, with socket replaced by kdbus.
3756 unix_error_with_read_to_come (DBusTransport *itransport,
3760 DBusTransportKdbus *transport = (DBusTransportKdbus *) itransport;
3762 if (!((flags & DBUS_WATCH_HANGUP) || (flags & DBUS_WATCH_ERROR)))
3765 /* If we have a read watch enabled ...
3766 we -might have data incoming ... => handle the HANGUP there */
3767 if (watch != transport->read_watch && _dbus_watch_get_enabled (transport->read_watch))
3774 * Copy-paste from socket transport. Removed authentication related code
3775 * and renamed socket_transport to kdbus_transport.
3778 kdbus_handle_watch (DBusTransport *transport,
3782 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
3784 _dbus_assert (watch == kdbus_transport->read_watch ||
3785 watch == kdbus_transport->write_watch);
3786 _dbus_assert (watch != NULL);
3788 /* If we hit an error here on a write watch, don't disconnect the transport yet because data can
3789 * still be in the buffer and do_reading may need several iteration to read
3790 * it all (because of its max_bytes_read_per_iteration limit).
3792 if (!(flags & DBUS_WATCH_READABLE) && unix_error_with_read_to_come (transport, watch, flags))
3794 _dbus_verbose ("Hang up or error on watch\n");
3795 _dbus_transport_disconnect (transport);
3799 if (watch == kdbus_transport->read_watch &&
3800 (flags & DBUS_WATCH_READABLE))
3802 _dbus_verbose ("handling read watch %p flags = %x\n",
3805 if (!do_reading (transport))
3807 _dbus_verbose ("no memory to read\n");
3811 else if (watch == kdbus_transport->write_watch &&
3812 (flags & DBUS_WATCH_WRITABLE))
3814 _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n",
3815 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
3817 if (!do_writing (transport))
3819 _dbus_verbose ("no memory to write\n");
3823 /* See if we still need the write watch */
3824 check_write_watch (kdbus_transport);
3831 * Copy-paste from socket transport, but socket_transport renamed to kdbus_transport
3832 * and _dbus_close_socket replaced with close ().
3835 kdbus_disconnect (DBusTransport *transport)
3837 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
3839 _dbus_verbose ("\n");
3841 free_watches (kdbus_transport);
3843 _kdbus_close (kdbus_transport->kdbus);
3847 * Copy-paste from socket transport. Renamed socket_transport to
3848 * kdbus_transport and added setting authenticated to TRUE, because
3849 * we do not perform authentication in kdbus, so we have mark is as already done
3850 * to make everything work.
3853 kdbus_connection_set (DBusTransport *transport)
3855 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
3857 _dbus_watch_set_handler (kdbus_transport->write_watch,
3858 _dbus_connection_handle_watch,
3859 transport->connection, NULL);
3861 _dbus_watch_set_handler (kdbus_transport->read_watch,
3862 _dbus_connection_handle_watch,
3863 transport->connection, NULL);
3865 if (!_dbus_connection_add_watch_unlocked (transport->connection,
3866 kdbus_transport->write_watch))
3869 if (!_dbus_connection_add_watch_unlocked (transport->connection,
3870 kdbus_transport->read_watch))
3872 _dbus_connection_remove_watch_unlocked (transport->connection,
3873 kdbus_transport->write_watch);
3877 check_read_watch (kdbus_transport);
3878 check_write_watch (kdbus_transport);
3884 * Copy-paste from socket_transport.
3885 * Socket_transport renamed to kdbus_transport
3887 * Original dbus copy-pasted @todo comment below.
3888 * @todo We need to have a way to wake up the select sleep if
3889 * a new iteration request comes in with a flag (read/write) that
3890 * we're not currently serving. Otherwise a call that just reads
3891 * could block a write call forever (if there are no incoming
3895 kdbus_do_iteration (DBusTransport *transport,
3897 int timeout_milliseconds)
3899 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
3904 _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p fd = %d\n",
3905 flags & DBUS_ITERATION_DO_READING ? "read" : "",
3906 flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
3907 timeout_milliseconds,
3908 kdbus_transport->read_watch,
3909 kdbus_transport->write_watch,
3910 _kdbus_get_fd (kdbus_transport->kdbus));
3912 poll_fd.fd = _kdbus_get_fd (kdbus_transport->kdbus);
3917 * This fix is for reply_with_error function.
3918 * When timeout is set to -1 in client application,
3919 * error messages are inserted directly to incoming queue and
3920 * application hangs on dbus_poll.
3922 * This causes a busy loop in _dbus_connection_block_pending_call()
3923 * There is no case of waiting for the locally-generated error reply
3925 if (_dbus_connection_get_n_incoming (transport->connection) > 0)
3927 timeout_milliseconds = 0;
3931 /* This is kind of a hack; if we have stuff to write, then try
3932 * to avoid the poll. This is probably about a 5% speedup on an
3933 * echo client/server.
3935 * If both reading and writing were requested, we want to avoid this
3936 * since it could have funky effects:
3937 * - both ends spinning waiting for the other one to read
3938 * data so they can finish writing
3939 * - prioritizing all writing ahead of reading
3941 if ((flags & DBUS_ITERATION_DO_WRITING) &&
3942 !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) &&
3943 !transport->disconnected &&
3944 _dbus_connection_has_messages_to_send_unlocked (transport->connection))
3946 do_writing (transport);
3948 if (transport->disconnected ||
3949 !_dbus_connection_has_messages_to_send_unlocked (transport->connection))
3953 /* If we get here, we decided to do the poll() after all */
3954 _dbus_assert (kdbus_transport->read_watch);
3955 if (flags & DBUS_ITERATION_DO_READING)
3956 poll_fd.events |= _DBUS_POLLIN;
3958 _dbus_assert (kdbus_transport->write_watch);
3959 if (flags & DBUS_ITERATION_DO_WRITING)
3960 poll_fd.events |= _DBUS_POLLOUT;
3964 if ( (flags & DBUS_ITERATION_BLOCK) && !(flags & DBUS_ITERATION_DO_WRITING))
3965 poll_timeout = timeout_milliseconds;
3969 /* For blocking selects we drop the connection lock here
3970 * to avoid blocking out connection access during a potentially
3971 * indefinite blocking call. The io path is still protected
3972 * by the io_path_cond condvar, so we won't reenter this.
3974 if (flags & DBUS_ITERATION_BLOCK)
3976 _dbus_verbose ("unlock pre poll\n");
3977 _dbus_connection_unlock (transport->connection);
3981 poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
3983 if (poll_res < 0 && _dbus_get_is_errno_eintr (errno))
3986 if (flags & DBUS_ITERATION_BLOCK)
3988 _dbus_verbose ("lock post poll\n");
3989 _dbus_connection_lock (transport->connection);
3995 poll_fd.revents = 0; /* some concern that posix does not guarantee this;
3996 * valgrind flags it as an error. though it probably
3997 * is guaranteed on linux at least.
4000 if (poll_fd.revents & _DBUS_POLLERR)
4001 do_io_error (transport);
4004 dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
4006 _dbus_verbose ("in iteration, need_read=%d\n",
4009 if (need_read && (flags & DBUS_ITERATION_DO_READING))
4010 do_reading (transport);
4011 /* We always be able to write to kdbus */
4012 if (flags & DBUS_ITERATION_DO_WRITING)
4013 do_writing (transport);
4017 _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
4021 /* We need to install the write watch only if we did not
4022 * successfully write everything. Note we need to be careful that we
4023 * don't call check_write_watch *before* do_writing, since it's
4024 * inefficient to add the write watch, and we can avoid it most of
4025 * the time since we can write immediately.
4027 * However, we MUST always call check_write_watch(); DBusConnection code
4028 * relies on the fact that running an iteration will notice that
4029 * messages are pending.
4031 check_write_watch (kdbus_transport);
4033 _dbus_verbose (" ... leaving do_iteration()\n");
4037 * Copy-paste from socket transport.
4040 kdbus_live_messages_changed (DBusTransport *transport)
4042 /* See if we should look for incoming messages again */
4043 check_read_watch ((DBusTransportKdbus *)transport);
4047 * Gets file descriptor of the kdbus bus.
4048 * @param transport transport
4049 * @param fd_p place to write fd to
4050 * @returns always TRUE
4053 kdbus_get_kdbus_fd (DBusTransport *transport,
4056 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
4058 fd_p->fd = _kdbus_get_fd (kdbus_transport->kdbus);
4063 static const DBusTransportVTable kdbus_vtable = {
4067 kdbus_connection_set,
4069 kdbus_live_messages_changed,
4073 typedef unsigned long (*ConnectionInfoExtractField) (struct nameInfo *);
4075 static inline unsigned long
4076 _extract_name_info_userId (struct nameInfo *nameInfo)
4078 return nameInfo->userId;
4081 static inline unsigned long
4082 _extract_name_info_processId (struct nameInfo *nameInfo)
4084 return nameInfo->processId;
4088 _dbus_transport_kdbus_get_connection_info_ulong_field (DBusTransportKdbus *transport,
4089 ConnectionInfoExtractField function,
4092 struct nameInfo conn_info;
4095 ret = _kdbus_connection_info_by_id (transport->kdbus,
4096 _kdbus_get_id (transport->kdbus),
4102 *val = function (&conn_info);
4107 _dbus_transport_kdbus_get_unix_user (DBusTransport *transport,
4110 return _dbus_transport_kdbus_get_connection_info_ulong_field ((DBusTransportKdbus *)transport,
4111 _extract_name_info_userId,
4116 _dbus_transport_kdbus_get_unix_process_id (DBusTransport *transport,
4119 return _dbus_transport_kdbus_get_connection_info_ulong_field ((DBusTransportKdbus *)transport,
4120 _extract_name_info_processId,
4125 * Copy-paste from dbus_transport_socket with needed changes.
4127 * Creates a new transport for the given kdbus file descriptor and address.
4128 * The file descriptor must be nonblocking.
4130 * @param fd the file descriptor.
4131 * @param address the transport's address
4132 * @returns the new transport, or #NULL if no memory.
4134 static DBusTransportKdbus *
4135 new_kdbus_transport (kdbus_t *kdbus,
4136 const DBusString *address,
4137 const char *activator)
4139 DBusTransportKdbus *kdbus_transport;
4141 kdbus_transport = dbus_new0 (DBusTransportKdbus, 1);
4142 if (kdbus_transport == NULL)
4145 kdbus_transport->kdbus = kdbus;
4147 kdbus_transport->write_watch = _dbus_watch_new (_kdbus_get_fd (kdbus),
4148 DBUS_WATCH_WRITABLE,
4151 if (kdbus_transport->write_watch == NULL)
4154 kdbus_transport->read_watch = _dbus_watch_new (_kdbus_get_fd (kdbus),
4155 DBUS_WATCH_READABLE,
4158 if (kdbus_transport->read_watch == NULL)
4161 if (!_dbus_transport_init_base_authenticated (&kdbus_transport->base,
4166 _dbus_transport_set_get_unix_user_function (&kdbus_transport->base,
4167 _dbus_transport_kdbus_get_unix_user);
4168 _dbus_transport_set_get_unix_process_id_function (&kdbus_transport->base,
4169 _dbus_transport_kdbus_get_unix_process_id);
4170 #ifdef ENABLE_KDBUS_SYNC_CALLS
4171 _dbus_transport_set_send_sync_call_function (&kdbus_transport->base,
4172 (DBusTransportSendSyncCallFunction) kdbus_send_sync_call);
4174 _dbus_transport_set_assure_protocol_function (&kdbus_transport->base,
4175 _dbus_message_assure_gvariant,
4176 DBUS_PROTOCOL_VERSION_GVARIANT);
4178 /* These values should probably be tunable or something. */
4179 kdbus_transport->max_bytes_read_per_iteration = MAX_BYTES_PER_ITERATION;
4180 kdbus_transport->max_bytes_written_per_iteration = MAX_BYTES_PER_ITERATION;
4182 if (activator!=NULL)
4184 kdbus_transport->activator = _dbus_strdup (activator);
4185 if (kdbus_transport->activator == NULL)
4189 kdbus_transport->matchmaker = matchmaker_new ();
4191 kdbus_transport->client_serial = 1;
4193 return kdbus_transport;
4196 _dbus_watch_invalidate (kdbus_transport->read_watch);
4197 _dbus_watch_unref (kdbus_transport->read_watch);
4199 _dbus_watch_invalidate (kdbus_transport->write_watch);
4200 _dbus_watch_unref (kdbus_transport->write_watch);
4202 dbus_free (kdbus_transport);
4207 initialize_policies (DBusTransportKdbus *transport, const char *path)
4209 dbus_bool_t result = TRUE;
4211 #ifdef LIBDBUSPOLICY
4212 transport->policy = dbuspolicy1_init (path);
4213 if (NULL == transport->policy)
4221 * Connects to kdbus, creates and sets-up transport.
4223 * @param path the path to the bus.
4224 * @param error address where an error can be returned.
4225 * @returns a new transport, or #NULL on failure.
4227 static DBusTransport*
4228 _dbus_transport_new_for_kdbus (const char *path,
4229 const char *activator,
4233 DBusTransportKdbus *transport;
4237 #ifdef DBUS_ENABLE_VERBOSE_MODE
4238 const char *dbgenv = _dbus_getenv ("G_DBUS_DEBUG");
4241 if (!strcmp (dbgenv, "message"))
4243 else if (!strcmp (dbgenv, "all"))
4248 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
4250 if (!_dbus_string_init (&address))
4252 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
4256 if ((!_dbus_string_append (&address, DBUS_ADDRESS_KDBUS "path=")) || (!_dbus_string_append (&address, path)))
4258 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
4262 kdbus = _kdbus_new ();
4265 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
4269 ret = _kdbus_open (kdbus, path);
4272 dbus_set_error (error,
4273 _dbus_error_from_errno (-ret),
4274 "Failed to open file descriptor: %s: %s",
4276 _dbus_strerror (-ret));
4277 goto failed_0_with_kdbus;
4280 _dbus_verbose ("Successfully connected to kdbus bus %s\n", path);
4282 transport = new_kdbus_transport (kdbus, &address, activator);
4283 if (transport == NULL)
4285 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
4289 if (!initialize_policies (transport, path))
4291 dbus_set_error (error,
4293 "Can't load dbus policy for kdbus transport");
4294 _kdbus_close (kdbus);
4295 transport_finalize ((DBusTransport*)transport);
4299 _dbus_string_free (&address);
4301 return (DBusTransport*)transport;
4304 _kdbus_close (kdbus);
4305 failed_0_with_kdbus:
4306 _kdbus_free (kdbus);
4308 _dbus_string_free (&address);
4314 * Opens kdbus transport if method from address entry is kdbus
4316 * @param entry the address entry to open
4317 * @param transport_p return location for the opened transport
4318 * @param error place to store error
4319 * @returns result of the attempt as a DBusTransportOpenResult enum
4321 DBusTransportOpenResult
4322 _dbus_transport_open_kdbus (DBusAddressEntry *entry,
4323 DBusTransport **transport_p,
4328 method = dbus_address_entry_get_method (entry);
4329 _dbus_assert (method != NULL);
4331 if (strcmp (method, "kernel") == 0)
4333 const char *path = dbus_address_entry_get_value (entry, "path");
4334 const char *activator = dbus_address_entry_get_value (entry, "activator");
4338 _dbus_set_bad_address (error, "kdbus", "path", NULL);
4339 return DBUS_TRANSPORT_OPEN_BAD_ADDRESS;
4342 *transport_p = _dbus_transport_new_for_kdbus (path, activator, error);
4344 if (*transport_p == NULL)
4346 _DBUS_ASSERT_ERROR_IS_SET (error);
4347 return DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT;
4351 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
4352 return DBUS_TRANSPORT_OPEN_OK;
4357 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
4358 return DBUS_TRANSPORT_OPEN_NOT_HANDLED;