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"
35 #include <linux/kdbus.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__) || defined(__x86_64__)
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_INFINITE_TIMEOUT_NS 0x3fffffffffffffffLLU
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)
238 if (sender && !dbus_message_set_sender (errMessage, sender))
240 _dbus_verbose ("oom");
241 dbus_message_unref (errMessage);
249 * Generates local error message as a reply to message given as parameter
250 * and adds generated error message to received messages queue.
251 * @param error_type type of error, preferably DBUS_ERROR_(...)
252 * @param template Template of error description. It can has formatting
253 * characters to print object string into it. Can be NULL.
254 * @param object String to print into error description. Can be NULL.
255 * If object is not NULL while template is NULL, the object string
256 * will be the only error description.
257 * @param message Message for which the error reply is generated.
258 * @returns local error message on success, otherwise NULL
261 reply_with_error (const char *error_type,
262 const char *template,
264 DBusMessage *message)
266 return reply_with_error_preset_sender (error_type, template,
267 object, message, NULL);
271 * Generates reply to the message given as a parameter with one item in the reply body
272 * and adds generated reply message to received messages queue.
273 * @param message The message we are replying to.
274 * @param data_type Type of data sent in the reply.Use DBUS_TYPE_(...)
275 * @param pData Address of data sent in the reply.
276 * @returns generated reply on success, otherwise NULL
279 reply_1_data (DBusMessage *message,
283 DBusMessageIter args;
286 reply = dbus_message_new_method_return (message);
290 if (!dbus_message_set_sender (reply, DBUS_SERVICE_DBUS))
293 dbus_message_iter_init_append (reply, &args);
294 if (!dbus_message_iter_append_basic (&args, data_type, pData))
300 dbus_message_unref (reply);
306 reply_fixed_array (DBusMessage *message,
311 DBusMessageIter args, array_iter;
314 reply = dbus_message_new_method_return (message);
318 if (!dbus_message_set_sender (reply, DBUS_SERVICE_DBUS))
321 dbus_message_iter_init_append (reply, &args);
323 if (!dbus_message_iter_open_container (&args,
325 DBUS_TYPE_BYTE_AS_STRING,
329 if (!dbus_message_iter_append_fixed_array (&array_iter, element_type, &data, n_elements))
332 if (!dbus_message_iter_close_container (&args, &array_iter))
338 dbus_message_iter_abandon_container (&args, &array_iter);
341 dbus_message_unref (reply);
346 * Retrieves file descriptor to memory pool from kdbus module and stores
347 * it in kdbus_transport->memfd. It is then used to send large message.
348 * Triggered when message payload is over MEMFD_SIZE_THRESHOLD
349 * @param kdbus_transport DBusTransportKdbus transport structure
350 * @returns 0 on success, otherwise -1
353 kdbus_acquire_memfd ( void )
357 /* FIXME add HAVE_MEMFD_CREATE */
358 if ((fd = syscall (__NR_memfd_create, "kdbus", MFD_ALLOW_SEALING | MFD_CLOEXEC )) < 0)
360 _dbus_verbose ("memfd_create failed (%d): %m\n", fd);
363 _dbus_verbose ("%s: memfd=%d\n", __FUNCTION__, fd);
368 bloom_add_pair (kdbus_bloom_data_t *bloom_data,
370 const char *parameter,
379 size = strlen (parameter) + strlen (value) + 1;
383 snprintf (buf, size + 1, "%s:%s", parameter, value);
384 _kdbus_bloom_add_data (kdbus, bloom_data, buf, size);
388 bloom_add_prefixes (kdbus_bloom_data_t *bloom_data,
390 const char *parameter,
397 size = strlen (parameter) + strlen (value) + 1;
401 snprintf (buf, size + 1, "%s:%s", parameter, value);
406 last_sep = strrchr (buf, separator);
407 if (!last_sep || last_sep == buf)
411 _kdbus_bloom_add_data (kdbus, bloom_data, buf, last_sep-buf);
416 setup_bloom_filter_for_message (DBusMessage *msg,
418 struct kdbus_bloom_filter *bloom_filter)
420 kdbus_bloom_data_t *bloom_data;
423 DBusMessageIter args;
426 _dbus_assert (bloom_filter);
428 bloom_data = _kdbus_bloom_filter_get_data (bloom_filter);
430 bloom_add_pair (bloom_data,
433 dbus_message_type_to_string (dbus_message_get_type (msg)));
435 bloom_add_pair (bloom_data, kdbus, "interface", dbus_message_get_interface (msg));
436 bloom_add_pair (bloom_data, kdbus, "member", dbus_message_get_member (msg));
437 str = dbus_message_get_path (msg);
440 bloom_add_pair (bloom_data, kdbus, "path", str);
441 bloom_add_pair (bloom_data, kdbus, "path-slash-prefix", str);
442 bloom_add_prefixes (bloom_data, kdbus, "path-slash-prefix", str, '/');
445 if (!dbus_message_iter_init (msg, &args))
448 for (i = 0; i < 64; i++)
451 char buf[sizeof ("arg")-1 + 2 + sizeof ("-slash-prefix")];
455 type = dbus_message_iter_get_arg_type (&args);
456 if (type != DBUS_TYPE_STRING &&
457 type != DBUS_TYPE_OBJECT_PATH &&
458 type != DBUS_TYPE_SIGNATURE)
461 dbus_message_iter_get_basic (&args, &str);
463 snprintf (buf, sizeof (buf), "arg%d", i);
465 bloom_add_pair (bloom_data, kdbus, buf, str);
467 /* point e to end of string, we will add suffixes */
470 /* we need remaining length of the buffer */
471 len = sizeof (buf) - len;
473 strncpy (e, "-dot-prefix", len);
474 bloom_add_prefixes (bloom_data, kdbus, buf, str, '.');
475 strncpy (e, "-slash-prefix", len);
476 bloom_add_prefixes (bloom_data, kdbus, buf, str, '/');
478 if (!dbus_message_iter_next (&args))
486 * Checks if a string is a unique name or well known name.
488 * @param name a valid D-Bus name
489 * @returns 0 for well-known names, otherwise unique id
492 parse_name (const char *name)
494 dbus_uint64_t unique_id = 0;
496 /* if name is unique name it must be converted to unique id */
497 if (strncmp (name, ":1.", 3) == 0)
500 unique_id = strtoull (&name[3], &endptr, 10);
502 if (unique_id == 0 || *endptr != '\0' || errno == ERANGE)
510 prepare_mfd (int memfd,
516 _dbus_verbose ("sending data via memfd\n");
519 wr = write (memfd, body, body_size);
522 _dbus_verbose ("writing to memfd failed: (%d) %m\n", errno);
529 // seal data - kdbus module needs it
530 if (fcntl (memfd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE | F_SEAL_SEAL) < 0)
532 _dbus_verbose ("memfd sealing failed: %d (%m)\n", errno);
539 send_message (DBusTransportKdbus *transport,
540 struct kdbus_msg *kdbus_msg,
542 const char *destination,
543 dbus_bool_t is_auto_start,
544 struct kdbus_msg **kdbus_msg_reply,
548 dbus_uint64_t flags = 0;
551 flags |= KDBUS_SEND_SYNC_REPLY;
553 ret = _kdbus_send (transport->kdbus,
559 _dbus_verbose ("kdbus error sending message: err %d (%s)\n", ret, _dbus_strerror (ret) );
563 case ENXIO: /* no such id on the bus */
566 dbus_set_error (error,
567 DBUS_ERROR_SERVICE_UNKNOWN,
568 "The name %s was not provided by any .service files",
571 dbus_set_error (error,
572 DBUS_ERROR_NAME_HAS_NO_OWNER,
573 "Name \"%s\" does not exist",
578 dbus_set_error (error,
579 DBUS_ERROR_SERVICE_UNKNOWN,
580 "No support for activation for name: \"%s\"", destination);
584 dbus_set_error (error,
585 DBUS_ERROR_LIMITS_EXCEEDED,
586 "The memory pool of the receiver is full");
590 dbus_set_error (error,
591 DBUS_ERROR_LIMITS_EXCEEDED,
592 "Too many pending messages on the receiver side");
596 dbus_set_error (error,
597 DBUS_ERROR_LIMITS_EXCEEDED,
598 "The size of the message is excessive");
602 dbus_set_error (error,
603 DBUS_ERROR_LIMITS_EXCEEDED,
604 "The maximum number of pending replies per connection has been reached");
608 dbus_set_error (error,
610 "Timeout was reached");
614 dbus_set_error (error,
615 DBUS_ERROR_ACCESS_DENIED,
616 "Permission denied");
620 dbus_set_error (error,
622 "Something went wrong: %s",
623 _dbus_strerror (ret));
633 kdbus_close_message (DBusTransportKdbus *transport, struct kdbus_msg *msg)
635 struct kdbus_item *item;
637 KDBUS_ITEM_FOREACH (item, msg, items)
639 if (item->type == KDBUS_ITEM_PAYLOAD_MEMFD)
640 close (item->memfd.fd);
643 _kdbus_free_mem (transport->kdbus, msg);
646 #ifdef DBUS_ENABLE_VERBOSE_MODE
648 debug_c_str (const char *msg, const char *str, int len)
651 fprintf (stderr, "%s\n", msg);
652 for (i = 0; i < len; i++)
654 fprintf (stderr, "%02x ", (unsigned char)str[i]);
655 if (i%16==15) fprintf (stderr, "\n");
657 fprintf (stderr, "\n");
661 debug_str (const char *msg, const DBusString *str)
663 debug_c_str (msg, _dbus_string_get_const_data (str), _dbus_string_get_length (str));
669 can_send (DBusTransportKdbus *transport,
670 DBusMessage *message)
673 int ret = DBUSPOLICY_RESULT_ALLOW;
674 if (NULL != transport->policy)
676 dbus_uint32_t reply_serial = dbus_message_get_reply_serial (message);
678 /* If reply_serial is non-zero, then it is a reply - just send it.
679 * Otherwise - check the policy.
681 if (0 == reply_serial)
683 /* If method call or unicast signal, check policy */
684 if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL ||
685 (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_SIGNAL &&
686 dbus_message_get_destination (message) != NULL))
687 ret = dbuspolicy1_check_out (transport->policy,
688 dbus_message_get_destination (message),
689 transport->my_DBus_unique_name,
690 dbus_message_get_path (message),
691 dbus_message_get_interface (message),
692 dbus_message_get_member (message),
693 dbus_message_get_type (message),
694 dbus_message_get_error_name (message),
696 !dbus_message_get_no_reply (message));
704 /* function prototypes */
705 static int kdbus_message_size (const struct kdbus_msg *msg,
707 static int kdbus_decode_dbus_message (const struct kdbus_msg *msg,
709 DBusTransportKdbus *kdbus_transport,
714 kdbus_write_msg_internal (DBusTransportKdbus *transport,
715 DBusMessage *message,
716 const char *destination,
717 DBusMessage **sync_reply,
718 dbus_bool_t check_privileges)
720 struct kdbus_msg *msg = NULL;
721 struct kdbus_msg *msg_reply = NULL;
722 struct kdbus_item *item;
723 uint64_t dst_id = KDBUS_DST_ID_BROADCAST;
724 const DBusString *header;
725 const DBusString *body;
726 int64_t ret_size = -1;
727 uint64_t body_size = 0;
728 uint64_t header_size = 0;
732 const char* header_data;
734 const char *destination_name = destination;
736 dbus_uint64_t items_size;
737 dbus_uint64_t flags = 0;
738 dbus_uint64_t timeout_ns_or_cookie_reply = 0;
739 dbus_bool_t check_sync_reply = FALSE;
741 dbus_error_init (&error);
743 if (sync_reply != NULL)
744 check_sync_reply = TRUE;
746 // determine destination and destination id
751 _dbus_string_init_const (&str, destination);
752 if (!_dbus_validate_bus_name (&str, 0, _dbus_string_get_length (&str)))
754 _dbus_verbose ("error: unique name is not valid: %s\n", destination);
758 dst_id = parse_name (destination);
762 dst_id = KDBUS_DST_ID_NAME; /* OK, this is zero anyway
763 * but leave it in case
764 * the kdbus constant changes
768 _dbus_message_get_network_data (message, &header, &body);
769 header_size = _dbus_string_get_length (header);
770 body_size = _dbus_string_get_length (body);
771 ret_size = header_size + body_size;
773 /* check whether we can and should use memfd */
774 if ((dst_id != KDBUS_DST_ID_BROADCAST) && (ret_size > MEMFD_SIZE_THRESHOLD))
775 memfd = kdbus_acquire_memfd ();
777 _dbus_message_get_unix_fds (message, &unix_fds, &fds_count);
779 items_size = _kdbus_compute_msg_items_size (transport->kdbus,
786 if (!dbus_message_get_auto_start (message))
787 flags |= KDBUS_MSG_NO_AUTO_START;
789 if (KDBUS_DST_ID_BROADCAST == dst_id) /* signals */
790 flags |= KDBUS_MSG_SIGNAL;
793 if (dbus_message_get_no_reply (message)) /* method replies and errors */
794 timeout_ns_or_cookie_reply = dbus_message_get_reply_serial (message);
795 else /* method calls */
797 long tv_sec, tv_usec;
798 int timeout_ms = _dbus_message_get_timeout_ms(message);
800 _dbus_get_monotonic_time (&tv_sec, &tv_usec);
802 timeout_ns_or_cookie_reply = 1U | ( /* ensure nonzero */
803 (dbus_uint64_t)tv_sec * 1000ULL * 1000ULL * 1000ULL
804 + tv_usec * 1000ULL + (
805 timeout_ms == -1 ? _DBUS_DEFAULT_TIMEOUT_VALUE * 1000000LLU :
806 timeout_ms == DBUS_TIMEOUT_INFINITE ? KDBUS_INFINITE_TIMEOUT_NS :
807 (uint64_t)timeout_ms * 1000000U
811 flags |= KDBUS_MSG_EXPECT_REPLY;
815 msg = _kdbus_new_msg (transport->kdbus,
822 dbus_message_get_serial (message),
823 timeout_ns_or_cookie_reply);
827 /* build message contents */
830 header_data = _dbus_string_get_const_data (header);
832 _dbus_verbose ("sending data by vec\n");
833 item = _kdbus_item_add_payload_vec (item,
835 (uintptr_t)header_data);
838 const char* body_data = _dbus_string_get_const_data (body);
839 size_t body_offsets_size;
840 const char *footer_ptr;
842 /* determine body offsets size */
843 if (ret_size <= 0xFF)
844 body_offsets_size = 1;
845 else if (ret_size <= 0xFFFF)
846 body_offsets_size = 2;
847 else if (ret_size <= 0xFFFFFFFF)
848 body_offsets_size = 4;
850 body_offsets_size = 8;
852 /* check footer size */
853 footer_ptr = body_data + body_size - body_offsets_size -1;
854 while (footer_ptr >= body_data && (*footer_ptr) != 0)
857 if (footer_ptr < body_data)
863 #ifdef DBUS_ENABLE_VERBOSE_MODE
866 debug_str ("Header to send:", header);
867 debug_str ("Body to send:", body);
873 /* prepare memfd for body */
874 if (-1 == prepare_mfd (memfd,
876 (uint64_t)((footer_ptr - body_data) * sizeof(char))))
883 item = _kdbus_item_add_payload_memfd (item,
885 (footer_ptr - body_data) * sizeof(char),
889 item = _kdbus_item_add_payload_vec (item,
890 (body_data + body_size - footer_ptr) * sizeof(char),
891 (uintptr_t)footer_ptr);
895 while (body_size > 0)
897 dbus_uint32_t part_size;
899 if (body_size < KDBUS_MSG_MAX_PAYLOAD_VEC_SIZE)
900 part_size = body_size;
902 part_size = KDBUS_MSG_MAX_PAYLOAD_VEC_SIZE;
904 /* we need to adjust part size if footer does not fit as a whole */
905 if (body_size - part_size > 0 && footer_ptr < (body_data + part_size))
906 part_size = footer_ptr - body_data;
908 _dbus_verbose ("attaching body part\n");
909 item = _kdbus_item_add_payload_vec (item,
911 (uintptr_t)body_data);
912 body_data += part_size;
913 body_size -= part_size;
919 item = _kdbus_item_add_fds (item, unix_fds, fds_count);
921 if (NULL != destination)
922 item = _kdbus_item_add_string (item,
925 strlen (destination) + 1);
926 else if (dst_id == KDBUS_DST_ID_BROADCAST)
928 struct kdbus_bloom_filter *filter = NULL;
929 item = _kdbus_item_add_bloom_filter (item,
932 setup_bloom_filter_for_message (message, transport->kdbus, filter);
936 if (check_privileges)
940 check = can_send (transport, message);
942 if (check != DBUSPOLICY_RESULT_ALLOW)
948 case DBUSPOLICY_RESULT_DENY:
949 reply = reply_with_error (DBUS_ERROR_ACCESS_DENIED, NULL,
950 "Cannot send message - message rejected due to XML security policies",
954 case DBUSPOLICY_RESULT_DEST_NOT_AVAILABLE:
955 _dbus_assert (destination_name != NULL);
956 if (dbus_message_get_auto_start (message))
957 reply = reply_with_error (DBUS_ERROR_SERVICE_UNKNOWN, NULL,
958 "Cannot send message - destination not known",
961 reply = reply_with_error (DBUS_ERROR_NAME_HAS_NO_OWNER, "Name \"%s\" does not exist",
966 case DBUSPOLICY_RESULT_KDBUS_ERROR:
967 reply = reply_with_error (DBUS_ERROR_ACCESS_DENIED, NULL,
968 "Cannot send message - message rejected due to internal libdbuspolicy error (kdbus)",
972 case DBUSPOLICY_RESULT_CYNARA_ERROR:
973 reply = reply_with_error (DBUS_ERROR_ACCESS_DENIED, NULL,
974 "Cannot send message - message rejected due to internal libdbuspolicy error (Cynara)",
979 reply = reply_with_error (DBUS_ERROR_ACCESS_DENIED, NULL,
980 "Cannot send message - unknown libdbuspolicy error",
991 if (check_sync_reply)
997 /* puts locally generated reply into received messages queue */
998 if (!add_message_to_received (reply, transport->base.connection))
1003 } /* ret != DBUSPOLICY_RESULT_ALLOW */
1004 } /* check_privileges */
1007 if (send_message (transport,
1010 dbus_message_get_destination (message),
1011 dbus_message_get_auto_start (message),
1015 DBusMessage *reply = NULL;
1017 if (dbus_error_is_set (&error))
1019 reply = reply_with_error (error.name,
1023 dbus_error_free(&error);
1032 if (check_sync_reply)
1034 *sync_reply = reply;
1038 /* puts locally generated reply into received messages queue */
1039 if (!add_message_to_received (reply, transport->base.connection))
1046 if (check_sync_reply)
1049 int size, ret, *fds;
1053 /* check message size */
1054 size = kdbus_message_size (msg_reply, &n_fds);
1058 kdbus_close_message (transport, msg_reply);
1062 /* alloc buffer for decoded message */
1063 data = dbus_malloc (sizeof (char) * size);
1067 kdbus_close_message (transport, msg_reply);
1071 /* alloc palce for fds */
1072 fds = dbus_malloc (sizeof (int) * (n_fds + 1));
1076 kdbus_close_message (transport, msg_reply);
1081 /* decode dbus message */
1082 ret = kdbus_decode_dbus_message (msg_reply, data,
1083 transport, fds, &n_fds);
1087 kdbus_close_message (transport, msg_reply);
1092 _dbus_string_init_const_len (&str, data, ret);
1094 /* create DBusMessage from kmsg */
1095 *sync_reply = _dbus_decode_kmsg (&str, msg_reply->src_id, fds, n_fds);
1096 if (*sync_reply == NULL)
1099 kdbus_close_message (transport, msg_reply);
1106 _kdbus_free_msg (msg);
1114 * Sends DBus message using kdbus.
1115 * Handles broadcasts and unicast messages, and passing of Unix fds.
1116 * Also can locally generate error replies on some error returned by kernel.
1118 * TODO refactor to be more compact - maybe we can send header always as a payload vector
1119 * and only message body as memfd if needed.
1121 * @param transport Transport.
1122 * @param message DBus message to be sent
1123 * @param destination Destination of the message.
1124 * @returns bytes sent or -1 if sending failed
1127 kdbus_write_msg (DBusTransportKdbus *transport,
1128 DBusMessage *message,
1129 const char *destination)
1131 return kdbus_write_msg_internal (transport, message, destination, NULL, TRUE);
1134 static dbus_uint64_t
1135 get_pool_size (void)
1137 dbus_uint64_t receive_pool_size = RECEIVE_POOL_SIZE_DEFAULT_SIZE;
1138 const char *env_pool;
1140 env_pool = _dbus_getenv (RECEIVE_POOL_SIZE_ENV_VAR_NAME);
1143 dbus_uint64_t size = 0;
1144 unsigned int multiply = 1;
1147 page_size = sysconf (_SC_PAGESIZE);
1148 if (page_size == -1)
1154 size = strtoul (env_pool, (char**)&env_pool, 10);
1155 if ((errno == EINVAL) || size == 0)
1161 if (*env_pool == 'k')
1166 else if (*env_pool == 'M')
1168 multiply = 1024 * 1024;
1172 if (*env_pool != '\0')
1178 receive_pool_size = size * multiply;
1180 if ((receive_pool_size > RECEIVE_POOL_SIZE_MAX_MBYTES * 1024 * 1024) ||
1181 (receive_pool_size < RECEIVE_POOL_SIZE_MIN_KBYTES * 1024) ||
1182 ((receive_pool_size & (page_size - 1)) != 0)) //pool size must be aligned to page size
1188 _dbus_warn ("%s value is invalid, default value %luB will be used.\n", RECEIVE_POOL_SIZE_ENV_VAR_NAME,
1189 RECEIVE_POOL_SIZE_DEFAULT_SIZE);
1190 _dbus_warn ("Correct value must be between %ukB and %uMB and must be aligned to page size: %ldB.\n",
1191 RECEIVE_POOL_SIZE_MIN_KBYTES, RECEIVE_POOL_SIZE_MAX_MBYTES, page_size);
1193 receive_pool_size = RECEIVE_POOL_SIZE_DEFAULT_SIZE;
1197 _dbus_verbose ("Receive pool size set to %llu.\n", (unsigned long long)receive_pool_size);
1198 return receive_pool_size;
1201 static dbus_uint64_t
1202 get_attach_flags_recv (DBusTransportKdbus *transport)
1204 dbus_uint64_t attach_flags_recv = 0;
1206 #ifdef LIBDBUSPOLICY
1207 attach_flags_recv = KDBUS_ATTACH_CREDS | KDBUS_ATTACH_NAMES | KDBUS_ATTACH_SECLABEL;
1210 return attach_flags_recv;
1214 * Performs kdbus hello - registration on the kdbus bus
1215 * needed to send and receive messages on the bus,
1216 * and configures transport.
1217 * As a result unique id on he bus is obtained.
1219 * @see KDBUS_HELLO_* flags in <linux/kdbus.h>
1221 * @param transport transport structure
1222 * @param registration_flags aditional flags to modify registration process
1223 * @returns #TRUE on success
1226 bus_register_kdbus (DBusTransportKdbus *transport,
1227 dbus_uint32_t registration_flags,
1231 dbus_uint64_t flags;
1233 #ifdef LIBDBUSPOLICY
1234 void *policy = dbuspolicy1_init_shared (_kdbus_get_path(transport->kdbus),
1235 _kdbus_get_fd(transport->kdbus));
1238 dbus_set_error (error,
1239 DBUS_ERROR_NO_REPLY,
1240 "Did not receive a reply. Possible causes include: couldn't load dbus policy for kdbus transport or the message bus security policy blocked the reply.");
1244 transport->policy = policy;
1247 flags = KDBUS_HELLO_ACCEPT_FD;
1248 if (registration_flags & REGISTER_FLAG_MONITOR)
1249 flags |= KDBUS_HELLO_MONITOR;
1251 ret = _kdbus_hello (transport->kdbus,
1254 get_attach_flags_recv (transport),
1256 transport->activator,
1260 dbus_set_error (error, DBUS_ERROR_FAILED, "Hello failed: %d", -ret);
1261 #ifdef LIBDBUSPOLICY
1262 dbuspolicy1_free (policy);
1267 #ifdef LIBDBUSPOLICY
1268 dbuspolicy1_init_set_pool (transport->policy, _kdbus_get_pool(transport->kdbus));
1271 transport->my_DBus_unique_name = create_unique_name_from_unique_id (_kdbus_get_id (transport->kdbus));
1272 if (NULL == transport->my_DBus_unique_name)
1274 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, "Hello post failed: %d", -ret);
1275 #ifdef LIBDBUSPOLICY
1276 dbuspolicy1_free (policy);
1281 _dbus_verbose ("-- Our peer ID is: %llu\n", (unsigned long long)_kdbus_get_id (transport->kdbus));
1287 can_own (DBusTransportKdbus *transport,
1290 dbus_bool_t result = TRUE;
1292 #ifdef LIBDBUSPOLICY
1293 if (NULL != transport->policy)
1294 result = (dbuspolicy1_can_own (transport->policy, name) == 1);
1301 request_DBus_name (DBusTransportKdbus *transport,
1306 DBusString service_name_real;
1307 const DBusString *service_name = &service_name_real;
1309 dbus_uint32_t flags;
1311 if (!dbus_message_get_args (msg, error,
1312 DBUS_TYPE_STRING, &name,
1313 DBUS_TYPE_UINT32, &flags,
1317 _dbus_string_init_const (&service_name_real, name);
1319 if (!_dbus_validate_bus_name (service_name, 0,
1320 _dbus_string_get_length (service_name)))
1322 dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1323 "Requested bus name \"%s\" is not valid", name);
1325 _dbus_verbose ("Attempt to acquire invalid service name\n");
1330 if (_dbus_string_get_byte (service_name, 0) == ':')
1332 /* Not allowed; only base services can start with ':' */
1333 dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1334 "Cannot acquire a service starting with ':' such as \"%s\"", name);
1336 _dbus_verbose ("Attempt to acquire invalid base service name \"%s\"", name);
1341 if (_dbus_string_equal_c_str (service_name, DBUS_SERVICE_DBUS))
1343 dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1344 "Connection is not allowed to own the service \"%s\"because "
1345 "it is reserved for D-Bus' use only", DBUS_SERVICE_DBUS);
1349 if (!can_own (transport, name))
1351 dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1352 "Connection \"%s\" is not allowed to own the "
1353 "service \"%s\" due to security policies",
1354 transport->my_DBus_unique_name,
1359 *result = _kdbus_request_name (transport->kdbus, name, flags);
1360 if (*result == -EPERM)
1362 dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1363 "Kdbus doesn't allow %s to own the service \"%s\"",
1364 transport->my_DBus_unique_name, _dbus_string_get_const_data (service_name));
1367 else if (*result < 0)
1369 dbus_set_error (error, DBUS_ERROR_FAILED , "Name \"%s\" could not be acquired, %d, %m", name, errno);
1377 release_DBus_name (DBusTransportKdbus *transport,
1383 DBusString service_name;
1385 if (!dbus_message_get_args (msg, error,
1386 DBUS_TYPE_STRING, &name,
1390 _dbus_string_init_const (&service_name, name);
1392 if (!_dbus_validate_bus_name (&service_name, 0,
1393 _dbus_string_get_length (&service_name)))
1395 dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1396 "Given bus name \"%s\" is not valid",
1397 _dbus_string_get_const_data (&service_name));
1399 _dbus_verbose ("Attempt to release invalid service name\n");
1403 if (_dbus_string_get_byte (&service_name, 0) == ':')
1405 /* Not allowed; the base service name cannot be created or released */
1406 dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1407 "Cannot release a service starting with ':' such as \"%s\"",
1408 _dbus_string_get_const_data (&service_name));
1410 _dbus_verbose ("Attempt to release invalid base service name \"%s\"",
1411 _dbus_string_get_const_data (&service_name));
1415 if (_dbus_string_equal_c_str (&service_name, DBUS_SERVICE_DBUS))
1417 /* Not allowed; the base service name cannot be created or released */
1418 dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
1419 "Cannot release the %s service because it is owned by the bus",
1422 _dbus_verbose ("Attempt to release service name \"%s\"",
1427 *result = _kdbus_release_name (transport->kdbus, name);
1430 dbus_set_error (error, DBUS_ERROR_FAILED , "Name \"%s\" could not be released, %d, %m", name, errno);
1438 strcmp_existing (const char *str1, const char *str2)
1440 if (NULL == str1 || NULL == str2)
1442 return strcmp (str1, str2);
1446 is_bloom_needed (MatchRule *rule)
1451 if (_match_rule_get_message_type (rule) != DBUS_TYPE_INVALID
1452 || _match_rule_get_interface (rule) != NULL
1453 || _match_rule_get_member (rule) != NULL
1454 || _match_rule_get_path (rule) != NULL
1455 || _match_rule_get_path_namespace (rule) != NULL)
1458 rule_int = _match_rule_get_args_len (rule);
1459 for (i = 0; i < rule_int; i++)
1461 if (_match_rule_get_args (rule, i) != NULL)
1469 get_bloom (kdbus_t *kdbus, MatchRule *rule, kdbus_bloom_data_t *bloom_data)
1472 const char *rule_string;
1474 char argument_buf[sizeof ("arg")-1 + 2 + sizeof ("-slash-prefix") +1];
1476 rule_int = _match_rule_get_message_type (rule);
1477 if (rule_int != DBUS_MESSAGE_TYPE_INVALID)
1479 bloom_add_pair (bloom_data, kdbus, "message-type", dbus_message_type_to_string (rule_int));
1480 _dbus_verbose ("Adding type %s \n", dbus_message_type_to_string (rule_int));
1483 rule_string = _match_rule_get_interface (rule);
1484 if (rule_string != NULL)
1486 bloom_add_pair (bloom_data, kdbus, "interface", rule_string);
1487 _dbus_verbose ("Adding interface %s \n", rule_string);
1490 rule_string = _match_rule_get_member (rule);
1491 if (rule_string != NULL)
1493 bloom_add_pair (bloom_data, kdbus, "member", rule_string);
1494 _dbus_verbose ("Adding member %s \n", rule_string);
1497 rule_string = _match_rule_get_path (rule);
1498 if (rule_string != NULL)
1500 bloom_add_pair (bloom_data, kdbus, "path", rule_string);
1501 _dbus_verbose ("Adding path %s \n", rule_string);
1504 rule_string = _match_rule_get_path_namespace (rule);
1505 if (rule_string != NULL)
1507 bloom_add_pair (bloom_data, kdbus, "path-slash-prefix", rule_string);
1508 _dbus_verbose ("Adding path-slash-prefix %s \n", rule_string);
1511 rule_int = _match_rule_get_args_len (rule);
1512 for (i = 0; i < rule_int; i++)
1514 rule_string = _match_rule_get_args (rule, i);
1515 if (rule_string != NULL)
1517 unsigned int rule_arg_lens = _match_rule_get_arg_lens (rule, i);
1518 if (rule_arg_lens & MATCH_ARG_IS_PATH)
1520 snprintf (argument_buf, sizeof (argument_buf), "arg%d-slash-prefix", i);
1521 bloom_add_prefixes (bloom_data, kdbus, argument_buf, rule_string, '/');
1523 else if (rule_arg_lens & MATCH_ARG_NAMESPACE)
1525 snprintf (argument_buf, sizeof (argument_buf), "arg%d-dot-prefix", i);
1526 bloom_add_prefixes (bloom_data, kdbus, argument_buf, rule_string, '.');
1530 snprintf (argument_buf, sizeof (argument_buf), "arg%d", i);
1531 bloom_add_pair (bloom_data, kdbus, argument_buf, rule_string);
1538 * Adds a match rule to match broadcast messages going through the message bus.
1539 * Do no affect messages addressed directly.
1541 * TODO add error reporting
1543 * @param transport transport
1547 add_match_kdbus (DBusTransportKdbus *transport,
1550 struct kdbus_cmd_match *cmd;
1551 struct kdbus_item *item;
1553 uint64_t src_id = KDBUS_MATCH_ID_ANY;
1555 dbus_bool_t need_bloom = FALSE;
1557 const char *rule_sender;
1558 const char *rule_arg0 = NULL;
1561 rule_cookie = match_rule_get_cookie (rule);
1562 rule_sender = _match_rule_get_sender (rule);
1565 * First check if it is org.freedesktop.DBus's NameOwnerChanged or any
1566 * org.freedesktop.DBus combination that includes this,
1567 * because it must be converted to special kdbus rule (kdbus has separate rules
1568 * for kdbus (kernel) generated broadcasts).
1570 if (!strcmp_existing (rule_sender, DBUS_SERVICE_DBUS))
1572 int message_type = _match_rule_get_message_type (rule);
1574 if ((DBUS_MESSAGE_TYPE_INVALID == message_type || DBUS_MESSAGE_TYPE_SIGNAL == message_type)
1575 && !strcmp_existing (_match_rule_get_interface (rule), DBUS_INTERFACE_DBUS)
1576 && !strcmp_existing (_match_rule_get_path (rule), DBUS_PATH_DBUS))
1578 if (_match_rule_get_args_len(rule) == 1)
1580 rule_arg0 = _match_rule_get_args(rule, 0);
1584 _dbus_string_init_const (&str, rule_arg0);
1585 ret = _dbus_validate_bus_name (&str, 0, _dbus_string_get_length (&str));
1590 if (!strcmp_existing (_match_rule_get_member (rule), "NameOwnerChanged"))
1592 ret = _kdbus_add_match_name_change (transport->kdbus,
1602 _dbus_verbose ("Failed adding match rule for name removal for daemon, error: %d, %s\n",
1603 ret, _dbus_strerror (ret));
1607 _dbus_verbose ("Added match rule for kernel correctly.\n");
1609 ret = _kdbus_add_match_id_change (transport->kdbus,
1617 _dbus_verbose ("Failed adding match rule for adding id for daemon, error: %d, %s\n",
1618 ret, _dbus_strerror (ret));
1622 else if (strcmp (_match_rule_get_member (rule), "NameAcquired") == 0)
1624 ret = _kdbus_add_match_name_acquired (transport->kdbus,
1629 _kdbus_get_id (transport->kdbus),
1634 _dbus_verbose ("Failed adding match rule for name removal for daemon, error: %d, %s\n",
1635 ret, _dbus_strerror (ret));
1639 else if (strcmp (_match_rule_get_member (rule), "NameLost") == 0)
1641 ret = _kdbus_add_match_name_lost (transport->kdbus,
1644 _kdbus_get_id (transport->kdbus),
1651 _dbus_verbose ("Failed adding match rule for name removal for daemon, error: %d, %s\n",
1652 ret, _dbus_strerror (ret));
1657 /* Sender=DBUS_SERVICE_DBUS matches (as opposed to wildcard sender) need no standard rule. */
1663 * standard rule - registered in general way, for non-kernel broadcasts
1664 * kdbus doesn't use it to check kdbus (kernel) generated broadcasts
1667 need_bloom = is_bloom_needed (rule);
1669 if (rule_sender != NULL)
1672 _dbus_string_init_const (&str, rule_sender);
1674 if (!_dbus_validate_bus_name (&str, 0, _dbus_string_get_length (&str)))
1677 src_id = parse_name (rule_sender);
1679 /* well-known name */
1680 src_id = KDBUS_MATCH_ID_ANY;
1686 items_size = _kdbus_compute_match_items_size (transport->kdbus,
1691 cmd = _kdbus_new_cmd_match (transport->kdbus,
1700 if (NULL != rule_sender) /* well-known name */
1702 item = _kdbus_item_add_string (item,
1705 strlen (rule_sender) + 1);
1706 _dbus_verbose ("Adding sender %s \n", rule_sender);
1708 else if (KDBUS_MATCH_ID_ANY != src_id) /* unique id */
1710 item = _kdbus_item_add_id (item, src_id);
1711 _dbus_verbose ("Adding src_id %llu \n", (unsigned long long)src_id);
1717 item = _kdbus_item_add_bloom_mask (item, transport->kdbus, &bloom);
1718 get_bloom (transport->kdbus, rule, bloom);
1721 ret = _kdbus_add_match (transport->kdbus, cmd);
1723 _kdbus_free_cmd_match (cmd);
1728 _dbus_verbose ("Failed adding match bus rule cookie %llu,\nerror: %d, %s\n",
1729 rule_cookie, ret, _dbus_strerror (ret));
1733 _dbus_verbose ("Added match bus rule %llu\n", rule_cookie);
1737 static DBusMessage *
1738 capture_org_freedesktop_DBus_Hello (DBusTransportKdbus *transport,
1739 DBusMessage *message,
1742 DBusMessageIter args;
1743 dbus_uint32_t registration_flags = 0;
1745 dbus_message_iter_init (message, &args);
1746 if (dbus_message_iter_get_arg_type (&args) == DBUS_TYPE_UINT32)
1747 dbus_message_iter_get_basic (&args, ®istration_flags);
1749 if (!bus_register_kdbus (transport, registration_flags, error))
1752 return reply_1_data (message, DBUS_TYPE_STRING, &transport->my_DBus_unique_name);
1755 free (transport->my_DBus_unique_name);
1759 static DBusMessage *
1760 capture_org_freedesktop_DBus_RequestName (DBusTransportKdbus *transport,
1761 DBusMessage *message,
1766 if (!request_DBus_name (transport, message, &result, error))
1769 return reply_1_data (message, DBUS_TYPE_UINT32, &result);
1772 static DBusMessage *
1773 capture_org_freedesktop_DBus_ReleaseName (DBusTransportKdbus *transport,
1774 DBusMessage *message,
1779 if (!release_DBus_name (transport, message, &result, error))
1782 return reply_1_data (message, DBUS_TYPE_UINT32, &result);
1785 static DBusMessage *
1786 capture_org_freedesktop_DBus_AddMatch (DBusTransportKdbus *transport,
1787 DBusMessage *message,
1792 MatchRule *rule = NULL;
1793 DBusConnection *connection = transport->base.connection;
1795 if (!dbus_message_get_args (message, error,
1796 DBUS_TYPE_STRING, &arg,
1800 _dbus_string_init_const (&arg_str, arg);
1802 rule = match_rule_parse (connection, &arg_str, error);
1806 if (!matchmaker_add_rule (transport->matchmaker, rule))
1808 dbus_set_error_const (error, DBUS_ERROR_NO_MEMORY, "No memory to store match rule");
1812 if (!add_match_kdbus (transport, rule))
1814 dbus_set_error (error, _dbus_error_from_errno (errno), "Could not add match rule, %s",
1815 _dbus_strerror_from_errno ());
1819 match_rule_unref (rule);
1820 return dbus_message_new_method_return (message);
1824 match_rule_unref (rule);
1825 _dbus_verbose ("Error during AddMatch in lib: %s, %s\n", error->name, error->message);
1829 static dbus_uint64_t
1830 get_match_cookie_for_remove (Matchmaker *matchmaker, MatchRule *rule_to_remove)
1832 DBusList *rules = matchmaker_get_rules_list (matchmaker, rule_to_remove);
1835 DBusList *link = _dbus_list_get_last_link (&rules);
1836 while (NULL != link)
1838 if (match_rule_equal_lib (link->data, rule_to_remove))
1840 return match_rule_get_cookie (link->data);
1842 link = _dbus_list_get_prev_link (&rules, link);
1848 static DBusMessage *
1849 capture_org_freedesktop_DBus_RemoveMatch (DBusTransportKdbus *transport,
1850 DBusMessage *message,
1855 MatchRule *rule = NULL;
1856 DBusConnection *connection = transport->base.connection;
1857 dbus_uint64_t cookie;
1859 if (!dbus_message_get_args (message, error,
1860 DBUS_TYPE_STRING, &arg,
1864 _dbus_string_init_const (&arg_str, arg);
1866 rule = match_rule_parse (connection, &arg_str, error);
1869 cookie = get_match_cookie_for_remove (transport->matchmaker, rule);
1872 dbus_set_error (error,
1873 DBUS_ERROR_MATCH_RULE_NOT_FOUND,
1874 "The given match rule wasn't found and can't be removed");
1878 int ret = _kdbus_remove_match (transport->kdbus, cookie);
1880 dbus_set_error (error,
1881 _dbus_error_from_errno (ret),
1882 "Could not remove match rule");
1884 if (!dbus_error_is_set (error))
1885 matchmaker_remove_rule_by_value (transport->matchmaker, rule, error);
1888 match_rule_unref (rule);
1891 if (dbus_error_is_set (error))
1893 _dbus_verbose ("Error during RemoveMatch in lib: %s, %s\n",
1899 return dbus_message_new_method_return (message);
1903 get_connection_info_by_name (DBusMessage *message,
1905 struct nameInfo *info,
1906 DBusTransportKdbus *transport,
1908 dbus_bool_t getLabel)
1911 if (!dbus_validate_bus_name (name, error))
1914 if ((ret = _kdbus_connection_info_by_name (transport->kdbus, name, getLabel, info)) != 0)
1916 if (ESRCH == ret || ENXIO == ret)
1917 dbus_set_error (error, DBUS_ERROR_NAME_HAS_NO_OWNER,
1918 "Could not get owner of name '%s': no such name", name);
1920 dbus_set_error (error, DBUS_ERROR_FAILED,
1921 "Unable to query name %s, returned %d, errno = %d (%m).",
1925 if (info->flags & KDBUS_HELLO_ACTIVATOR)
1927 dbus_set_error (error, DBUS_ERROR_NAME_HAS_NO_OWNER,
1928 "Could not get owner of name '%s'", name);
1929 /* we return ESRCH - this is an indicator that name has an activator */
1935 /* This local function handles common case for org.freedesktop.DBus method handlers:
1936 * 1. gets string argument from incoming message;
1937 * 2. gets connection info for such name.
1938 * Note: if getLabel argument is set to TRUE, the caller must free info.sec_label.
1941 get_connection_info_from_message_argument (DBusMessage *message,
1943 struct nameInfo *info,
1944 DBusTransportKdbus *transport,
1945 dbus_bool_t getLabel)
1949 if (!dbus_message_get_args (message, error,
1950 DBUS_TYPE_STRING, &arg,
1954 return get_connection_info_by_name (message, error, info, transport, arg, getLabel);
1957 static DBusMessage *
1958 capture_org_freedesktop_DBus_GetConnectionCredentials (DBusTransportKdbus *transport,
1959 DBusMessage *message,
1962 DBusMessage *reply = NULL;
1963 DBusMessageIter reply_iter;
1964 DBusMessageIter array_iter;
1965 struct nameInfo info;
1967 if (get_connection_info_from_message_argument (message, error, &info, transport, TRUE) != 0)
1970 reply = _dbus_asv_new_method_return (message, &reply_iter, &array_iter);
1974 /* we can't represent > 32-bit pids; if your system needs them, please
1975 * add ProcessID64 to the spec or something */
1976 if (info.processId <= _DBUS_UINT32_MAX)
1978 if (!_dbus_asv_add_uint32 (&array_iter, "ProcessID", info.processId))
1981 /* we can't represent > 32-bit uids; if your system needs them, please
1982 * add UnixUserID64 to the spec or something */
1983 if (info.userId <= _DBUS_UINT32_MAX)
1985 if (!_dbus_asv_add_uint32 (&array_iter, "UnixUserID", info.userId))
1989 if (info.sec_label != NULL)
1991 dbus_bool_t res = _dbus_asv_add_byte_array (&array_iter,
1992 "LinuxSecurityLabel",
1994 info.sec_label_len);
1996 dbus_free (info.sec_label);
2002 if (!_dbus_asv_close (&reply_iter, &array_iter))
2005 if (!dbus_message_set_sender (reply, DBUS_SERVICE_DBUS))
2011 _dbus_asv_abandon (&reply_iter, &array_iter);
2012 dbus_message_unref (reply);
2018 _mac_smack_use (void)
2020 static int cached_use = -1;
2023 cached_use = access("/sys/fs/smackfs/", F_OK) >= 0;
2028 static DBusMessage *
2029 capture_org_freedesktop_DBus_GetConnectionSELinuxSecurityContext (DBusTransportKdbus *transport,
2030 DBusMessage *message,
2033 struct nameInfo info;
2035 if (get_connection_info_from_message_argument (message, error, &info, transport, TRUE) != 0)
2038 if (info.sec_label != NULL)
2040 if (_mac_smack_use())
2042 dbus_set_error (error, DBUS_ERROR_SELINUX_SECURITY_CONTEXT_UNKNOWN,
2043 "Could not determine security context");
2044 dbus_free (info.sec_label);
2050 reply = reply_fixed_array (message, DBUS_TYPE_BYTE,
2052 info.sec_label_len);
2054 dbus_free (info.sec_label);
2060 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED, "Operation not supported");
2066 static DBusMessage *
2067 capture_org_freedesktop_DBus_GetConnectionUnixProcessID (DBusTransportKdbus *transport,
2068 DBusMessage *message,
2071 struct nameInfo info;
2072 dbus_uint32_t processId;
2074 if (get_connection_info_from_message_argument (message, error, &info, transport, FALSE) != 0 ||
2075 info.processId > _DBUS_UINT32_MAX)
2078 processId = info.processId;
2080 return reply_1_data (message, DBUS_TYPE_UINT32, &processId);
2083 static DBusMessage *
2084 capture_org_freedesktop_DBus_GetConnectionUnixUser (DBusTransportKdbus *transport,
2085 DBusMessage *message,
2088 struct nameInfo info;
2089 dbus_uint32_t userId;
2091 if (get_connection_info_from_message_argument (message, error, &info, transport, FALSE) != 0 ||
2092 info.userId > _DBUS_UINT32_MAX)
2095 userId = info.userId;
2097 return reply_1_data (message, DBUS_TYPE_UINT32, &userId);
2100 static DBusMessage *
2101 capture_org_freedesktop_DBus_GetId (DBusTransportKdbus *transport,
2102 DBusMessage *message,
2105 dbus_uint64_t bus_id_size = _kdbus_get_bus_id_size ();
2106 char bus_id[bus_id_size*2+1];
2107 char *bus_id_ptr = bus_id;
2108 char *bus_id_original = _kdbus_get_bus_id (transport->kdbus);
2109 dbus_uint64_t i = 0;
2110 for (; i < bus_id_size; i++)
2111 snprintf (bus_id + 2*i, sizeof (bus_id) - 2*i, "%02x", bus_id_original[i]);
2112 return reply_1_data (message, DBUS_TYPE_STRING, &bus_id_ptr);
2115 static DBusMessage *
2116 capture_org_freedesktop_DBus_GetNameOwner (DBusTransportKdbus *transport,
2117 DBusMessage *message,
2121 struct nameInfo info;
2125 if (!dbus_message_get_args (message, error,
2126 DBUS_TYPE_STRING, &arg,
2130 if (strcmp (arg, DBUS_SERVICE_DBUS) == 0)
2132 if (-1 == asprintf (&unique_name, "%s", DBUS_SERVICE_DBUS))
2137 if (get_connection_info_by_name (message, error, &info, transport, arg, FALSE) != 0)
2140 unique_name = create_unique_name_from_unique_id (info.uniqueId);
2141 if (NULL == unique_name)
2145 reply = reply_1_data (message, DBUS_TYPE_STRING, &unique_name);
2152 static DBusMessage *
2153 reply_listNames (DBusTransportKdbus *transport,
2154 DBusMessage *message,
2156 dbus_uint64_t flags)
2158 DBusMessage *reply = NULL;
2159 dbus_uint64_t prev_id = 0;
2161 /* First, get the list from kdbus */
2163 struct kdbus_info *name_list, *name;
2166 DBusMessageIter iter;
2167 DBusMessageIter array_iter;
2169 ret = _kdbus_list (transport->kdbus,
2175 dbus_set_error (error, DBUS_ERROR_FAILED, "Error listing names");
2179 /* Compose the reply on the fly */
2180 reply = dbus_message_new_method_return (message);
2184 dbus_message_iter_init_append (reply, &iter);
2185 if (!dbus_message_iter_open_container (&iter,
2187 DBUS_TYPE_STRING_AS_STRING,
2191 KDBUS_FOREACH (name, name_list, list_size)
2193 struct kdbus_item *item;
2195 if ((flags & KDBUS_LIST_UNIQUE) && name->id != prev_id)
2199 char *unique_name = create_unique_name_from_unique_id (name->id);
2201 if (NULL == unique_name)
2204 res = dbus_message_iter_append_basic (&array_iter,
2213 KDBUS_ITEM_FOREACH (item, name, items)
2215 if (item->type == KDBUS_ITEM_OWNED_NAME)
2217 char *name_ptr = item->name.name;
2219 if (!dbus_validate_bus_name (name_ptr, NULL))
2222 if (flags & KDBUS_LIST_QUEUED)
2223 name_ptr = create_unique_name_from_unique_id (name->id);
2225 if (NULL == name_ptr)
2228 if (!dbus_message_iter_append_basic (&array_iter,
2232 if (flags & KDBUS_LIST_QUEUED)
2237 if (flags & KDBUS_LIST_QUEUED)
2243 if (!dbus_message_iter_close_container (&iter, &array_iter))
2246 if (!dbus_message_set_sender (reply, DBUS_SERVICE_DBUS))
2249 _kdbus_free_mem (transport->kdbus, name_list);
2254 dbus_message_iter_abandon_container (&iter, &array_iter);
2257 dbus_message_unref (reply);
2259 _kdbus_free_mem (transport->kdbus, name_list);
2263 static DBusMessage *
2264 capture_org_freedesktop_DBus_ListActivatableNames (DBusTransportKdbus *transport,
2265 DBusMessage *message,
2268 return reply_listNames (transport, message, error, KDBUS_LIST_ACTIVATORS);
2271 static DBusMessage *
2272 capture_org_freedesktop_DBus_ListNames (DBusTransportKdbus *transport,
2273 DBusMessage *message,
2276 return reply_listNames (transport, message, error, KDBUS_LIST_UNIQUE | KDBUS_LIST_NAMES);
2279 static DBusMessage *
2280 capture_org_freedesktop_DBus_ListQueuedOwners (DBusTransportKdbus *transport,
2281 DBusMessage *message,
2284 struct nameInfo info;
2286 if (get_connection_info_from_message_argument (message, error, &info, transport, FALSE) != 0)
2289 return reply_listNames (transport, message, error, KDBUS_LIST_QUEUED);
2292 static DBusMessage *
2293 capture_org_freedesktop_DBus_NameHasOwner (DBusTransportKdbus *transport,
2294 DBusMessage *message,
2297 struct nameInfo info;
2298 dbus_bool_t result = TRUE;
2300 if (get_connection_info_from_message_argument (message, error, &info, transport, FALSE) != 0)
2302 if (dbus_error_is_set (error) && dbus_error_has_name (error, DBUS_ERROR_NAME_HAS_NO_OWNER))
2305 dbus_error_free (error);
2311 return reply_1_data (message, DBUS_TYPE_BOOLEAN, &result);
2314 static DBusMessage *
2315 capture_org_freedesktop_DBus_ReloadConfig (DBusTransportKdbus *transport,
2316 DBusMessage *message,
2319 DBusMessageIter iter;
2320 DBusMessage *reply = NULL;
2322 dbus_message_iter_init (message, &iter);
2323 if (dbus_message_iter_get_arg_type (&iter) != DBUS_TYPE_STRUCT)
2325 dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
2326 "Call to 'ReloadConfig' has wrong args");
2330 reply = dbus_message_new_method_return (message);
2334 if (!dbus_message_set_sender (reply, DBUS_SERVICE_DBUS))
2340 dbus_message_unref (reply);
2344 static DBusMessage *
2345 capture_org_freedesktop_DBus_StartServiceByName (DBusTransportKdbus *transport,
2346 DBusMessage *message,
2349 struct nameInfo info;
2351 dbus_uint32_t flags; /* Spec says: not used, but we check the syntax anyway */
2353 dbus_bool_t dbus_service = FALSE;
2355 if (!dbus_message_get_args (message, error,
2356 DBUS_TYPE_STRING, &name,
2357 DBUS_TYPE_UINT32, &flags,
2361 dbus_service = (strncmp (name, DBUS_SERVICE_DBUS, strlen (DBUS_SERVICE_DBUS) + 1) == 0);
2364 ret = get_connection_info_by_name (message,
2371 if (dbus_service || 0 == ret)
2373 dbus_uint32_t status = DBUS_START_REPLY_ALREADY_RUNNING;
2374 return reply_1_data (message, DBUS_TYPE_UINT32, &status);
2376 else if (-ESRCH == ret) /* there is an activator */
2378 DBusMessage *sub_message;
2380 /* if we are here, then we have error set - free place for possible real error */
2381 dbus_error_free (error);
2383 /* send method call to org.freedesktop.DBus.Peer.Ping */
2384 sub_message = dbus_message_new_method_call (name, "/", DBUS_INTERFACE_PEER, "Ping");
2385 if (sub_message == NULL)
2388 /* The serial number here is set to -1. A message needs a valid serial number.
2389 * We do not have access to connection's serial numbers counter, so we need to make up one.
2390 * -1 is the last valid serial, so we hope that we'll never get there, especially with 64-bit
2393 dbus_message_set_serial (sub_message, -1);
2395 dbus_message_lock (sub_message);
2397 ret = kdbus_write_msg_internal (transport, sub_message, name, NULL, FALSE);
2399 dbus_message_unref (sub_message);
2405 dbus_uint32_t status = DBUS_START_REPLY_SUCCESS;
2406 return reply_1_data (message, DBUS_TYPE_UINT32, &status);
2412 * There was an error set in get_connection_info_by_name()
2413 * We want to have another error return from StartServiceByName.
2415 dbus_error_free (error);
2416 dbus_set_error (error,
2417 DBUS_ERROR_SERVICE_UNKNOWN,
2418 "The name %s was not provided by any .service files",
2425 static DBusMessage *
2426 capture_org_freedesktop_DBus_UpdateActivationEnvironment (DBusTransportKdbus *transport,
2427 DBusMessage *message,
2430 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
2431 "'%s' method not supported", dbus_message_get_member (message));
2435 typedef DBusMessage * (*CaptureHandler)(DBusTransportKdbus *, DBusMessage *, DBusError *);
2436 struct CaptureHandlers {
2437 const char *method_name;
2438 CaptureHandler handler;
2441 #define HANDLER_ELEMENT(x) {#x, capture_org_freedesktop_DBus_##x}
2443 /* This is to cut the code to parts, and keep it organized:
2444 * an array of elements of type, as in example:
2445 * { "RequestName", capture_org_freedesktop_DBus_RequestName }
2446 * That is, a method of name RequestName will be handled by capture_org_freedesktop_DBus_RequestName ().
2448 static struct CaptureHandlers capture_handlers[] =
2450 // "Hello" is handled separately
2451 // HANDLER_ELEMENT (Hello),
2452 HANDLER_ELEMENT (RequestName),
2453 HANDLER_ELEMENT (ReleaseName),
2454 HANDLER_ELEMENT (AddMatch),
2455 HANDLER_ELEMENT (RemoveMatch),
2456 HANDLER_ELEMENT (GetConnectionCredentials),
2457 HANDLER_ELEMENT (GetConnectionSELinuxSecurityContext),
2458 HANDLER_ELEMENT (GetConnectionUnixProcessID),
2459 HANDLER_ELEMENT (GetConnectionUnixUser),
2460 HANDLER_ELEMENT (GetId),
2461 HANDLER_ELEMENT (GetNameOwner),
2462 HANDLER_ELEMENT (ListActivatableNames),
2463 HANDLER_ELEMENT (ListNames),
2464 HANDLER_ELEMENT (ListQueuedOwners),
2465 HANDLER_ELEMENT (NameHasOwner),
2466 HANDLER_ELEMENT (ReloadConfig),
2467 HANDLER_ELEMENT (StartServiceByName),
2468 HANDLER_ELEMENT (UpdateActivationEnvironment)
2472 * Looks over messages sent to org.freedesktop.DBus. Hello message, which performs
2473 * registration on the bus, is captured as it must be locally converted into
2474 * appropriate ioctl. AddMatch and RemoveMatch are captured to store match rules
2475 * locally in case of false positive result of kdbus bloom filters, but after
2476 * being read they are passed to org.freedesktop.DBus to register these rules
2478 * All the rest org.freedesktop.DBus methods are left untouched
2479 * and they are sent to dbus-daemon in the same way as every other messages.
2481 * @param transport Transport
2482 * @param message Message being sent.
2484 1 if message is not captured and should be passed to kdbus
2485 * 0 if message was handled locally and correctly (it includes proper return of error reply),
2486 * -1 message to org.freedesktop.DBus was not handled correctly.
2489 capture_org_freedesktop_DBus (DBusTransportKdbus *transport,
2490 const char *destination,
2491 DBusMessage *message,
2492 DBusMessage **reply)
2495 if (!strcmp (destination, DBUS_SERVICE_DBUS))
2497 const char *interface = dbus_message_get_interface (message);
2498 if (interface && !strcmp (interface, DBUS_INTERFACE_DBUS))
2501 const char *member = dbus_message_get_member (message);
2503 _dbus_assert (member != NULL);
2505 dbus_error_init (&error);
2507 if (!strcmp (member, "Hello"))
2509 *reply = capture_org_freedesktop_DBus_Hello (transport, message, &error);
2514 int handlers_size = sizeof (capture_handlers)/sizeof (capture_handlers[0]);
2516 while (i < handlers_size && strcmp (member, capture_handlers[i].method_name) != 0)
2519 if (i < handlers_size)
2521 *reply = capture_handlers[i].handler (transport, message, &error);
2525 dbus_set_error (&error, DBUS_ERROR_UNKNOWN_METHOD,
2526 "org.freedesktop.DBus does not understand message %s", member);
2530 if (*reply == NULL && dbus_error_is_set (&error))
2532 *reply = reply_with_error ((char*)error.name,
2536 dbus_error_free (&error);
2544 } /* if DBUS_INTERFACE_DBUS */
2545 } /* if DBUS_SERVICE_DBUS */
2550 #ifdef DBUS_ENABLE_VERBOSE_MODE
2551 #define ENUM_NAME_ITEM(x) case x : return #x
2554 enum_MSG (long long id)
2558 ENUM_NAME_ITEM (_KDBUS_ITEM_NULL);
2559 ENUM_NAME_ITEM (KDBUS_ITEM_PAYLOAD_VEC);
2560 ENUM_NAME_ITEM (KDBUS_ITEM_PAYLOAD_OFF);
2561 ENUM_NAME_ITEM (KDBUS_ITEM_PAYLOAD_MEMFD);
2562 ENUM_NAME_ITEM (KDBUS_ITEM_FDS);
2563 ENUM_NAME_ITEM (KDBUS_ITEM_BLOOM_PARAMETER);
2564 ENUM_NAME_ITEM (KDBUS_ITEM_BLOOM_FILTER);
2565 ENUM_NAME_ITEM (KDBUS_ITEM_DST_NAME);
2566 ENUM_NAME_ITEM (KDBUS_ITEM_CREDS);
2567 ENUM_NAME_ITEM (KDBUS_ITEM_PID_COMM);
2568 ENUM_NAME_ITEM (KDBUS_ITEM_TID_COMM);
2569 ENUM_NAME_ITEM (KDBUS_ITEM_EXE);
2570 ENUM_NAME_ITEM (KDBUS_ITEM_CMDLINE);
2571 ENUM_NAME_ITEM (KDBUS_ITEM_CGROUP);
2572 ENUM_NAME_ITEM (KDBUS_ITEM_CAPS);
2573 ENUM_NAME_ITEM (KDBUS_ITEM_SECLABEL);
2574 ENUM_NAME_ITEM (KDBUS_ITEM_AUDIT);
2575 ENUM_NAME_ITEM (KDBUS_ITEM_CONN_DESCRIPTION);
2576 ENUM_NAME_ITEM (KDBUS_ITEM_NAME);
2577 ENUM_NAME_ITEM (KDBUS_ITEM_TIMESTAMP);
2578 ENUM_NAME_ITEM (KDBUS_ITEM_NAME_ADD);
2579 ENUM_NAME_ITEM (KDBUS_ITEM_NAME_REMOVE);
2580 ENUM_NAME_ITEM (KDBUS_ITEM_NAME_CHANGE);
2581 ENUM_NAME_ITEM (KDBUS_ITEM_ID_ADD);
2582 ENUM_NAME_ITEM (KDBUS_ITEM_ID_REMOVE);
2583 ENUM_NAME_ITEM (KDBUS_ITEM_REPLY_TIMEOUT);
2584 ENUM_NAME_ITEM (KDBUS_ITEM_REPLY_DEAD);
2589 #if KDBUS_MSG_DECODE_DEBUG == 1
2591 enum_PAYLOAD (long long id)
2595 ENUM_NAME_ITEM (KDBUS_PAYLOAD_KERNEL);
2596 ENUM_NAME_ITEM (KDBUS_PAYLOAD_DBUS);
2602 msg_id (uint64_t id)
2605 const char* const_ptr;
2612 snprintf (buf, sizeof (buf), "%llu", (unsigned long long)id);
2620 static dbus_uint32_t
2621 get_next_client_serial (DBusTransportKdbus *transport)
2623 dbus_uint32_t serial;
2625 serial = transport->client_serial++;
2627 if (transport->client_serial == 0)
2628 transport->client_serial = 1;
2634 * Calculates length of the kdbus message content (payload).
2636 * @param msg kdbus message
2637 * @return the length of the kdbus message's payload.
2640 kdbus_message_size (const struct kdbus_msg *msg,
2643 const struct kdbus_item *item;
2647 KDBUS_ITEM_FOREACH (item, msg, items)
2649 if (item->size < KDBUS_ITEM_HEADER_SIZE)
2651 _dbus_verbose (" +%s (%llu bytes) invalid data record\n", enum_MSG (item->type), item->size);
2656 case KDBUS_ITEM_PAYLOAD_OFF:
2657 ret_size += item->vec.size;
2659 case KDBUS_ITEM_PAYLOAD_MEMFD:
2660 ret_size += item->memfd.size;
2662 case KDBUS_ITEM_FDS:
2663 *n_fds = (item->size - KDBUS_ITEM_HEADER_SIZE) / sizeof (int);
2674 generate_NameSignal (const char *signal,
2676 DBusTransportKdbus *transport)
2678 DBusMessage *message;
2680 _dbus_verbose ("Generating %s for %s.\n", signal, name);
2682 message = dbus_message_new_signal (DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, signal);
2683 if (message == NULL)
2686 if (!dbus_message_append_args (message, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID))
2688 if (!dbus_message_set_destination (message, transport->my_DBus_unique_name))
2690 if (!dbus_message_set_sender (message, DBUS_SERVICE_DBUS))
2692 dbus_message_set_serial (message, get_next_client_serial (transport));
2694 if (!add_message_to_received (message, transport->base.connection))
2700 dbus_message_unref (message);
2705 * The NameOwnerChanged signals take three parameters with
2706 * unique or well-known names, but only some forms actually
2709 * WELLKNOWN, "", UNIQUE → KDBUS_ITEM_NAME_ADD
2710 * WELLKNOWN, UNIQUE, "" → KDBUS_ITEM_NAME_REMOVE
2711 * WELLKNOWN, UNIQUE, UNIQUE → KDBUS_ITEM_NAME_CHANGE
2712 * UNIQUE, "", UNIQUE → KDBUS_ITEM_ID_ADD
2713 * UNIQUE, UNIQUE, "" → KDBUS_ITEM_ID_REMOVE
2715 * For the latter two the two unique names must be identical.
2718 kdbus_handle_name_owner_changed (__u64 type,
2719 const char *bus_name,
2722 DBusTransportKdbus *transport)
2724 DBusMessage *message = NULL;
2725 DBusMessageIter args;
2727 const char *const_ptr;
2729 if ((message = dbus_message_new_signal (DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged")) == NULL)
2732 dbus_message_iter_init_append (message, &args);
2734 // for ID_ADD and ID_REMOVE this function takes NULL as bus_name
2735 if (bus_name == NULL)
2737 snprintf (tmp_str, sizeof (tmp_str), ":1.%llu", old != 0 ? old : new);
2738 const_ptr = tmp_str;
2741 const_ptr = bus_name;
2743 if (!dbus_message_iter_append_basic (&args, DBUS_TYPE_STRING, &const_ptr))
2746 _dbus_verbose ("%s\n", const_ptr);
2749 if ((old==0) && (new==0))
2751 /* kdbus generates its own set of events that can not be passed to
2752 * client without translation. */
2753 const char *src = "org.freedesktop.DBus";
2754 const char *dst = "org.freedesktop.DBus";
2756 if (type == KDBUS_ITEM_NAME_ADD || type == KDBUS_ITEM_ID_ADD)
2758 else if (type == KDBUS_ITEM_NAME_REMOVE || type == KDBUS_ITEM_ID_REMOVE)
2761 if (!dbus_message_iter_append_basic (&args, DBUS_TYPE_STRING, &src))
2763 if (!dbus_message_iter_append_basic (&args, DBUS_TYPE_STRING, &dst))
2766 _dbus_verbose ("[NameOwnerChanged:%s, old=%lld, new=%lld\n", __func__, old, new);
2770 // determine and append old_id
2773 snprintf (tmp_str, sizeof (tmp_str), ":1.%llu", old);
2774 const_ptr = tmp_str;
2779 if (!dbus_message_iter_append_basic (&args, DBUS_TYPE_STRING, &const_ptr))
2782 _dbus_verbose ("%s\n", const_ptr);
2783 // determine and append new_id
2786 snprintf (tmp_str, sizeof (tmp_str), ":1.%llu", new);
2787 const_ptr = tmp_str;
2792 if (!dbus_message_iter_append_basic (&args, DBUS_TYPE_STRING, &const_ptr))
2795 _dbus_verbose ("%s\n", const_ptr);
2798 if (!dbus_message_set_sender (message, DBUS_SERVICE_DBUS))
2800 dbus_message_set_serial (message, get_next_client_serial (transport));
2802 if (!add_message_to_received (message, transport->base.connection))
2808 dbus_message_unref (message);
2814 handle_item_timestamp (const struct kdbus_item *item)
2816 #if KDBUS_MSG_DECODE_DEBUG == 1
2817 _dbus_verbose (" +%s (%llu bytes) realtime=%lluns monotonic=%lluns\n",
2818 enum_MSG (item->type), item->size,
2819 (unsigned long long)item->timestamp.realtime_ns,
2820 (unsigned long long)item->timestamp.monotonic_ns);
2825 handle_unexpected_item (const struct kdbus_item *item)
2827 _dbus_assert_not_reached ("unexpected item from kdbus");
2831 handle_padding (const struct kdbus_msg *msg,
2832 const struct kdbus_item *end_of_items)
2834 #if KDBUS_MSG_DECODE_DEBUG == 1
2835 if ((char *)end_of_items - ((char *)msg + msg->size) >= 8)
2836 _dbus_verbose ("invalid padding at end of message\n");
2840 #ifdef LIBDBUSPOLICY
2842 load_dbus_header (DBusTransportKdbus *transport,
2844 const char *message_data,
2845 dbus_uint32_t message_len)
2847 DBusValidity validity = DBUS_VALID;
2849 dbus_uint32_t fields_array_len_unsigned;
2850 dbus_uint32_t body_len_unsigned;
2853 if (0 == message_len)
2856 _dbus_string_init_const_len (&message, message_data, message_len);
2857 _dbus_gvariant_raw_get_lengths (&message,
2858 &fields_array_len_unsigned,
2862 _dbus_string_init_const_len (&header->data,
2864 fields_array_len_unsigned + FIRST_GVARIANT_FIELD_OFFSET);
2866 header->padding = 0;
2867 header->byte_order = message_data[0];
2868 header->protocol_version = DBUS_PROTOCOL_VERSION_GVARIANT;
2869 for (i = 0; i <= DBUS_HEADER_FIELD_LAST; i++)
2870 header->fields[i].value_pos = _DBUS_HEADER_FIELD_VALUE_NONEXISTENT;
2872 return _dbus_header_load_gvariant (header, &validity);
2877 can_receive (DBusTransportKdbus *transport,
2878 const struct kdbus_msg *msg,
2879 const char *message_data,
2880 dbus_uint32_t message_len)
2882 dbus_bool_t result = TRUE;
2884 #ifdef LIBDBUSPOLICY
2885 if (transport->policy)
2888 dbus_bool_t got_header = FALSE;
2889 dbus_bool_t got_creds = FALSE;
2890 dbus_bool_t got_seclabel = FALSE;
2892 if (KDBUS_PAYLOAD_DBUS == msg->payload_type)
2894 const struct kdbus_item *item;
2895 uid_t sender_euid = -1;
2896 gid_t sender_egid = -1;
2897 const char *seclabel = NULL;
2902 if (!_dbus_string_init (&names))
2904 _dbus_verbose ("oom:_dbus_string_init");
2908 KDBUS_ITEM_FOREACH(item, msg, items)
2911 case KDBUS_ITEM_CREDS:
2912 sender_euid = (uid_t) item->creds.euid;
2913 sender_egid = (gid_t) item->creds.egid;
2914 got_creds = (sender_euid != (uid_t)-1) && (sender_egid != (gid_t)-1);
2916 case KDBUS_ITEM_SECLABEL:
2917 seclabel = item->str;
2918 got_seclabel = (seclabel != NULL);
2920 case KDBUS_ITEM_OWNED_NAME:
2923 _dbus_string_init_const (&name, item->name.name);
2924 if (_dbus_validate_bus_name (&name, 0, _dbus_string_get_length (&name)))
2926 if (_dbus_string_get_length (&names) != 0)
2928 if (!_dbus_string_append_byte (&names, ' '))
2930 _dbus_string_free (&names);
2935 if (!_dbus_string_copy (&name,
2938 _dbus_string_get_length (&names)))
2940 _dbus_string_free (&names);
2947 break; /* ignore all other items */
2950 if (NULL != message_data && message_len > 0)
2952 if (load_dbus_header (transport, &header, message_data, message_len))
2956 _dbus_header_get_message_type (&header) != DBUS_MESSAGE_TYPE_METHOD_CALL &&
2957 _dbus_header_get_message_type (&header) != DBUS_MESSAGE_TYPE_SIGNAL)
2961 else if (got_header && got_creds && got_seclabel)
2963 const char *destination = NULL;
2964 const char *path = NULL;
2965 const char *interface = NULL;
2966 const char *member = NULL;
2967 const char *error_name = NULL;
2968 dbus_uint64_t reply_cookie = 0;
2969 dbus_bool_t requested_reply = FALSE;
2972 _dbus_header_get_field_basic (&header,
2973 DBUS_HEADER_FIELD_DESTINATION,
2977 destination = transport->my_DBus_unique_name;
2979 _dbus_header_get_field_basic (&header,
2980 DBUS_HEADER_FIELD_PATH,
2984 _dbus_header_get_field_basic (&header,
2985 DBUS_HEADER_FIELD_INTERFACE,
2989 _dbus_header_get_field_basic (&header,
2990 DBUS_HEADER_FIELD_MEMBER,
2994 _dbus_header_get_field_basic (&header,
2995 DBUS_HEADER_FIELD_ERROR_NAME,
2999 _dbus_header_get_field_basic (&header,
3000 DBUS_HEADER_FIELD_REPLY_SERIAL,
3004 requested_reply = !(_dbus_header_get_flag (&header,
3005 DBUS_HEADER_FLAG_NO_REPLY_EXPECTED));
3007 ret = dbuspolicy1_check_in (transport->policy,
3009 _dbus_string_get_length (&names) > 0 ?
3010 _dbus_string_get_const_data (&names) :
3018 _dbus_header_get_message_type (&header),
3022 result = (1 == ret);
3025 _dbus_string_free (&names);
3034 kdbus_decode_dbus_message (const struct kdbus_msg *msg,
3036 DBusTransportKdbus *kdbus_transport,
3040 const struct kdbus_item *item;
3042 char *buffer = data;
3046 KDBUS_ITEM_FOREACH (item, msg, items)
3048 if (item->size < KDBUS_ITEM_HEADER_SIZE)
3050 _dbus_verbose (" +%s (%llu bytes) invalid data record\n", enum_MSG (item->type), item->size);
3057 case KDBUS_ITEM_PAYLOAD_OFF:
3058 memcpy (data, (char *)msg+item->vec.offset, item->vec.size);
3059 data += item->vec.size;
3060 ret_size += item->vec.size;
3062 #ifdef DBUS_ENABLE_VERBOSE_MODE
3065 debug_c_str ("Message part arrived:", (char *)msg+item->vec.offset, item->vec.size);
3069 _dbus_verbose (" +%s (%llu bytes) off=%llu size=%llu\n",
3070 enum_MSG (item->type), item->size,
3071 (unsigned long long)item->vec.offset,
3072 (unsigned long long)item->vec.size);
3075 case KDBUS_ITEM_PAYLOAD_MEMFD:
3080 size = item->memfd.size;
3081 _dbus_verbose ("memfd.size : %llu\n", (unsigned long long)size);
3083 buf = mmap (NULL, size, PROT_READ, MAP_PRIVATE, item->memfd.fd, 0);
3084 if (buf == MAP_FAILED)
3086 _dbus_verbose ("mmap () fd=%i failed:%m", item->memfd.fd);
3090 memcpy (data, buf, size);
3095 close (item->memfd.fd);
3097 _dbus_verbose (" +%s (%llu bytes) off=%llu size=%llu\n",
3098 enum_MSG (item->type), item->size,
3099 (unsigned long long)item->vec.offset,
3100 (unsigned long long)item->vec.size);
3104 case KDBUS_ITEM_FDS:
3108 *n_fds = (item->size - KDBUS_ITEM_HEADER_SIZE) / sizeof (int);
3109 memcpy (fds, item->fds, *n_fds * sizeof (int));
3110 for (i = 0; i < *n_fds; i++)
3111 _dbus_fd_set_close_on_exec (fds[i]);
3115 case KDBUS_ITEM_CREDS:
3116 #if KDBUS_MSG_DECODE_DEBUG == 1
3117 _dbus_verbose (" +%s (%llu bytes) uid=%lld, gid=%lld, pid=%lld, tid=%lld, starttime=%lld\n",
3118 enum_MSG (item->type), item->size,
3119 item->creds.uid, item->creds.gid,
3120 item->creds.pid, item->creds.tid,
3121 item->creds.starttime);
3125 case KDBUS_ITEM_PID_COMM:
3126 case KDBUS_ITEM_TID_COMM:
3127 case KDBUS_ITEM_EXE:
3128 case KDBUS_ITEM_CGROUP:
3129 case KDBUS_ITEM_SECLABEL:
3130 case KDBUS_ITEM_DST_NAME:
3131 #if KDBUS_MSG_DECODE_DEBUG == 1
3132 _dbus_verbose (" +%s (%llu bytes) '%s' (%zu)\n",
3133 enum_MSG (item->type), item->size, item->str, strlen (item->str));
3137 case KDBUS_ITEM_CMDLINE:
3138 case KDBUS_ITEM_NAME:
3139 #if KDBUS_MSG_DECODE_DEBUG == 1
3141 __u64 size = item->size - KDBUS_ITEM_HEADER_SIZE;
3142 const char *str = item->str;
3145 _dbus_verbose (" +%s (%llu bytes) ", enum_MSG (item->type), item->size);
3148 _dbus_verbose ("'%s' ", str);
3149 size -= strlen (str) + 1;
3150 str += strlen (str) + 1;
3154 _dbus_verbose ("(%d string%s)\n", count, (count == 1) ? "" : "s");
3159 case KDBUS_ITEM_AUDIT:
3160 #if KDBUS_MSG_DECODE_DEBUG == 1
3161 _dbus_verbose (" +%s (%llu bytes) loginuid=%llu sessionid=%llu\n",
3162 enum_MSG (item->type), item->size,
3163 (unsigned long long)item->data64[0],
3164 (unsigned long long)item->data64[1]);
3168 case KDBUS_ITEM_CAPS:
3169 #if KDBUS_MSG_DECODE_DEBUG == 1
3172 const uint32_t *cap;
3175 _dbus_verbose (" +%s (%llu bytes) len=%llu bytes)\n",
3176 enum_MSG (item->type), item->size,
3177 (unsigned long long)item->size - KDBUS_ITEM_HEADER_SIZE);
3180 n = (item->size - KDBUS_ITEM_HEADER_SIZE) / 4 / sizeof (uint32_t);
3182 _dbus_verbose (" CapInh=");
3183 for (i = 0; i < n; i++)
3184 _dbus_verbose ("%08x", cap[(0 * n) + (n - i - 1)]);
3186 _dbus_verbose (" CapPrm=");
3187 for (i = 0; i < n; i++)
3188 _dbus_verbose ("%08x", cap[(1 * n) + (n - i - 1)]);
3190 _dbus_verbose (" CapEff=");
3191 for (i = 0; i < n; i++)
3192 _dbus_verbose ("%08x", cap[(2 * n) + (n - i - 1)]);
3194 _dbus_verbose (" CapInh=");
3195 for (i = 0; i < n; i++)
3196 _dbus_verbose ("%08x", cap[(3 * n) + (n - i - 1)]);
3197 _dbus_verbose ("\n");
3202 case KDBUS_ITEM_TIMESTAMP:
3203 handle_item_timestamp (item);
3206 case KDBUS_ITEM_BLOOM_FILTER:
3211 handle_unexpected_item (item);
3216 handle_padding (msg, item);
3218 if (!can_receive (kdbus_transport, msg, buffer, ret_size))
3219 return 0; /* ignore message if not allowed */
3225 kdbus_decode_kernel_message (const struct kdbus_msg *msg,
3226 DBusTransportKdbus *kdbus_transport)
3228 const struct kdbus_item *item;
3231 KDBUS_ITEM_FOREACH (item, msg, items)
3233 if (item->size < KDBUS_ITEM_HEADER_SIZE)
3235 _dbus_verbose (" +%s (%llu bytes) invalid data record\n", enum_MSG (item->type), item->size);
3242 case KDBUS_ITEM_REPLY_TIMEOUT:
3243 case KDBUS_ITEM_REPLY_DEAD:
3244 _dbus_verbose (" +%s (%llu bytes) cookie=%llu\n",
3245 enum_MSG (item->type), item->size, msg->cookie_reply);
3248 case KDBUS_ITEM_NAME_ADD:
3249 case KDBUS_ITEM_NAME_REMOVE:
3250 case KDBUS_ITEM_NAME_CHANGE:
3254 _dbus_verbose (" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, old flags=0x%llx, new flags=0x%llx\n",
3255 enum_MSG (item->type), (unsigned long long) item->size,
3256 item->name_change.name, item->name_change.old_id.id,
3257 item->name_change.new_id.id, item->name_change.old_id.flags,
3258 item->name_change.new_id.flags);
3260 if (item->name_change.new_id.id == _kdbus_get_id (kdbus_transport->kdbus))
3261 ret_size = generate_NameSignal ("NameAcquired", item->name_change.name, kdbus_transport);
3262 else if (item->name_change.old_id.id == _kdbus_get_id (kdbus_transport->kdbus))
3263 ret_size = generate_NameSignal ("NameLost", item->name_change.name, kdbus_transport);
3268 if (item->name_change.new_id.flags & KDBUS_NAME_ACTIVATOR)
3269 local_ret = kdbus_handle_name_owner_changed (item->type,
3270 item->name_change.name,
3271 item->name_change.old_id.id, 0,
3273 else if (item->name_change.old_id.flags & KDBUS_NAME_ACTIVATOR)
3274 local_ret = kdbus_handle_name_owner_changed (item->type,
3275 item->name_change.name, 0,
3276 item->name_change.new_id.id,
3279 local_ret = kdbus_handle_name_owner_changed (item->type,
3280 item->name_change.name,
3281 item->name_change.old_id.id,
3282 item->name_change.new_id.id,
3284 if (local_ret == -1)
3287 ret_size += local_ret;
3291 case KDBUS_ITEM_ID_ADD:
3292 case KDBUS_ITEM_ID_REMOVE:
3293 _dbus_verbose (" +%s (%llu bytes) id=%llu flags=%llu\n",
3294 enum_MSG (item->type), (unsigned long long) item->size,
3295 (unsigned long long) item->id_change.id,
3296 (unsigned long long) item->id_change.flags);
3298 if (item->id_change.flags & KDBUS_HELLO_ACTIVATOR)
3299 ret_size = kdbus_handle_name_owner_changed (item->type, NULL, 0, 0,
3302 ret_size = kdbus_handle_name_owner_changed (item->type, NULL,
3303 item->type == KDBUS_ITEM_ID_ADD ? 0 : item->id_change.id,
3304 item->type == KDBUS_ITEM_ID_ADD ? item->id_change.id : 0,
3311 case KDBUS_ITEM_TIMESTAMP:
3312 handle_item_timestamp (item);
3316 handle_unexpected_item (item);
3321 handle_padding (msg, item);
3328 * Decodes kdbus message in order to extract DBus message and puts it into received data buffer
3329 * and file descriptor's buffer. Also captures kdbus error messages and kdbus kernel broadcasts
3330 * and converts all of them into appropriate DBus messages.
3332 * @param msg kdbus message
3333 * @param data place to copy DBus message to
3334 * @param kdbus_transport transport
3335 * @param fds place to store file descriptors received
3336 * @param n_fds place to store quantity of file descriptors received
3337 * @return number of DBus message's bytes received or -1 on error
3340 kdbus_decode_msg (const struct kdbus_msg *msg,
3342 DBusTransportKdbus *kdbus_transport,
3348 #if KDBUS_MSG_DECODE_DEBUG == 1
3349 _dbus_verbose ("MESSAGE: %s (%llu bytes) flags=0x%llx, %s → %s, cookie=%llu, timeout=%llu\n",
3350 enum_PAYLOAD (msg->payload_type),
3351 (unsigned long long) msg->size,
3352 (unsigned long long) msg->flags,
3353 msg_id (msg->src_id),
3354 msg_id (msg->dst_id),
3355 (unsigned long long) msg->cookie,
3356 (unsigned long long) msg->timeout_ns);
3359 switch (msg->payload_type)
3361 case KDBUS_PAYLOAD_DBUS:
3362 ret_size = kdbus_decode_dbus_message (msg, data, kdbus_transport, fds, n_fds);
3364 case KDBUS_PAYLOAD_KERNEL:
3365 ret_size = kdbus_decode_kernel_message (msg, kdbus_transport);
3368 _dbus_assert_not_reached ("unexpected payload type from kdbus");
3376 * Reads message from kdbus and puts it into DBus buffers
3378 * @param kdbus_transport transport
3379 * @param buffer place to copy received message to
3380 * @param fds place to store file descriptors received with the message
3381 * @param n_fds place to store quantity of file descriptors received
3382 * @return size of received message on success, -1 on error
3385 kdbus_read_message (DBusTransportKdbus *kdbus_transport,
3390 int ret_size, buf_size;
3391 struct kdbus_msg *msg;
3394 dbus_uint64_t flags = 0;
3397 start = _dbus_string_get_length (buffer);
3399 if (kdbus_transport->activator != NULL)
3400 flags |= KDBUS_RECV_PEEK;
3402 ret = _kdbus_recv (kdbus_transport->kdbus, flags, 0, &msg);
3406 _dbus_verbose ("kdbus error receiving message: %d (%s)\n", ret, _dbus_strerror (ret));
3410 buf_size = kdbus_message_size (msg, n_fds);
3413 _dbus_verbose ("kdbus error - too short message: %d (%m)\n", errno);
3417 /* What is the maximum size of the locally generated message?
3418 I just assume 2048 bytes */
3419 buf_size = MAX (buf_size, 2048);
3421 if (!_dbus_string_lengthen (buffer, buf_size))
3426 data = _dbus_string_get_data_len (buffer, start, buf_size);
3428 ret_size = kdbus_decode_msg (msg, data, kdbus_transport, fds, n_fds);
3430 if (ret_size == -1) /* error */
3431 _dbus_string_set_length (buffer, start);
3432 else if (ret_size >= 0 && buf_size != ret_size) /* case of locally generated message */
3433 _dbus_string_set_length (buffer, start + ret_size);
3436 _dbus_message_loader_set_unique_sender_id (kdbus_transport->base.loader, msg->src_id);
3438 if (kdbus_transport->activator != NULL)
3441 ret = _kdbus_free_mem (kdbus_transport->kdbus, msg);
3444 _dbus_verbose ("kdbus error freeing message: %d (%s)\n", ret, _dbus_strerror (ret));
3451 #ifdef ENABLE_KDBUS_SYNC_CALLS
3452 static DBusMessage *
3453 kdbus_send_sync_call (DBusTransportKdbus *transport,
3454 DBusMessage *message)
3456 DBusMessage *reply = NULL;
3458 const char *destination;
3460 dbus_message_lock (message);
3462 destination = dbus_message_get_destination (message);
3467 ret = capture_org_freedesktop_DBus ((DBusTransportKdbus*)transport, destination, message, &reply);
3474 kdbus_write_msg_internal (transport, message, destination, &reply, TRUE);
3482 dbus_error_init (&error);
3484 dbus_set_error (&error, DBUS_ERROR_FAILED,
3485 "Something went wrong");
3487 reply = reply_with_error ((char*)error.name,
3492 dbus_error_free (&error);
3496 _dbus_assert (reply != NULL);
3497 dbus_message_lock (reply);
3504 * Copy-paste from socket transport. Only renames done.
3507 free_watches (DBusTransportKdbus *kdbus_transport)
3509 DBusConnection *connection = kdbus_transport->base.connection;
3510 _dbus_verbose ("start\n");
3512 if (kdbus_transport->read_watch)
3515 _dbus_connection_remove_watch_unlocked (connection,
3516 kdbus_transport->read_watch);
3517 _dbus_watch_invalidate (kdbus_transport->read_watch);
3518 _dbus_watch_unref (kdbus_transport->read_watch);
3519 kdbus_transport->read_watch = NULL;
3522 if (kdbus_transport->write_watch)
3525 _dbus_connection_remove_watch_unlocked (connection,
3526 kdbus_transport->write_watch);
3527 _dbus_watch_invalidate (kdbus_transport->write_watch);
3528 _dbus_watch_unref (kdbus_transport->write_watch);
3529 kdbus_transport->write_watch = NULL;
3532 _dbus_verbose ("end\n");
3536 free_policies (DBusTransportKdbus *transport)
3538 #ifdef LIBDBUSPOLICY
3539 if (NULL != transport->policy)
3540 dbuspolicy1_free (transport->policy);
3545 * Copy-paste from socket transport. Only done needed renames and removed
3546 * lines related to encoded messages.
3549 transport_finalize (DBusTransport *transport)
3551 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus *)transport;
3552 _dbus_verbose ("\n");
3554 free_watches (kdbus_transport);
3556 _dbus_transport_finalize_base (transport);
3558 _dbus_assert (kdbus_transport->read_watch == NULL);
3559 _dbus_assert (kdbus_transport->write_watch == NULL);
3561 free_matchmaker (kdbus_transport->matchmaker);
3563 dbus_free (kdbus_transport->activator);
3565 free_policies ( kdbus_transport );
3567 _kdbus_free (kdbus_transport->kdbus);
3568 free (kdbus_transport->my_DBus_unique_name);
3570 dbus_free (transport);
3574 * Copy-paste from socket transport. Removed code related to authentication,
3575 * socket_transport replaced by kdbus_transport.
3578 check_write_watch (DBusTransportKdbus *kdbus_transport)
3581 DBusTransport *transport = &kdbus_transport->base;
3583 if (transport->connection == NULL)
3586 if (transport->disconnected)
3588 _dbus_assert (kdbus_transport->write_watch == NULL);
3592 _dbus_transport_ref (transport);
3594 needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection);
3596 _dbus_verbose ("check_write_watch (): needed = %d on connection %p watch %p fd = %d outgoing messages exist %d\n",
3597 needed, transport->connection, kdbus_transport->write_watch,
3598 _kdbus_get_fd (kdbus_transport->kdbus),
3599 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
3601 _dbus_connection_toggle_watch_unlocked (transport->connection,
3602 kdbus_transport->write_watch,
3605 _dbus_transport_unref (transport);
3609 * Copy-paste from socket transport. Removed code related to authentication,
3610 * socket_transport replaced by kdbus_transport.
3613 check_read_watch (DBusTransportKdbus *kdbus_transport)
3615 dbus_bool_t need_read_watch;
3616 DBusTransport *transport = &kdbus_transport->base;
3618 _dbus_verbose ("fd = %d\n",_kdbus_get_fd (kdbus_transport->kdbus));
3620 if (transport->connection == NULL)
3623 if (transport->disconnected)
3625 _dbus_assert (kdbus_transport->read_watch == NULL);
3629 _dbus_transport_ref (transport);
3632 (_dbus_counter_get_size_value (transport->live_messages) < transport->max_live_messages_size) &&
3633 (_dbus_counter_get_unix_fd_value (transport->live_messages) < transport->max_live_messages_unix_fds);
3635 _dbus_verbose (" setting read watch enabled = %d\n", need_read_watch);
3637 _dbus_connection_toggle_watch_unlocked (transport->connection,
3638 kdbus_transport->read_watch,
3641 _dbus_transport_unref (transport);
3645 * Copy-paste from socket transport.
3648 do_io_error (DBusTransport *transport)
3650 _dbus_transport_ref (transport);
3651 _dbus_transport_disconnect (transport);
3652 _dbus_transport_unref (transport);
3656 * Based on do_writing from socket transport.
3657 * Removed authentication code and code related to encoded messages
3658 * and adapted to kdbus transport.
3659 * In socket transport returns false on out-of-memory. Here this won't happen,
3660 * so it always returns TRUE.
3663 do_writing (DBusTransport *transport)
3665 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
3667 dbus_bool_t oom = FALSE;
3669 if (transport->disconnected)
3671 _dbus_verbose ("Not connected, not writing anything\n");
3675 _dbus_verbose ("do_writing (), have_messages = %d, fd = %d\n",
3676 _dbus_connection_has_messages_to_send_unlocked (transport->connection),
3677 _kdbus_get_fd (kdbus_transport->kdbus));
3679 while (!transport->disconnected && _dbus_connection_has_messages_to_send_unlocked (transport->connection))
3682 DBusMessage *message;
3684 const DBusString *header;
3685 const DBusString *body;
3686 const char* pDestination;
3688 if (total > kdbus_transport->max_bytes_written_per_iteration)
3690 _dbus_verbose ("%d bytes exceeds %d bytes written per iteration, returning\n",
3691 total, kdbus_transport->max_bytes_written_per_iteration);
3696 message = _dbus_connection_get_message_to_send (transport->connection);
3697 _dbus_assert (message != NULL);
3698 pDestination = dbus_message_get_destination (message);
3704 ret = capture_org_freedesktop_DBus ((DBusTransportKdbus*)transport, pDestination, message, &reply);
3705 if (ret < 0) //error
3710 else if (ret == 0) //message captured and handled correctly
3712 /* puts locally generated reply into received messages queue */
3713 if (!add_message_to_received (reply, kdbus_transport->base.connection))
3719 _dbus_message_get_network_data (message, &header, &body);
3720 bytes_written = _dbus_string_get_length (header) + _dbus_string_get_length (body);
3723 //else send as regular message
3726 bytes_written = kdbus_write_msg (kdbus_transport, message, pDestination);
3729 if (bytes_written < 0)
3731 if (errno == ENOMEM)
3737 /* EINTR already handled for us */
3739 /* For some discussion of why we also ignore EPIPE here, see
3740 * http://lists.freedesktop.org/archives/dbus/2008-March/009526.html
3743 if (_dbus_get_is_errno_eagain_or_ewouldblock (errno) || _dbus_get_is_errno_epipe (errno))
3747 _dbus_verbose ("Error writing to remote app: %s\n", _dbus_strerror_from_errno ());
3748 do_io_error (transport);
3754 #if defined (DBUS_ENABLE_VERBOSE_MODE) || !defined (DBUS_DISABLE_ASSERT)
3755 int total_bytes_to_write;
3757 _dbus_message_get_network_data (message, &header, &body);
3758 total_bytes_to_write = _dbus_string_get_length (header)
3759 + _dbus_string_get_length (body);
3760 _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
3761 total_bytes_to_write);
3763 _dbus_assert (bytes_written == total_bytes_to_write);
3765 total += bytes_written;
3767 _dbus_connection_message_sent_unlocked (transport->connection,
3780 * Based on do_reading from socket transport.
3781 * Removed authentication code and code related to encoded messages
3782 * and adapted to kdbus transport.
3783 * returns false on out-of-memory
3786 do_reading (DBusTransport *transport)
3788 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
3791 dbus_bool_t oom = FALSE;
3795 _dbus_verbose ("fd = %d\n", _kdbus_get_fd (kdbus_transport->kdbus));
3799 /* See if we've exceeded max messages and need to disable reading */
3800 if (kdbus_transport->activator == NULL)
3801 check_read_watch (kdbus_transport);
3803 if (total > kdbus_transport->max_bytes_read_per_iteration)
3805 _dbus_verbose ("%d bytes exceeds %d bytes read per iteration, returning\n",
3806 total, kdbus_transport->max_bytes_read_per_iteration);
3810 _dbus_assert (kdbus_transport->read_watch != NULL ||
3811 transport->disconnected);
3813 if (transport->disconnected)
3816 if (!dbus_watch_get_enabled (kdbus_transport->read_watch))
3819 if (!_dbus_message_loader_get_unix_fds (transport->loader, &fds, &n_fds))
3821 _dbus_verbose ("Out of memory reading file descriptors\n");
3825 _dbus_message_loader_get_buffer (transport->loader, &buffer, NULL, NULL);
3827 bytes_read = kdbus_read_message (kdbus_transport, buffer, fds, &n_fds);
3829 if (bytes_read >= 0 && n_fds > 0)
3830 _dbus_verbose ("Read %i unix fds\n", n_fds);
3832 _dbus_message_loader_return_buffer (transport->loader,
3834 _dbus_message_loader_return_unix_fds (transport->loader, fds, bytes_read < 0 ? 0 : n_fds);
3838 /* EINTR already handled for us */
3840 if (_dbus_get_is_errno_enomem (errno))
3842 _dbus_verbose ("Out of memory in read()/do_reading()\n");
3846 else if (_dbus_get_is_errno_eagain_or_ewouldblock (errno))
3850 _dbus_verbose ("Error reading from remote app: %s\n",
3851 _dbus_strerror_from_errno ());
3852 do_io_error (transport);
3856 else if (bytes_read > 0)
3858 _dbus_verbose (" read %d bytes\n", bytes_read);
3860 total += bytes_read;
3862 if (!_dbus_transport_queue_messages (transport))
3865 _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
3869 /* Try reading more data until we get EAGAIN and return, or
3870 * exceed max bytes per iteration. If in blocking mode of
3871 * course we'll block instead of returning.
3875 /* 0 == bytes_read is for kernel and ignored messages */
3884 * Copy-paste from socket transport, with socket replaced by kdbus.
3887 unix_error_with_read_to_come (DBusTransport *itransport,
3891 DBusTransportKdbus *transport = (DBusTransportKdbus *) itransport;
3893 if (!((flags & DBUS_WATCH_HANGUP) || (flags & DBUS_WATCH_ERROR)))
3896 /* If we have a read watch enabled ...
3897 we -might have data incoming ... => handle the HANGUP there */
3898 if (watch != transport->read_watch && _dbus_watch_get_enabled (transport->read_watch))
3905 * Copy-paste from socket transport. Removed authentication related code
3906 * and renamed socket_transport to kdbus_transport.
3909 kdbus_handle_watch (DBusTransport *transport,
3913 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
3915 _dbus_assert (watch == kdbus_transport->read_watch ||
3916 watch == kdbus_transport->write_watch);
3917 _dbus_assert (watch != NULL);
3919 /* If we hit an error here on a write watch, don't disconnect the transport yet because data can
3920 * still be in the buffer and do_reading may need several iteration to read
3921 * it all (because of its max_bytes_read_per_iteration limit).
3923 if (!(flags & DBUS_WATCH_READABLE) && unix_error_with_read_to_come (transport, watch, flags))
3925 _dbus_verbose ("Hang up or error on watch\n");
3926 _dbus_transport_disconnect (transport);
3930 if (watch == kdbus_transport->read_watch &&
3931 (flags & DBUS_WATCH_READABLE))
3933 _dbus_verbose ("handling read watch %p flags = %x\n",
3936 if (!do_reading (transport))
3938 _dbus_verbose ("no memory to read\n");
3942 else if (watch == kdbus_transport->write_watch &&
3943 (flags & DBUS_WATCH_WRITABLE))
3945 _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n",
3946 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
3948 if (!do_writing (transport))
3950 _dbus_verbose ("no memory to write\n");
3954 /* See if we still need the write watch */
3955 check_write_watch (kdbus_transport);
3962 * Copy-paste from socket transport, but socket_transport renamed to kdbus_transport
3963 * and _dbus_close_socket replaced with close ().
3966 kdbus_disconnect (DBusTransport *transport)
3968 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
3970 _dbus_verbose ("\n");
3972 free_watches (kdbus_transport);
3974 _kdbus_close (kdbus_transport->kdbus);
3978 * Copy-paste from socket transport. Renamed socket_transport to
3979 * kdbus_transport and added setting authenticated to TRUE, because
3980 * we do not perform authentication in kdbus, so we have mark is as already done
3981 * to make everything work.
3984 kdbus_connection_set (DBusTransport *transport)
3986 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
3988 _dbus_watch_set_handler (kdbus_transport->write_watch,
3989 _dbus_connection_handle_watch,
3990 transport->connection, NULL);
3992 _dbus_watch_set_handler (kdbus_transport->read_watch,
3993 _dbus_connection_handle_watch,
3994 transport->connection, NULL);
3996 if (!_dbus_connection_add_watch_unlocked (transport->connection,
3997 kdbus_transport->write_watch))
4000 if (!_dbus_connection_add_watch_unlocked (transport->connection,
4001 kdbus_transport->read_watch))
4003 _dbus_connection_remove_watch_unlocked (transport->connection,
4004 kdbus_transport->write_watch);
4008 check_read_watch (kdbus_transport);
4009 check_write_watch (kdbus_transport);
4015 * Copy-paste from socket_transport.
4016 * Socket_transport renamed to kdbus_transport
4018 * Original dbus copy-pasted @todo comment below.
4019 * @todo We need to have a way to wake up the select sleep if
4020 * a new iteration request comes in with a flag (read/write) that
4021 * we're not currently serving. Otherwise a call that just reads
4022 * could block a write call forever (if there are no incoming
4026 kdbus_do_iteration (DBusTransport *transport,
4028 int timeout_milliseconds)
4030 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
4035 _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p fd = %d\n",
4036 flags & DBUS_ITERATION_DO_READING ? "read" : "",
4037 flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
4038 timeout_milliseconds,
4039 kdbus_transport->read_watch,
4040 kdbus_transport->write_watch,
4041 _kdbus_get_fd (kdbus_transport->kdbus));
4043 poll_fd.fd = _kdbus_get_fd (kdbus_transport->kdbus);
4048 * This fix is for reply_with_error function.
4049 * When timeout is set to -1 in client application,
4050 * error messages are inserted directly to incoming queue and
4051 * application hangs on dbus_poll.
4053 * This causes a busy loop in _dbus_connection_block_pending_call()
4054 * There is no case of waiting for the locally-generated error reply
4056 if (_dbus_connection_get_n_incoming (transport->connection) > 0)
4058 timeout_milliseconds = 0;
4062 /* This is kind of a hack; if we have stuff to write, then try
4063 * to avoid the poll. This is probably about a 5% speedup on an
4064 * echo client/server.
4066 * If both reading and writing were requested, we want to avoid this
4067 * since it could have funky effects:
4068 * - both ends spinning waiting for the other one to read
4069 * data so they can finish writing
4070 * - prioritizing all writing ahead of reading
4072 if ((flags & DBUS_ITERATION_DO_WRITING) &&
4073 !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) &&
4074 !transport->disconnected &&
4075 _dbus_connection_has_messages_to_send_unlocked (transport->connection))
4077 do_writing (transport);
4079 if (transport->disconnected ||
4080 !_dbus_connection_has_messages_to_send_unlocked (transport->connection))
4084 /* If we get here, we decided to do the poll() after all */
4085 _dbus_assert (kdbus_transport->read_watch);
4086 if (flags & DBUS_ITERATION_DO_READING)
4087 poll_fd.events |= _DBUS_POLLIN;
4089 _dbus_assert (kdbus_transport->write_watch);
4090 if (flags & DBUS_ITERATION_DO_WRITING)
4091 poll_fd.events |= _DBUS_POLLOUT;
4095 if ( (flags & DBUS_ITERATION_BLOCK) && !(flags & DBUS_ITERATION_DO_WRITING))
4096 poll_timeout = timeout_milliseconds;
4100 /* For blocking selects we drop the connection lock here
4101 * to avoid blocking out connection access during a potentially
4102 * indefinite blocking call. The io path is still protected
4103 * by the io_path_cond condvar, so we won't reenter this.
4105 if (flags & DBUS_ITERATION_BLOCK)
4107 _dbus_verbose ("unlock pre poll\n");
4108 _dbus_connection_unlock (transport->connection);
4112 poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
4114 if (poll_res < 0 && _dbus_get_is_errno_eintr (errno))
4117 if (flags & DBUS_ITERATION_BLOCK)
4119 _dbus_verbose ("lock post poll\n");
4120 _dbus_connection_lock (transport->connection);
4126 poll_fd.revents = 0; /* some concern that posix does not guarantee this;
4127 * valgrind flags it as an error. though it probably
4128 * is guaranteed on linux at least.
4131 if (poll_fd.revents & _DBUS_POLLERR)
4132 do_io_error (transport);
4135 dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
4137 _dbus_verbose ("in iteration, need_read=%d\n",
4140 if (need_read && (flags & DBUS_ITERATION_DO_READING))
4141 do_reading (transport);
4142 /* We always be able to write to kdbus */
4143 if (flags & DBUS_ITERATION_DO_WRITING)
4144 do_writing (transport);
4148 _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
4152 /* We need to install the write watch only if we did not
4153 * successfully write everything. Note we need to be careful that we
4154 * don't call check_write_watch *before* do_writing, since it's
4155 * inefficient to add the write watch, and we can avoid it most of
4156 * the time since we can write immediately.
4158 * However, we MUST always call check_write_watch(); DBusConnection code
4159 * relies on the fact that running an iteration will notice that
4160 * messages are pending.
4162 check_write_watch (kdbus_transport);
4164 _dbus_verbose (" ... leaving do_iteration()\n");
4168 * Copy-paste from socket transport.
4171 kdbus_live_messages_changed (DBusTransport *transport)
4173 /* See if we should look for incoming messages again */
4174 check_read_watch ((DBusTransportKdbus *)transport);
4178 * Gets file descriptor of the kdbus bus.
4179 * @param transport transport
4180 * @param fd_p place to write fd to
4181 * @returns always TRUE
4184 kdbus_get_kdbus_fd (DBusTransport *transport,
4187 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
4189 fd_p->fd = _kdbus_get_fd (kdbus_transport->kdbus);
4194 static const DBusTransportVTable kdbus_vtable = {
4198 kdbus_connection_set,
4200 kdbus_live_messages_changed,
4204 typedef unsigned long (*ConnectionInfoExtractField) (struct nameInfo *);
4206 static inline unsigned long
4207 _extract_name_info_userId (struct nameInfo *nameInfo)
4209 return nameInfo->userId;
4212 static inline unsigned long
4213 _extract_name_info_processId (struct nameInfo *nameInfo)
4215 return nameInfo->processId;
4219 _dbus_transport_kdbus_get_connection_info_ulong_field (DBusTransportKdbus *transport,
4220 ConnectionInfoExtractField function,
4223 struct nameInfo conn_info;
4226 ret = _kdbus_connection_info_by_id (transport->kdbus,
4227 _kdbus_get_id (transport->kdbus),
4233 *val = function (&conn_info);
4238 _dbus_transport_kdbus_get_unix_user (DBusTransport *transport,
4241 return _dbus_transport_kdbus_get_connection_info_ulong_field ((DBusTransportKdbus *)transport,
4242 _extract_name_info_userId,
4247 _dbus_transport_kdbus_get_unix_process_id (DBusTransport *transport,
4250 return _dbus_transport_kdbus_get_connection_info_ulong_field ((DBusTransportKdbus *)transport,
4251 _extract_name_info_processId,
4256 * Copy-paste from dbus_transport_socket with needed changes.
4258 * Creates a new transport for the given kdbus file descriptor and address.
4259 * The file descriptor must be nonblocking.
4261 * @param fd the file descriptor.
4262 * @param address the transport's address
4263 * @returns the new transport, or #NULL if no memory.
4265 static DBusTransportKdbus *
4266 new_kdbus_transport (kdbus_t *kdbus,
4267 const DBusString *address,
4268 const char *activator)
4270 DBusTransportKdbus *kdbus_transport;
4272 kdbus_transport = dbus_new0 (DBusTransportKdbus, 1);
4273 if (kdbus_transport == NULL)
4276 kdbus_transport->kdbus = kdbus;
4278 kdbus_transport->write_watch = _dbus_watch_new (_kdbus_get_fd (kdbus),
4279 DBUS_WATCH_WRITABLE,
4282 if (kdbus_transport->write_watch == NULL)
4285 kdbus_transport->read_watch = _dbus_watch_new (_kdbus_get_fd (kdbus),
4286 DBUS_WATCH_READABLE,
4289 if (kdbus_transport->read_watch == NULL)
4292 if (!_dbus_transport_init_base_authenticated (&kdbus_transport->base,
4297 _dbus_transport_set_get_unix_user_function (&kdbus_transport->base,
4298 _dbus_transport_kdbus_get_unix_user);
4299 _dbus_transport_set_get_unix_process_id_function (&kdbus_transport->base,
4300 _dbus_transport_kdbus_get_unix_process_id);
4301 #ifdef ENABLE_KDBUS_SYNC_CALLS
4302 _dbus_transport_set_send_sync_call_function (&kdbus_transport->base,
4303 (DBusTransportSendSyncCallFunction) kdbus_send_sync_call);
4305 _dbus_transport_set_assure_protocol_function (&kdbus_transport->base,
4306 _dbus_message_assure_gvariant,
4307 DBUS_PROTOCOL_VERSION_GVARIANT);
4309 /* These values should probably be tunable or something. */
4310 kdbus_transport->max_bytes_read_per_iteration = MAX_BYTES_PER_ITERATION;
4311 kdbus_transport->max_bytes_written_per_iteration = MAX_BYTES_PER_ITERATION;
4313 if (activator!=NULL)
4315 kdbus_transport->activator = _dbus_strdup (activator);
4316 if (kdbus_transport->activator == NULL)
4320 kdbus_transport->matchmaker = matchmaker_new ();
4322 kdbus_transport->client_serial = 1;
4324 return kdbus_transport;
4327 _dbus_watch_invalidate (kdbus_transport->read_watch);
4328 _dbus_watch_unref (kdbus_transport->read_watch);
4330 _dbus_watch_invalidate (kdbus_transport->write_watch);
4331 _dbus_watch_unref (kdbus_transport->write_watch);
4333 dbus_free (kdbus_transport);
4338 * Connects to kdbus, creates and sets-up transport.
4340 * @param path the path to the bus.
4341 * @param error address where an error can be returned.
4342 * @returns a new transport, or #NULL on failure.
4344 static DBusTransport*
4345 _dbus_transport_new_for_kdbus (const char *path,
4346 const char *activator,
4350 DBusTransportKdbus *transport;
4354 #ifdef DBUS_ENABLE_VERBOSE_MODE
4355 const char *dbgenv = _dbus_getenv ("G_DBUS_DEBUG");
4358 if (!strcmp (dbgenv, "message"))
4360 else if (!strcmp (dbgenv, "all"))
4365 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
4367 if (!_dbus_string_init (&address))
4369 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
4373 if ((!_dbus_string_append (&address, DBUS_ADDRESS_KDBUS "path=")) || (!_dbus_string_append (&address, path)))
4375 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
4379 kdbus = _kdbus_new (path);
4382 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
4386 ret = _kdbus_open (kdbus);
4389 dbus_set_error (error,
4390 _dbus_error_from_errno (-ret),
4391 "Failed to open file descriptor: %s: %s",
4393 _dbus_strerror (-ret));
4394 goto failed_0_with_kdbus;
4397 _dbus_verbose ("Successfully connected to kdbus bus %s\n", path);
4399 transport = new_kdbus_transport (kdbus, &address, activator);
4400 if (transport == NULL)
4402 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
4406 _dbus_string_free (&address);
4408 return (DBusTransport*)transport;
4411 _kdbus_close (kdbus);
4412 failed_0_with_kdbus:
4413 _kdbus_free (kdbus);
4415 _dbus_string_free (&address);
4421 * Opens kdbus transport if method from address entry is kdbus
4423 * @param entry the address entry to open
4424 * @param transport_p return location for the opened transport
4425 * @param error place to store error
4426 * @returns result of the attempt as a DBusTransportOpenResult enum
4428 DBusTransportOpenResult
4429 _dbus_transport_open_kdbus (DBusAddressEntry *entry,
4430 DBusTransport **transport_p,
4435 method = dbus_address_entry_get_method (entry);
4436 _dbus_assert (method != NULL);
4438 if (strcmp (method, "kernel") == 0)
4440 const char *path = dbus_address_entry_get_value (entry, "path");
4441 const char *activator = dbus_address_entry_get_value (entry, "activator");
4445 _dbus_set_bad_address (error, "kdbus", "path", NULL);
4446 return DBUS_TRANSPORT_OPEN_BAD_ADDRESS;
4449 *transport_p = _dbus_transport_new_for_kdbus (path, activator, error);
4451 if (*transport_p == NULL)
4453 _DBUS_ASSERT_ERROR_IS_SET (error);
4454 return DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT;
4458 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
4459 return DBUS_TRANSPORT_OPEN_OK;
4464 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
4465 return DBUS_TRANSPORT_OPEN_NOT_HANDLED;