2 * dbus-transport-kdbus.c
4 * Transport layer using kdbus
6 * Created on: Jun 20, 2013
12 #include "dbus-transport.h"
13 #include "dbus-transport-kdbus.h"
14 #include <dbus/dbus-transport-protected.h>
15 #include "dbus-connection-internal.h"
17 #include "dbus-watch.h"
18 #include "dbus-errors.h"
20 #include <linux/types.h>
24 #include <sys/ioctl.h>
32 #include <openssl/md5.h>
34 #define KDBUS_ALIGN8(l) (((l) + 7) & ~7)
35 #define KDBUS_ITEM_SIZE(s) KDBUS_ALIGN8((s) + KDBUS_PART_HEADER_SIZE)
37 #define KDBUS_PART_NEXT(part) \
38 (typeof(part))(((uint8_t *)part) + KDBUS_ALIGN8((part)->size))
39 #define KDBUS_PART_FOREACH(part, head, first) \
40 for (part = (head)->first; \
41 (uint8_t *)(part) < (uint8_t *)(head) + (head)->size; \
42 part = KDBUS_PART_NEXT(part))
43 #define RECEIVE_POOL_SIZE (10 * 1024LU * 1024LU)
44 #define MEMFD_SIZE_THRESHOLD (2 * 1024 * 1024LU) // over this memfd is used
46 #define KDBUS_MSG_DECODE_DEBUG 0
48 #define ITER_APPEND_STR(string) \
49 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &string)) \
55 #define MSG_ITEM_BUILD_VEC(data, datasize) \
56 item->type = KDBUS_MSG_PAYLOAD_VEC; \
57 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec); \
58 item->vec.address = (unsigned long) data; \
59 item->vec.size = datasize;
62 * Opaque object representing a socket file descriptor transport.
64 typedef struct DBusTransportSocket DBusTransportSocket;
67 * Implementation details of DBusTransportSocket. All members are private.
69 struct DBusTransportSocket
71 DBusTransport base; /**< Parent instance */
72 int fd; /**< File descriptor. */
73 DBusWatch *read_watch; /**< Watch for readability. */
74 DBusWatch *write_watch; /**< Watch for writability. */
76 int max_bytes_read_per_iteration; /**< In kdbus only to control overall message size*/
77 int max_bytes_written_per_iteration; /**< In kdbus only to control overall message size*/
79 int message_bytes_written; /**< Number of bytes of current
80 * outgoing message that have
83 DBusString encoded_outgoing; /**< Encoded version of current
86 DBusString encoded_incoming; /**< Encoded version of current
89 void* kdbus_mmap_ptr; /**< Mapped memory where Kdbus (kernel) writes
90 * messages incoming to us.
92 int memfd; /**< File descriptor to special
93 * memory pool for bulk data
94 * transfer. Retrieved from
95 * Kdbus kernel module.
97 __u64 bloom_size; /**< bloom filter field size */
98 char* sender; /**< uniqe name of the sender */
102 socket_get_socket_fd (DBusTransport *transport,
105 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
107 *fd_p = socket_transport->fd;
113 * Adds locally generated message to received messages queue
116 static dbus_bool_t add_message_to_received(DBusMessage *message, DBusConnection* connection)
118 DBusList *message_link;
120 message_link = _dbus_list_alloc_link (message);
121 if (message_link == NULL)
123 dbus_message_unref (message);
127 _dbus_connection_queue_synthesized_message_link(connection, message_link);
132 static int reply_with_error(char* error_type, const char* template, const char* object, DBusMessage *message, DBusConnection* connection)
134 DBusMessage *errMessage;
135 char* error_msg = "";
139 error_msg = alloca(strlen(template) + strlen(object));
140 sprintf(error_msg, template, object);
143 error_msg = (char*)object;
145 errMessage = generate_local_error_message(dbus_message_get_serial(message), error_type, error_msg);
146 if(errMessage == NULL)
148 if (add_message_to_received(errMessage, connection))
154 static int reply_1_data(DBusMessage *message, int data_type, void* pData, DBusConnection* connection)
156 DBusMessageIter args;
159 reply = dbus_message_new_method_return(message);
162 dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
163 dbus_message_iter_init_append(reply, &args);
164 if (!dbus_message_iter_append_basic(&args, data_type, pData))
166 dbus_message_unref(reply);
169 if(add_message_to_received(reply, connection))
175 static int reply_ack(DBusMessage *message, DBusConnection* connection)
179 reply = dbus_message_new_method_return(message);
182 if(add_message_to_received(reply, connection))
188 * Retrieves file descriptor to memory pool from kdbus module.
189 * It is then used for bulk data sending.
190 * Triggered when message payload is over MEMFD_SIZE_THRESHOLD
193 static int kdbus_init_memfd(DBusTransportSocket* socket_transport)
197 if (ioctl(socket_transport->fd, KDBUS_CMD_MEMFD_NEW, &memfd) < 0) {
198 _dbus_verbose("KDBUS_CMD_MEMFD_NEW failed: \n");
202 socket_transport->memfd = memfd;
203 _dbus_verbose("kdbus_init_memfd: %d!!\n", socket_transport->memfd);
208 * Initiates Kdbus message structure.
209 * Calculates it's size, allocates memory and fills some fields.
210 * @param name Well-known name or NULL
211 * @param dst_id Numeric id of recipient
212 * @param body_size size of message body if present
213 * @param use_memfd flag to build memfd message
214 * @param fds_count number of file descriptors used
215 * @param transport transport
216 * @return initialized kdbus message
218 static struct kdbus_msg* kdbus_init_msg(const char* name, __u64 dst_id, uint64_t body_size, dbus_bool_t use_memfd, int fds_count, DBusTransportSocket *transport)
220 struct kdbus_msg* msg;
223 msg_size = sizeof(struct kdbus_msg);
225 if(use_memfd == TRUE) // bulk data - memfd - encoded and plain
226 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_memfd));
228 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
230 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
234 msg_size += KDBUS_ITEM_SIZE(sizeof(int)*fds_count);
237 msg_size += KDBUS_ITEM_SIZE(strlen(name) + 1);
238 else if (dst_id == KDBUS_DST_ID_BROADCAST)
239 msg_size += KDBUS_PART_HEADER_SIZE + transport->bloom_size;
241 msg = malloc(msg_size);
244 _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
248 memset(msg, 0, msg_size);
249 msg->size = msg_size;
250 msg->payload_type = KDBUS_PAYLOAD_DBUS1;
251 msg->dst_id = name ? 0 : dst_id;
252 msg->src_id = strtoull(dbus_bus_get_unique_name(transport->base.connection), NULL , 10);
258 * Builds and sends kdbus message using Dbus message.
259 * Decide whether used payload vector or memfd memory pool.
260 * Handles broadcasts and unicast messages, and passing of Unix fds.
261 * Does error handling.
262 * TODO refactor to be more compact
264 * @param transport transport
265 * @param message DBus message to be sent
266 * @param encoded flag if the message is encoded
267 * @return size of data sent
269 static int kdbus_write_msg(DBusTransportSocket *transport, DBusMessage *message, dbus_bool_t encoded)
271 struct kdbus_msg *msg;
272 struct kdbus_item *item;
274 uint64_t dst_id = KDBUS_DST_ID_BROADCAST;
275 const DBusString *header;
276 const DBusString *body;
277 uint64_t ret_size = 0;
278 uint64_t body_size = 0;
279 uint64_t header_size = 0;
280 dbus_bool_t use_memfd;
283 dbus_bool_t autostart;
285 // determine name and destination id
286 if((name = dbus_message_get_destination(message)))
288 dst_id = KDBUS_DST_ID_WELL_KNOWN_NAME;
289 if((name[0] == ':') && (name[1] == '1') && (name[2] == '.')) /* if name starts with ":1." it is a unique name and should be send as number */
291 dst_id = strtoull(&name[3], NULL, 10);
298 ret_size = _dbus_string_get_length (&transport->encoded_outgoing);
301 _dbus_message_get_network_data (message, &header, &body);
302 header_size = _dbus_string_get_length(header);
303 body_size = _dbus_string_get_length(body);
304 ret_size = header_size + body_size;
307 // check if message size is big enough to use memfd kdbus transport
308 use_memfd = ret_size > MEMFD_SIZE_THRESHOLD ? TRUE : FALSE;
309 if(use_memfd) kdbus_init_memfd(transport);
311 _dbus_message_get_unix_fds(message, &unix_fds, &fds_count);
313 // init basic message fields
314 msg = kdbus_init_msg(name, dst_id, body_size, use_memfd, fds_count, transport);
315 msg->cookie = dbus_message_get_serial(message);
316 autostart = dbus_message_get_auto_start (message);
318 msg->flags |= KDBUS_MSG_FLAGS_NO_AUTO_START;
320 // build message contents
323 // case 1 - bulk data transfer - memfd - encoded and plain
328 if(ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 0) < 0)
330 _dbus_verbose("memfd sealing failed: \n");
334 buf = mmap(NULL, ret_size, PROT_WRITE, MAP_SHARED, transport->memfd, 0);
335 if (buf == MAP_FAILED)
337 _dbus_verbose("mmap() fd=%i failed:%m", transport->memfd);
342 memcpy(buf, &transport->encoded_outgoing, ret_size);
345 memcpy(buf, _dbus_string_get_const_data(header), header_size);
348 memcpy(buf, _dbus_string_get_const_data(body), body_size);
353 munmap(buf, ret_size);
355 // seal data - kdbus module needs it
356 if(ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 1) < 0) {
357 _dbus_verbose("memfd sealing failed: %d (%m)\n", errno);
362 item->type = KDBUS_MSG_PAYLOAD_MEMFD;
363 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_memfd);
364 item->memfd.size = ret_size;
365 item->memfd.fd = transport->memfd;
366 // case 2 - small encoded - don't use memfd
368 _dbus_verbose("sending encoded data\n");
369 MSG_ITEM_BUILD_VEC(&transport->encoded_outgoing, _dbus_string_get_length (&transport->encoded_outgoing));
371 // case 3 - small not encoded - don't use memfd
373 _dbus_verbose("sending normal vector data\n");
374 MSG_ITEM_BUILD_VEC(_dbus_string_get_const_data(header), header_size);
378 _dbus_verbose("body attaching\n");
379 item = KDBUS_PART_NEXT(item);
380 MSG_ITEM_BUILD_VEC(_dbus_string_get_const_data(body), body_size);
386 item = KDBUS_PART_NEXT(item);
387 item->type = KDBUS_MSG_FDS;
388 item->size = KDBUS_PART_HEADER_SIZE + (sizeof(int) * fds_count);
389 memcpy(item->fds, unix_fds, sizeof(int) * fds_count);
394 item = KDBUS_PART_NEXT(item);
395 item->type = KDBUS_MSG_DST_NAME;
396 item->size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1;
397 strcpy(item->str, name);
399 else if (dst_id == KDBUS_DST_ID_BROADCAST)
401 item = KDBUS_PART_NEXT(item);
402 item->type = KDBUS_MSG_BLOOM;
403 item->size = KDBUS_PART_HEADER_SIZE + transport->bloom_size;
404 strncpy(item->data, dbus_message_get_interface(message), transport->bloom_size);
408 if (ioctl(transport->fd, KDBUS_CMD_MSG_SEND, msg))
412 if((errno == ESRCH) || (errno == ENXIO) || (errno = EADDRNOTAVAIL)) //when recipient is not available on the bus
416 //todo start service here, otherwise
417 if(!reply_with_error(DBUS_ERROR_SERVICE_UNKNOWN, "The name %s was not provided by any .service files", dbus_message_get_destination(message), message, transport->base.connection))
421 if(!reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Name \"%s\" does not exist", dbus_message_get_destination(message), message, transport->base.connection))
425 _dbus_verbose("kdbus error sending message: err %d (%m)\n", errno);
430 close(transport->memfd);
445 * Performs kdbus query of id of the given name
447 * @param name name to query for
449 * @param ownerID place to store id of the name
450 * @return 0 on success, -errno if failed
452 static int kdbus_NameQuery(char* name, int fd, struct nameInfo* pInfo)
454 struct kdbus_cmd_name_info *msg;
455 struct kdbus_item *item;
460 pInfo->sec_label_len = 0;
461 pInfo->sec_label = NULL;
463 item_size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1;
464 item_size = (item_size < 56) ? 56 : item_size; //at least 56 bytes are needed by kernel to place info about name, otherwise error
465 size = sizeof(struct kdbus_cmd_name_info) + item_size;
470 _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
474 memset(msg, 0, size);
476 if((name[0] == ':') && (name[1] == '1') && (name[2] == '.')) /* if name starts with ":1." it is a unique name and should be send as number */
477 msg->id = strtoull(&name[3], NULL, 10);
482 item->type = KDBUS_NAME_INFO_ITEM_NAME;
483 item->size = item_size;
484 strcpy(item->str, name);
487 ret = ioctl(fd, KDBUS_CMD_NAME_QUERY, msg);
492 else if(ret == -ENOBUFS)
494 msg = realloc(msg, msg->size); //prepare memory
503 pInfo->uniqueId = msg->id;
504 pInfo->userId = msg->creds.uid;
505 pInfo->processId = msg->creds.pid;
506 _dbus_verbose ("I'm alive 1\n");
508 while((uint8_t *)(item) < (uint8_t *)(msg) + msg->size)
510 if(item->type == KDBUS_NAME_INFO_ITEM_SECLABEL)
512 pInfo->sec_label_len = item->size - KDBUS_PART_HEADER_SIZE - 1;
513 if(pInfo->sec_label_len != 0)
514 pInfo->sec_label = malloc(pInfo->sec_label_len);
515 if(pInfo->sec_label == NULL)
518 memcpy(pInfo->sec_label, item->data, pInfo->sec_label_len);
522 item = KDBUS_PART_NEXT(item);
530 static struct kdbus_policy *make_policy_name(const char *name)
532 struct kdbus_policy *p;
535 size = offsetof(struct kdbus_policy, name) + strlen(name) + 1;
541 p->type = KDBUS_POLICY_NAME;
542 strcpy(p->name, name);
547 static struct kdbus_policy *make_policy_access(__u64 type, __u64 bits, __u64 id)
549 struct kdbus_policy *p;
550 __u64 size = sizeof(*p);
558 p->type = KDBUS_POLICY_ACCESS;
559 p->access.type = type;
560 p->access.bits = bits;
566 static void append_policy(struct kdbus_cmd_policy *cmd_policy, struct kdbus_policy *policy, __u64 max_size)
568 struct kdbus_policy *dst = (struct kdbus_policy *) ((char *) cmd_policy + cmd_policy->size);
570 if (cmd_policy->size + policy->size > max_size)
573 memcpy(dst, policy, policy->size);
574 cmd_policy->size += KDBUS_ALIGN8(policy->size);
579 * Registers kdbus policy for given connection.
581 * Policy sets rights of the name (unique or well known) on the bus. Without policy it is
582 * not possible to send or receive messages. It must be set separately for unique id and
583 * well known name of the connection. It is set after registering on the bus, but before
584 * requesting for name. The policy is valid for the given name, not for the connection.
586 * Name of the policy equals name on the bus.
588 * @param name name of the policy = name of the connection
589 * @param connection the connection
590 * @param error place to store errors
592 * @returns #TRUE on success
594 static dbus_bool_t bus_register_policy_kdbus(const char* name, int fd)
596 struct kdbus_cmd_policy *cmd_policy;
597 struct kdbus_policy *policy;
600 cmd_policy = alloca(size);
601 memset(cmd_policy, 0, size);
603 policy = (struct kdbus_policy *) cmd_policy->policies;
604 cmd_policy->size = offsetof(struct kdbus_cmd_policy, policies);
606 policy = make_policy_name(name);
607 append_policy(cmd_policy, policy, size);
609 policy = make_policy_access(KDBUS_POLICY_ACCESS_USER, KDBUS_POLICY_OWN, getuid());
610 append_policy(cmd_policy, policy, size);
612 policy = make_policy_access(KDBUS_POLICY_ACCESS_WORLD, KDBUS_POLICY_RECV, 0);
613 append_policy(cmd_policy, policy, size);
615 policy = make_policy_access(KDBUS_POLICY_ACCESS_WORLD, KDBUS_POLICY_SEND, 0);
616 append_policy(cmd_policy, policy, size);
618 if (ioctl(fd, KDBUS_CMD_EP_POLICY_SET, cmd_policy) < 0)
620 _dbus_verbose ("Error setting policy: %m, %d", errno);
624 _dbus_verbose("Policy %s set correctly\n", name);
629 * Kdbus part of dbus_bus_register.
630 * Shouldn't be used separately because it needs to be surrounded
631 * by other functions as it is done in dbus_bus_register.
633 * @param name place to store unique name given by bus
634 * @param connection the connection
635 * @param error place to store errors
636 * @returns #TRUE on success
638 static dbus_bool_t bus_register_kdbus(char* name, DBusTransportSocket* transportS)
640 struct kdbus_cmd_hello __attribute__ ((__aligned__(8))) hello;
642 hello.conn_flags = KDBUS_HELLO_ACCEPT_FD/* |
643 KDBUS_HELLO_ATTACH_COMM |
644 KDBUS_HELLO_ATTACH_EXE |
645 KDBUS_HELLO_ATTACH_CMDLINE |
646 KDBUS_HELLO_ATTACH_CAPS |
647 KDBUS_HELLO_ATTACH_CGROUP |
648 KDBUS_HELLO_ATTACH_SECLABEL |
649 KDBUS_HELLO_ATTACH_AUDIT*/;
650 hello.size = sizeof(struct kdbus_cmd_hello);
651 hello.pool_size = RECEIVE_POOL_SIZE;
653 if (ioctl(transportS->fd, KDBUS_CMD_HELLO, &hello))
655 _dbus_verbose ("Failed to send hello: %m, %d",errno);
659 sprintf(name, "%llu", (unsigned long long)hello.id);
660 _dbus_verbose("-- Our peer ID is: %s\n", name);
661 transportS->bloom_size = hello.bloom_size;
663 transportS->kdbus_mmap_ptr = mmap(NULL, RECEIVE_POOL_SIZE, PROT_READ, MAP_SHARED, transportS->fd, 0);
664 if (transportS->kdbus_mmap_ptr == MAP_FAILED)
666 _dbus_verbose("Error when mmap: %m, %d",errno);
674 * kdbus version of dbus_bus_request_name.
676 * Asks the bus to assign the given name to this connection.
678 * Use same flags as original dbus version with one exception below.
679 * Result flag #DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER is currently
680 * never returned by kdbus, instead DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER
681 * is returned by kdbus.
683 * @param connection the connection
684 * @param name the name to request
686 * @param error location to store the error
687 * @returns a result code, -1 if error is set
689 static int bus_request_name_kdbus(int fd, const char *name, const uint64_t flags)
691 struct kdbus_cmd_name *cmd_name;
693 uint64_t size = sizeof(*cmd_name) + strlen(name) + 1;
694 uint64_t flags_kdbus = 0;
696 cmd_name = alloca(size);
698 memset(cmd_name, 0, size);
699 strcpy(cmd_name->name, name);
700 cmd_name->size = size;
702 if(flags & DBUS_NAME_FLAG_ALLOW_REPLACEMENT)
703 flags_kdbus |= KDBUS_NAME_ALLOW_REPLACEMENT;
704 if(!(flags & DBUS_NAME_FLAG_DO_NOT_QUEUE))
705 flags_kdbus |= KDBUS_NAME_QUEUE;
706 if(flags & DBUS_NAME_FLAG_REPLACE_EXISTING)
707 flags_kdbus |= KDBUS_NAME_REPLACE_EXISTING;
709 cmd_name->conn_flags = flags_kdbus;
711 _dbus_verbose("Request name - flags sent: 0x%llx !!!!!!!!!\n", cmd_name->conn_flags);
713 if (ioctl(fd, KDBUS_CMD_NAME_ACQUIRE, cmd_name))
715 _dbus_verbose ("error acquiring name '%s': %m, %d", name, errno);
717 return DBUS_REQUEST_NAME_REPLY_EXISTS;
721 _dbus_verbose("Request name - received flag: 0x%llx !!!!!!!!!\n", cmd_name->conn_flags);
723 if(cmd_name->conn_flags & KDBUS_NAME_IN_QUEUE)
724 return DBUS_REQUEST_NAME_REPLY_IN_QUEUE;
726 return DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER;
727 /*todo now 1 code is never returned - DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER
728 * because kdbus never returns it now
733 * Seeks key in rule string, and duplicates value of the key into pValue.
734 * If value is "org.freedesktop.DBus" it is indicated by returning -1, because it
735 * needs to be handled in different manner.
736 * Value is duplicated from rule string to newly allocated memory pointe by pValue,
737 * so it must be freed after use.
739 * @param rule rule to look through
740 * @param key key to look for
741 * @param pValue pointer to value of the key found
742 * @return length of the value string, 0 means not found, -1 means "org.freedesktop.DBus"
744 static int parse_match_key(const char *rule, const char* key, char** pValue)
747 const char* pValueEnd;
748 int value_length = 0;
750 pBegin = strstr(rule, key);
753 pBegin += strlen(key);
754 pValueEnd = strchr(pBegin, '\'');
757 value_length = pValueEnd - pBegin;
758 *pValue = strndup(pBegin, value_length);
761 if(strcmp(*pValue, "org.freedesktop.DBus") == 0)
763 _dbus_verbose ("found for key: %s value:'%s'\n", key, *pValue);
771 * Adds a match rule to match broadcast messages going through the message bus.
772 * Do no affect messages addressed directly.
774 * The "rule" argument is the string form of a match rule.
776 * In kdbus function do not blocks.
778 * Upper function returns nothing because of blocking issues
779 * so there is no point to return true or false here.
781 * Only part of the dbus's matching capabilities is implemented in kdbus now, because of different mechanism.
783 * interface match key mapped to bloom
784 * sender match key mapped to src_name
785 * also handled org.freedesktop.dbus members: NameOwnerChanged, NameLost, NameAcquired
787 * @param connection connection to the message bus
788 * @param rule textual form of match rule
789 * @param error location to store any errors - may be NULL
791 static dbus_bool_t dbus_bus_add_match_kdbus (DBusTransportSocket* transportS, const char *rule)
793 struct kdbus_cmd_match* pCmd_match;
794 struct kdbus_item *pItem;
795 __u64 src_id = KDBUS_MATCH_SRC_ID_ANY;
797 unsigned int kernel_item = 0;
800 char* pInterface = NULL;
801 dbus_bool_t ret_value = FALSE;
803 /*parsing rule and calculating size of command*/
804 size = sizeof(struct kdbus_cmd_match);
806 if(strstr(rule, "member='NameOwnerChanged'"))
809 size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2; /*std DBus: 3 name related items plus 2 id related items*/
811 else if(strstr(rule, "member='NameChanged'"))
813 kernel_item = KDBUS_MATCH_NAME_CHANGE;
814 size += KDBUS_ITEM_SIZE(1);
816 else if(strstr(rule, "member='NameLost'"))
818 kernel_item = KDBUS_MATCH_NAME_REMOVE;
819 size += KDBUS_ITEM_SIZE(1);
821 else if(strstr(rule, "member='NameAcquired'"))
823 kernel_item = KDBUS_MATCH_NAME_ADD;
824 size += KDBUS_ITEM_SIZE(1);
827 name_size = parse_match_key(rule, "interface='", &pInterface);
828 if((name_size == -1) && (kernel_item == 0)) //means org.freedesktop.DBus without specified member
831 size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2; /* 3 above name related items plus 2 id related items*/
833 else if(name_size > 0) /*actual size is not important for interface because bloom size is defined by bus*/
834 size += KDBUS_PART_HEADER_SIZE + transportS->bloom_size;
836 name_size = parse_match_key(rule, "sender='", &pName);
837 if((name_size == -1) && (kernel_item == 0)) //means org.freedesktop.DBus without specified name - same as interface few line above
840 size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2; /* 3 above name related items plus 2 id related items*/
842 else if(name_size > 0)
844 if(!strncmp(pName, ":1.", 3)) /*if name is unique name it must be converted to unique id*/
846 src_id = strtoull(&pName[3], NULL, 10);
851 size += KDBUS_ITEM_SIZE(name_size + 1); //well known name
854 pCmd_match = alloca(size);
855 if(pCmd_match == NULL)
859 pCmd_match->size = size;
860 pCmd_match->cookie = strtoull(dbus_bus_get_unique_name(transportS->base.connection), NULL , 10);
862 pItem = pCmd_match->items;
863 if(kernel_item == ~0) //all signals from kernel
865 pCmd_match->src_id = 0;
866 pItem->type = KDBUS_MATCH_NAME_CHANGE;
867 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
868 pItem = KDBUS_PART_NEXT(pItem);
869 pItem->type = KDBUS_MATCH_NAME_ADD;
870 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
871 pItem = KDBUS_PART_NEXT(pItem);
872 pItem->type = KDBUS_MATCH_NAME_REMOVE;
873 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
874 pItem = KDBUS_PART_NEXT(pItem);
875 pItem->type = KDBUS_MATCH_ID_ADD;
876 pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64);
877 pItem = KDBUS_PART_NEXT(pItem);
878 pItem->type = KDBUS_MATCH_ID_REMOVE;
879 pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64);
881 else if(kernel_item) //only one item
883 pCmd_match->src_id = 0;
884 pItem->type = kernel_item;
885 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
889 pCmd_match->src_id = src_id;
892 pItem->type = KDBUS_MATCH_SRC_NAME;
893 pItem->size = KDBUS_PART_HEADER_SIZE + name_size + 1;
894 strcpy(pItem->str, pName);
895 pItem = KDBUS_PART_NEXT(pItem);
900 pItem->type = KDBUS_MATCH_BLOOM;
901 pItem->size = KDBUS_PART_HEADER_SIZE + transportS->bloom_size;
902 strncpy(pItem->data, pInterface, transportS->bloom_size);
906 if(ioctl(transportS->fd, KDBUS_CMD_MATCH_ADD, pCmd_match))
907 _dbus_verbose("Failed adding match bus rule %s,\nerror: %d, %m\n", rule, errno);
910 _dbus_verbose("Added match bus rule %s\n", rule);
923 * Opposing to dbus, in kdbus removes all match rules with given
924 * cookie, which now is equal to uniqe id.
926 * In kdbus this function will not block
928 * @param connection connection to the message bus
929 * @param error location to store any errors - may be NULL
931 static dbus_bool_t dbus_bus_remove_match_kdbus (DBusTransportSocket* transportS)
933 struct kdbus_cmd_match __attribute__ ((__aligned__(8))) cmd;
935 cmd.cookie = strtoull(dbus_bus_get_unique_name(transportS->base.connection), NULL , 10);
937 cmd.size = sizeof(struct kdbus_cmd_match);
939 if(ioctl(transportS->fd, KDBUS_CMD_MATCH_ADD, &cmd))
941 _dbus_verbose("Failed removing match rule; error: %d, %m\n", errno);
946 _dbus_verbose("Match rule removed correctly.\n");
952 * Handles messages sent to bus daemon - "org.freedesktop.DBus" and translates them to appropriate
953 * kdbus ioctl commands. Than translate kdbus reply into dbus message and put it into recived messages queue.
955 * !!! Not all methods are handled !!! Doubt if it is even possible.
956 * If method is not handled, returns error reply org.freedesktop.DBus.Error.UnknownMethod
963 * Not handled methods:
964 * - ListActivatableNames
965 * - StartServiceByName
966 * - UpdateActivationEnvironment
967 * - GetConnectionUnixUser
970 static int emulateOrgFreedesktopDBus(DBusTransport *transport, DBusMessage *message)
973 struct nameInfo info;
976 if(!strcmp(dbus_message_get_member(message), "Hello"))
981 name = malloc(snprintf(name, 0, "%llu", ULLONG_MAX) + 1);
984 if(!bus_register_kdbus(name, (DBusTransportSocket*)transport))
986 if(!bus_register_policy_kdbus(name, ((DBusTransportSocket*)transport)->fd))
989 sender = malloc (strlen(name) + 4);
992 sprintf(sender, ":1.%s", name);
993 ((DBusTransportSocket*)transport)->sender = sender;
995 if(!reply_1_data(message, DBUS_TYPE_STRING, &name, transport->connection))
996 return 0; //todo why we cannot free name after sending reply?
1003 else if(!strcmp(dbus_message_get_member(message), "RequestName"))
1009 if(!dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_UINT32, &flags, DBUS_TYPE_INVALID))
1011 if(!bus_register_policy_kdbus(name, ((DBusTransportSocket*)transport)->fd))
1014 result = bus_request_name_kdbus(((DBusTransportSocket*)transport)->fd, name, flags);
1015 return reply_1_data(message, DBUS_TYPE_UINT32, &result, transport->connection);
1017 else if(!strcmp(dbus_message_get_member(message), "AddMatch"))
1021 if(!dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &rule, DBUS_TYPE_INVALID))
1024 if(!dbus_bus_add_match_kdbus((DBusTransportSocket*)transport, rule))
1027 return reply_ack(message,transport->connection);
1029 else if(!strcmp(dbus_message_get_member(message), "RemoveMatch"))
1031 if(!dbus_bus_remove_match_kdbus((DBusTransportSocket*)transport))
1033 return reply_ack(message, transport->connection);
1035 else if(!strcmp(dbus_message_get_member(message), "GetNameOwner")) //returns id of the well known name
1039 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1040 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
1041 if(inter_ret == 0) //unique id of the name
1043 char unique_name[(unsigned int)(snprintf(name, 0, "%llu", ULLONG_MAX) + sizeof(":1."))];
1044 const char* pString = unique_name;
1046 sprintf(unique_name, ":1.%llu", (unsigned long long int)info.uniqueId);
1047 _dbus_verbose("Unique name discovered:%s\n", unique_name);
1048 ret_value = reply_1_data(message, DBUS_TYPE_STRING, &pString, transport->connection);
1050 else if(inter_ret == -ENOENT) //name has no owner
1051 return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get owner of name '%s': no such name", name, message, transport->connection);
1054 _dbus_verbose("kdbus error sending name query: err %d (%m)\n", errno);
1055 ret_value = reply_with_error(DBUS_ERROR_FAILED, "Could not determine unique name for '%s'", name, message, transport->connection);
1058 else if(!strcmp(dbus_message_get_member(message), "NameHasOwner")) //returns if name is currently registered on the bus
1063 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1064 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
1065 if((inter_ret == 0) || (inter_ret == -ENOENT))
1067 result = (inter_ret == 0) ? TRUE : FALSE;
1068 ret_value = reply_1_data(message, DBUS_TYPE_BOOLEAN, &result, transport->connection);
1072 _dbus_verbose("kdbus error checking if name exists: err %d (%m)\n", errno);
1073 ret_value = reply_with_error(DBUS_ERROR_FAILED, "Could not determine whether name '%s' exists", name, message, transport->connection);
1076 else if(!strcmp(dbus_message_get_member(message), "GetConnectionUnixUser"))
1080 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1081 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
1082 if(inter_ret == 0) //name found
1084 _dbus_verbose("User id:%llu\n", (unsigned long long) info.userId);
1085 ret_value = reply_1_data(message, DBUS_TYPE_UINT32, &info.userId, transport->connection);
1087 else if(inter_ret == -ENOENT) //name has no owner
1088 return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get UID of name '%s': no such name", name, message, transport->connection);
1091 _dbus_verbose("kdbus error determining UID: err %d (%m)\n", errno);
1092 ret_value = reply_with_error(DBUS_ERROR_FAILED, "Could not determine UID for '%s'", name, message, transport->connection);
1095 else if(!strcmp(dbus_message_get_member(message), "GetConnectionUnixProcessID"))
1099 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1100 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
1101 if(inter_ret == 0) //name found
1102 ret_value = reply_1_data(message, DBUS_TYPE_UINT32, &info.processId, transport->connection);
1103 else if(inter_ret == -ENOENT) //name has no owner
1104 return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get PID of name '%s': no such name", name, message, transport->connection);
1107 _dbus_verbose("kdbus error determining PID: err %d (%m)\n", errno);
1108 ret_value = reply_with_error(DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN,"Could not determine PID for '%s'", name, message, transport->connection);
1111 else if(!strcmp(dbus_message_get_member(message), "ListNames")) //return all well known names on he bus
1113 struct kdbus_cmd_names* pCmd;
1116 cmd_size = sizeof(struct kdbus_cmd_names) + KDBUS_ITEM_SIZE(1);
1117 pCmd = malloc(cmd_size);
1120 pCmd->size = cmd_size;
1124 if(ioctl(((DBusTransportSocket*)transport)->fd, KDBUS_CMD_NAME_LIST, pCmd))
1128 if(errno == ENOBUFS) //buffer to small to put all names into it
1129 cmd_size = pCmd->size; //here kernel tells how much memory it needs
1132 _dbus_verbose("kdbus error asking for name list: err %d (%m)\n",errno);
1136 if(cmd_size) //kernel needs more memory
1138 pCmd = realloc(pCmd, cmd_size); //prepare memory
1141 goto again; //and try again
1146 DBusMessageIter args;
1147 struct kdbus_cmd_name* pCmd_name;
1150 reply = dbus_message_new_method_return(message);
1153 dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
1154 dbus_message_iter_init_append(reply, &args);
1156 for (pCmd_name = pCmd->names; (uint8_t *)(pCmd_name) < (uint8_t *)(pCmd) + pCmd->size; pCmd_name = KDBUS_PART_NEXT(pCmd_name))
1158 pName = pCmd_name->name;
1159 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pName))
1161 dbus_message_unref(reply);
1166 if(add_message_to_received(reply, transport->connection))
1177 else if(!strcmp(dbus_message_get_member(message), "GetId"))
1180 char uuid[DBUS_UUID_LENGTH_BYTES];
1183 DBusString binary, encoded;
1186 path = &transport->address[11]; //start of kdbus bus path
1187 if(stat(path, &stats) < -1)
1189 _dbus_verbose("kdbus error reading stats of bus: err %d (%m)\n", errno);
1190 return reply_with_error(DBUS_ERROR_FAILED, "Could not determine bus '%s' uuid", path, message, transport->connection);
1194 MD5_Update(&md5, path, strlen(path));
1195 MD5_Update(&md5, &stats.st_ctim.tv_sec, sizeof(stats.st_ctim.tv_sec));
1196 MD5_Final(uuid, &md5);
1198 if(!_dbus_string_init (&encoded))
1200 _dbus_string_init_const_len (&binary, uuid, DBUS_UUID_LENGTH_BYTES);
1201 if(!_dbus_string_hex_encode (&binary, 0, &encoded, _dbus_string_get_length (&encoded)))
1203 path = (char*)_dbus_string_get_const_data (&encoded);
1204 ret_value = reply_1_data(message, DBUS_TYPE_STRING, &path, transport->connection);
1207 _dbus_string_free(&binary);
1208 _dbus_string_free(&encoded);
1212 else if(!strcmp(dbus_message_get_member(message), "GetAdtAuditSessionData"))
1216 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1217 return reply_with_error(DBUS_ERROR_ADT_AUDIT_DATA_UNKNOWN, "Could not determine audit session data for '%s'", name, message, transport->connection);
1219 else if(!strcmp(dbus_message_get_member(message), "GetConnectionSELinuxSecurityContext"))
1223 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1224 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
1225 if(inter_ret == -ENOENT) //name has no owner
1226 return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get security context of name '%s': no such name", name, message, transport->connection);
1227 else if(inter_ret < 0)
1228 return reply_with_error(DBUS_ERROR_SELINUX_SECURITY_CONTEXT_UNKNOWN, "Could not determine security context for '%s'", name, message, transport->connection);
1234 reply = dbus_message_new_method_return(message);
1237 dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
1238 if (!dbus_message_append_args (reply, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &info.sec_label, info.sec_label_len, DBUS_TYPE_INVALID))
1239 dbus_message_unref(reply);
1240 else if(add_message_to_received(reply, transport->connection))
1246 return reply_with_error(DBUS_ERROR_UNKNOWN_METHOD, NULL, (char*)dbus_message_get_member(message), message, transport->connection);
1247 /* else if(!strcmp(dbus_message_get_member(message), "ListActivatableNames")) //todo
1251 else if(!strcmp(dbus_message_get_member(message), "StartServiceByName"))
1255 else if(!strcmp(dbus_message_get_member(message), "UpdateActivationEnvironment"))
1259 else if(!strcmp(dbus_message_get_member(message), "ReloadConfig"))
1266 free(info.sec_label);
1270 #if KDBUS_MSG_DECODE_DEBUG == 1
1271 static char *msg_id(uint64_t id, char *buf)
1277 sprintf(buf, "%llu", (unsigned long long)id);
1281 struct kdbus_enum_table {
1285 #define _STRINGIFY(x) #x
1286 #define STRINGIFY(x) _STRINGIFY(x)
1287 #define ELEMENTSOF(x) (sizeof(x)/sizeof((x)[0]))
1288 #define TABLE(what) static struct kdbus_enum_table kdbus_table_##what[]
1289 #define ENUM(_id) { .id=_id, .name=STRINGIFY(_id) }
1290 #define LOOKUP(what) \
1291 const char *enum_##what(long long id) { \
1293 for (i = 0; i < ELEMENTSOF(kdbus_table_##what); i++) \
1294 if (id == kdbus_table_##what[i].id) \
1295 return kdbus_table_##what[i].name; \
1298 const char *enum_MSG(long long id);
1300 ENUM(_KDBUS_MSG_NULL),
1301 ENUM(KDBUS_MSG_PAYLOAD_VEC),
1302 ENUM(KDBUS_MSG_PAYLOAD_OFF),
1303 ENUM(KDBUS_MSG_PAYLOAD_MEMFD),
1304 ENUM(KDBUS_MSG_FDS),
1305 ENUM(KDBUS_MSG_BLOOM),
1306 ENUM(KDBUS_MSG_DST_NAME),
1307 ENUM(KDBUS_MSG_SRC_CREDS),
1308 ENUM(KDBUS_MSG_SRC_PID_COMM),
1309 ENUM(KDBUS_MSG_SRC_TID_COMM),
1310 ENUM(KDBUS_MSG_SRC_EXE),
1311 ENUM(KDBUS_MSG_SRC_CMDLINE),
1312 ENUM(KDBUS_MSG_SRC_CGROUP),
1313 ENUM(KDBUS_MSG_SRC_CAPS),
1314 ENUM(KDBUS_MSG_SRC_SECLABEL),
1315 ENUM(KDBUS_MSG_SRC_AUDIT),
1316 ENUM(KDBUS_MSG_SRC_NAMES),
1317 ENUM(KDBUS_MSG_TIMESTAMP),
1318 ENUM(KDBUS_MSG_NAME_ADD),
1319 ENUM(KDBUS_MSG_NAME_REMOVE),
1320 ENUM(KDBUS_MSG_NAME_CHANGE),
1321 ENUM(KDBUS_MSG_ID_ADD),
1322 ENUM(KDBUS_MSG_ID_REMOVE),
1323 ENUM(KDBUS_MSG_REPLY_TIMEOUT),
1324 ENUM(KDBUS_MSG_REPLY_DEAD),
1327 const char *enum_PAYLOAD(long long id);
1329 ENUM(KDBUS_PAYLOAD_KERNEL),
1330 ENUM(KDBUS_PAYLOAD_DBUS1),
1331 ENUM(KDBUS_PAYLOAD_GVARIANT),
1336 * Puts locally generated message into received data buffer.
1337 * Use only during receiving phase!
1339 * @param message message to load
1340 * @param data place to load message
1341 * @return size of message
1343 static int put_message_into_data(DBusMessage *message, char* data)
1346 const DBusString *header;
1347 const DBusString *body;
1350 dbus_message_set_serial(message, 1);
1351 dbus_message_lock (message);
1352 _dbus_message_get_network_data (message, &header, &body);
1353 ret_size = _dbus_string_get_length(header);
1354 memcpy(data, _dbus_string_get_const_data(header), ret_size);
1356 size = _dbus_string_get_length(body);
1357 memcpy(data, _dbus_string_get_const_data(body), size);
1363 * Decodes kdbus message in order to extract dbus message and put it into data and fds.
1364 * Also captures and decodes kdbus error messages and kdbus kernel broadcasts and converts
1365 * all of them into dbus messages.
1367 * @param msg kdbus message
1368 * @param data place to copy dbus message to
1369 * @param socket_transport transport
1370 * @param fds place to store file descriptors received
1371 * @param n_fds place to store quantity of file descriptor
1372 * @return number of dbus message's bytes received or -1 on error
1374 static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTransportSocket* socket_transport, int* fds, int* n_fds)
1376 const struct kdbus_item *item;
1378 DBusMessage *message = NULL;
1379 DBusMessageIter args;
1380 const char* emptyString = "";
1381 const char* pString = NULL;
1382 char dbus_name[(unsigned int)(snprintf((char*)pString, 0, "%llu", ULLONG_MAX) + sizeof(":1."))];
1383 const char* pDBusName = dbus_name;
1384 #if KDBUS_MSG_DECODE_DEBUG == 1
1388 #if KDBUS_MSG_DECODE_DEBUG == 1
1389 _dbus_verbose("MESSAGE: %s (%llu bytes) flags=0x%llx, %s → %s, cookie=%llu, timeout=%llu\n",
1390 enum_PAYLOAD(msg->payload_type), (unsigned long long) msg->size,
1391 (unsigned long long) msg->flags,
1392 msg_id(msg->src_id, buf), msg_id(msg->dst_id, buf),
1393 (unsigned long long) msg->cookie, (unsigned long long) msg->timeout_ns);
1398 KDBUS_PART_FOREACH(item, msg, items)
1400 if (item->size <= KDBUS_PART_HEADER_SIZE)
1402 _dbus_verbose(" +%s (%llu bytes) invalid data record\n", enum_MSG(item->type), item->size);
1403 break; //??? continue (because dbus will find error) or break
1408 case KDBUS_MSG_PAYLOAD_OFF:
1409 memcpy(data, (char *)socket_transport->kdbus_mmap_ptr + item->vec.offset, item->vec.size);
1410 data += item->vec.size;
1411 ret_size += item->vec.size;
1413 _dbus_verbose(" +%s (%llu bytes) off=%llu size=%llu\n",
1414 enum_MSG(item->type), item->size,
1415 (unsigned long long)item->vec.offset,
1416 (unsigned long long)item->vec.size);
1419 case KDBUS_MSG_PAYLOAD_MEMFD:
1424 size = item->memfd.size;
1425 _dbus_verbose("memfd.size : %llu\n", (unsigned long long)size);
1427 buf = mmap(NULL, size, PROT_READ , MAP_SHARED, item->memfd.fd, 0);
1428 if (buf == MAP_FAILED)
1430 _dbus_verbose("mmap() fd=%i failed:%m", item->memfd.fd);
1434 memcpy(data, buf, size);
1440 _dbus_verbose(" +%s (%llu bytes) off=%llu size=%llu\n",
1441 enum_MSG(item->type), item->size,
1442 (unsigned long long)item->vec.offset,
1443 (unsigned long long)item->vec.size);
1451 *n_fds = (item->size - KDBUS_PART_HEADER_SIZE) / sizeof(int);
1452 memcpy(fds, item->fds, *n_fds * sizeof(int));
1453 for (i = 0; i < *n_fds; i++)
1454 _dbus_fd_set_close_on_exec(fds[i]);
1458 #if KDBUS_MSG_DECODE_DEBUG == 1
1459 case KDBUS_MSG_SRC_CREDS:
1460 _dbus_verbose(" +%s (%llu bytes) uid=%lld, gid=%lld, pid=%lld, tid=%lld, starttime=%lld\n",
1461 enum_MSG(item->type), item->size,
1462 item->creds.uid, item->creds.gid,
1463 item->creds.pid, item->creds.tid,
1464 item->creds.starttime);
1467 case KDBUS_MSG_SRC_PID_COMM:
1468 case KDBUS_MSG_SRC_TID_COMM:
1469 case KDBUS_MSG_SRC_EXE:
1470 case KDBUS_MSG_SRC_CGROUP:
1471 case KDBUS_MSG_SRC_SECLABEL:
1472 case KDBUS_MSG_DST_NAME:
1473 _dbus_verbose(" +%s (%llu bytes) '%s' (%zu)\n",
1474 enum_MSG(item->type), item->size, item->str, strlen(item->str));
1477 case KDBUS_MSG_SRC_CMDLINE:
1478 case KDBUS_MSG_SRC_NAMES: {
1479 __u64 size = item->size - KDBUS_PART_HEADER_SIZE;
1480 const char *str = item->str;
1483 _dbus_verbose(" +%s (%llu bytes) ", enum_MSG(item->type), item->size);
1485 _dbus_verbose("'%s' ", str);
1486 size -= strlen(str) + 1;
1487 str += strlen(str) + 1;
1491 _dbus_verbose("(%d string%s)\n", count, (count == 1) ? "" : "s");
1495 case KDBUS_MSG_SRC_AUDIT:
1496 _dbus_verbose(" +%s (%llu bytes) loginuid=%llu sessionid=%llu\n",
1497 enum_MSG(item->type), item->size,
1498 (unsigned long long)item->data64[0],
1499 (unsigned long long)item->data64[1]);
1502 case KDBUS_MSG_SRC_CAPS: {
1504 const uint32_t *cap;
1507 _dbus_verbose(" +%s (%llu bytes) len=%llu bytes)\n",
1508 enum_MSG(item->type), item->size,
1509 (unsigned long long)item->size - KDBUS_PART_HEADER_SIZE);
1512 n = (item->size - KDBUS_PART_HEADER_SIZE) / 4 / sizeof(uint32_t);
1514 _dbus_verbose(" CapInh=");
1515 for (i = 0; i < n; i++)
1516 _dbus_verbose("%08x", cap[(0 * n) + (n - i - 1)]);
1518 _dbus_verbose(" CapPrm=");
1519 for (i = 0; i < n; i++)
1520 _dbus_verbose("%08x", cap[(1 * n) + (n - i - 1)]);
1522 _dbus_verbose(" CapEff=");
1523 for (i = 0; i < n; i++)
1524 _dbus_verbose("%08x", cap[(2 * n) + (n - i - 1)]);
1526 _dbus_verbose(" CapInh=");
1527 for (i = 0; i < n; i++)
1528 _dbus_verbose("%08x", cap[(3 * n) + (n - i - 1)]);
1529 _dbus_verbose("\n");
1533 case KDBUS_MSG_TIMESTAMP:
1534 _dbus_verbose(" +%s (%llu bytes) realtime=%lluns monotonic=%lluns\n",
1535 enum_MSG(item->type), item->size,
1536 (unsigned long long)item->timestamp.realtime_ns,
1537 (unsigned long long)item->timestamp.monotonic_ns);
1541 case KDBUS_MSG_REPLY_TIMEOUT:
1542 _dbus_verbose(" +%s (%llu bytes) cookie=%llu\n",
1543 enum_MSG(item->type), item->size, msg->cookie_reply);
1545 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NO_REPLY, NULL);
1552 ret_size = put_message_into_data(message, data);
1555 case KDBUS_MSG_REPLY_DEAD:
1556 _dbus_verbose(" +%s (%llu bytes) cookie=%llu\n",
1557 enum_MSG(item->type), item->size, msg->cookie_reply);
1559 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NAME_HAS_NO_OWNER, NULL);
1566 ret_size = put_message_into_data(message, data);
1569 case KDBUS_MSG_NAME_ADD:
1570 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1571 enum_MSG(item->type), (unsigned long long) item->size,
1572 item->name_change.name, item->name_change.old_id,
1573 item->name_change.new_id, item->name_change.flags);
1575 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1582 sprintf(dbus_name,":1.%llu",item->name_change.new_id);
1583 pString = item->name_change.name;
1584 _dbus_verbose ("Name added: %s\n", pString);
1585 dbus_message_iter_init_append(message, &args);
1586 ITER_APPEND_STR(pString)
1587 ITER_APPEND_STR(emptyString)
1588 ITER_APPEND_STR(pDBusName)
1589 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1591 ret_size = put_message_into_data(message, data);
1594 case KDBUS_MSG_NAME_REMOVE:
1595 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1596 enum_MSG(item->type), (unsigned long long) item->size,
1597 item->name_change.name, item->name_change.old_id,
1598 item->name_change.new_id, item->name_change.flags);
1600 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged"); // name of the signal
1607 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
1608 pString = item->name_change.name;
1609 _dbus_verbose ("Name removed: %s\n", pString);
1610 dbus_message_iter_init_append(message, &args);
1611 ITER_APPEND_STR(pString)
1612 ITER_APPEND_STR(pDBusName)
1613 ITER_APPEND_STR(emptyString)
1614 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1616 ret_size = put_message_into_data(message, data);
1619 case KDBUS_MSG_NAME_CHANGE:
1620 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1621 enum_MSG(item->type), (unsigned long long) item->size,
1622 item->name_change.name, item->name_change.old_id,
1623 item->name_change.new_id, item->name_change.flags);
1625 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1632 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
1633 pString = item->name_change.name;
1634 _dbus_verbose ("Name changed: %s\n", pString);
1635 dbus_message_iter_init_append(message, &args);
1636 ITER_APPEND_STR(pString)
1637 ITER_APPEND_STR(pDBusName)
1638 sprintf(&dbus_name[3],"%llu",item->name_change.new_id);
1639 _dbus_verbose ("New id: %s\n", pDBusName);
1640 ITER_APPEND_STR(pDBusName)
1641 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1643 ret_size = put_message_into_data(message, data);
1646 case KDBUS_MSG_ID_ADD:
1647 _dbus_verbose(" +%s (%llu bytes) id=%llu flags=%llu\n",
1648 enum_MSG(item->type), (unsigned long long) item->size,
1649 (unsigned long long) item->id_change.id,
1650 (unsigned long long) item->id_change.flags);
1652 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1659 sprintf(dbus_name,":1.%llu",item->id_change.id);
1660 dbus_message_iter_init_append(message, &args);
1661 ITER_APPEND_STR(pDBusName)
1662 ITER_APPEND_STR(emptyString)
1663 ITER_APPEND_STR(pDBusName)
1664 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1666 ret_size = put_message_into_data(message, data);
1669 case KDBUS_MSG_ID_REMOVE:
1670 _dbus_verbose(" +%s (%llu bytes) id=%llu flags=%llu\n",
1671 enum_MSG(item->type), (unsigned long long) item->size,
1672 (unsigned long long) item->id_change.id,
1673 (unsigned long long) item->id_change.flags);
1675 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1682 sprintf(dbus_name,":1.%llu",item->id_change.id);
1683 dbus_message_iter_init_append(message, &args);
1684 ITER_APPEND_STR(pDBusName)
1685 ITER_APPEND_STR(pDBusName)
1686 ITER_APPEND_STR(emptyString)
1687 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1689 ret_size = put_message_into_data(message, data);
1691 #if KDBUS_MSG_DECODE_DEBUG == 1
1693 _dbus_verbose(" +%s (%llu bytes)\n", enum_MSG(item->type), item->size);
1699 #if KDBUS_MSG_DECODE_DEBUG == 1
1701 if ((char *)item - ((char *)msg + msg->size) >= 8)
1702 _dbus_verbose("invalid padding at end of message\n");
1707 dbus_message_unref(message);
1712 * Reads message from kdbus and puts it into dbus buffer and fds
1714 * @param transport transport
1715 * @param buffer place to copy received message to
1716 * @param fds place to store file descriptors sent in the message
1717 * @param n_fds place to store number of file descriptors
1718 * @return size of received message on success, -1 on error
1720 static int kdbus_read_message(DBusTransportSocket *socket_transport, DBusString *buffer, int* fds, int* n_fds)
1723 uint64_t __attribute__ ((__aligned__(8))) offset;
1724 struct kdbus_msg *msg;
1728 start = _dbus_string_get_length (buffer);
1729 if (!_dbus_string_lengthen (buffer, socket_transport->max_bytes_read_per_iteration))
1734 data = _dbus_string_get_data_len (buffer, start, socket_transport->max_bytes_read_per_iteration);
1737 if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RECV, &offset) < 0)
1741 _dbus_verbose("kdbus error receiving message: %d (%m)\n", errno);
1742 _dbus_string_set_length (buffer, start);
1746 msg = (struct kdbus_msg *)((char*)socket_transport->kdbus_mmap_ptr + offset);
1748 ret_size = kdbus_decode_msg(msg, data, socket_transport, fds, n_fds);
1750 if(ret_size == -1) /* error */
1752 _dbus_string_set_length (buffer, start);
1756 _dbus_string_set_length (buffer, start + ret_size);
1760 if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RELEASE, &offset) < 0)
1764 _dbus_verbose("kdbus error freeing message: %d (%m)\n", errno);
1772 free_watches (DBusTransport *transport)
1774 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1776 _dbus_verbose ("start\n");
1778 if (socket_transport->read_watch)
1780 if (transport->connection)
1781 _dbus_connection_remove_watch_unlocked (transport->connection,
1782 socket_transport->read_watch);
1783 _dbus_watch_invalidate (socket_transport->read_watch);
1784 _dbus_watch_unref (socket_transport->read_watch);
1785 socket_transport->read_watch = NULL;
1788 if (socket_transport->write_watch)
1790 if (transport->connection)
1791 _dbus_connection_remove_watch_unlocked (transport->connection,
1792 socket_transport->write_watch);
1793 _dbus_watch_invalidate (socket_transport->write_watch);
1794 _dbus_watch_unref (socket_transport->write_watch);
1795 socket_transport->write_watch = NULL;
1798 _dbus_verbose ("end\n");
1802 socket_finalize (DBusTransport *transport)
1804 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1806 _dbus_verbose ("\n");
1808 free_watches (transport);
1810 _dbus_string_free (&socket_transport->encoded_outgoing);
1811 _dbus_string_free (&socket_transport->encoded_incoming);
1813 _dbus_transport_finalize_base (transport);
1815 _dbus_assert (socket_transport->read_watch == NULL);
1816 _dbus_assert (socket_transport->write_watch == NULL);
1818 dbus_free (transport);
1822 check_write_watch (DBusTransport *transport)
1824 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1827 if (transport->connection == NULL)
1830 if (transport->disconnected)
1832 _dbus_assert (socket_transport->write_watch == NULL);
1836 _dbus_transport_ref (transport);
1838 #ifdef DBUS_AUTHENTICATION
1839 if (_dbus_transport_get_is_authenticated (transport))
1841 needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection);
1842 #ifdef DBUS_AUTHENTICATION
1845 if (transport->send_credentials_pending)
1849 DBusAuthState auth_state;
1851 auth_state = _dbus_auth_do_work (transport->auth);
1853 /* If we need memory we install the write watch just in case,
1854 * if there's no need for it, it will get de-installed
1855 * next time we try reading.
1857 if (auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND ||
1858 auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY)
1865 _dbus_verbose ("check_write_watch(): needed = %d on connection %p watch %p fd = %d outgoing messages exist %d\n",
1866 needed, transport->connection, socket_transport->write_watch,
1867 socket_transport->fd,
1868 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1870 _dbus_connection_toggle_watch_unlocked (transport->connection,
1871 socket_transport->write_watch,
1874 _dbus_transport_unref (transport);
1878 check_read_watch (DBusTransport *transport)
1880 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1881 dbus_bool_t need_read_watch;
1883 _dbus_verbose ("fd = %d\n",socket_transport->fd);
1885 if (transport->connection == NULL)
1888 if (transport->disconnected)
1890 _dbus_assert (socket_transport->read_watch == NULL);
1894 _dbus_transport_ref (transport);
1896 #ifdef DBUS_AUTHENTICATION
1897 if (_dbus_transport_get_is_authenticated (transport))
1900 (_dbus_counter_get_size_value (transport->live_messages) < transport->max_live_messages_size) &&
1901 (_dbus_counter_get_unix_fd_value (transport->live_messages) < transport->max_live_messages_unix_fds);
1902 #ifdef DBUS_AUTHENTICATION
1905 if (transport->receive_credentials_pending)
1906 need_read_watch = TRUE;
1909 /* The reason to disable need_read_watch when not WAITING_FOR_INPUT
1910 * is to avoid spinning on the file descriptor when we're waiting
1911 * to write or for some other part of the auth process
1913 DBusAuthState auth_state;
1915 auth_state = _dbus_auth_do_work (transport->auth);
1917 /* If we need memory we install the read watch just in case,
1918 * if there's no need for it, it will get de-installed
1919 * next time we try reading. If we're authenticated we
1920 * install it since we normally have it installed while
1923 if (auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT ||
1924 auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY ||
1925 auth_state == DBUS_AUTH_STATE_AUTHENTICATED)
1926 need_read_watch = TRUE;
1928 need_read_watch = FALSE;
1933 _dbus_verbose (" setting read watch enabled = %d\n", need_read_watch);
1934 _dbus_connection_toggle_watch_unlocked (transport->connection,
1935 socket_transport->read_watch,
1938 _dbus_transport_unref (transport);
1942 do_io_error (DBusTransport *transport)
1944 _dbus_transport_ref (transport);
1945 _dbus_transport_disconnect (transport);
1946 _dbus_transport_unref (transport);
1949 #ifdef DBUS_AUTHENTICATION
1950 /* return value is whether we successfully read any new data. */
1952 read_data_into_auth (DBusTransport *transport,
1955 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1961 _dbus_auth_get_buffer (transport->auth, &buffer);
1963 bytes_read = kdbus_read_message(socket_transport, buffer);
1965 _dbus_auth_return_buffer (transport->auth, buffer,
1966 bytes_read > 0 ? bytes_read : 0);
1970 _dbus_verbose (" read %d bytes in auth phase\n", bytes_read);
1973 else if (bytes_read < 0)
1975 /* EINTR already handled for us */
1977 if (_dbus_get_is_errno_enomem ())
1981 else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1982 ; /* do nothing, just return FALSE below */
1985 _dbus_verbose ("Error reading from remote app: %s\n",
1986 _dbus_strerror_from_errno ());
1987 do_io_error (transport);
1994 _dbus_assert (bytes_read == 0);
1996 _dbus_verbose ("Disconnected from remote app\n");
1997 do_io_error (transport);
2003 /* Return value is whether we successfully wrote any bytes */
2005 write_data_from_auth (DBusTransport *transport)
2007 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2009 const DBusString *buffer;
2011 if (!_dbus_auth_get_bytes_to_send (transport->auth,
2015 bytes_written = _dbus_write_socket (socket_transport->fd,
2017 0, _dbus_string_get_length (buffer));
2019 if (bytes_written > 0)
2021 _dbus_auth_bytes_sent (transport->auth, bytes_written);
2024 else if (bytes_written < 0)
2026 /* EINTR already handled for us */
2028 if (_dbus_get_is_errno_eagain_or_ewouldblock ())
2032 _dbus_verbose ("Error writing to remote app: %s\n",
2033 _dbus_strerror_from_errno ());
2034 do_io_error (transport);
2043 exchange_credentials (DBusTransport *transport,
2044 dbus_bool_t do_reading,
2045 dbus_bool_t do_writing)
2047 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2048 DBusError error = DBUS_ERROR_INIT;
2050 _dbus_verbose ("exchange_credentials: do_reading = %d, do_writing = %d\n",
2051 do_reading, do_writing);
2053 if (do_writing && transport->send_credentials_pending)
2055 if (_dbus_send_credentials_socket (socket_transport->fd,
2058 transport->send_credentials_pending = FALSE;
2062 _dbus_verbose ("Failed to write credentials: %s\n", error.message);
2063 dbus_error_free (&error);
2064 do_io_error (transport);
2068 if (do_reading && transport->receive_credentials_pending)
2070 /* FIXME this can fail due to IO error _or_ OOM, broken
2071 * (somewhat tricky to fix since the OOM error can be set after
2072 * we already read the credentials byte, so basically we need to
2073 * separate reading the byte and storing it in the
2074 * transport->credentials). Does not really matter for now
2075 * because storing in credentials never actually fails on unix.
2077 if (_dbus_read_credentials_socket (socket_transport->fd,
2078 transport->credentials,
2081 transport->receive_credentials_pending = FALSE;
2085 _dbus_verbose ("Failed to read credentials %s\n", error.message);
2086 dbus_error_free (&error);
2087 do_io_error (transport);
2091 if (!(transport->send_credentials_pending ||
2092 transport->receive_credentials_pending))
2094 if (!_dbus_auth_set_credentials (transport->auth,
2095 transport->credentials))
2103 do_authentication (DBusTransport *transport,
2104 dbus_bool_t do_reading,
2105 dbus_bool_t do_writing,
2106 dbus_bool_t *auth_completed)
2109 dbus_bool_t orig_auth_state;
2113 orig_auth_state = _dbus_transport_get_is_authenticated (transport);
2115 /* This is essential to avoid the check_write_watch() at the end,
2116 * we don't want to add a write watch in do_iteration before
2117 * we try writing and get EAGAIN
2119 if (orig_auth_state)
2122 *auth_completed = FALSE;
2126 _dbus_transport_ref (transport);
2128 while (!_dbus_transport_get_is_authenticated (transport) &&
2129 _dbus_transport_get_is_connected (transport))
2131 if (!exchange_credentials (transport, do_reading, do_writing))
2137 if (transport->send_credentials_pending ||
2138 transport->receive_credentials_pending)
2140 _dbus_verbose ("send_credentials_pending = %d receive_credentials_pending = %d\n",
2141 transport->send_credentials_pending,
2142 transport->receive_credentials_pending);
2146 #define TRANSPORT_SIDE(t) ((t)->is_server ? "server" : "client")
2147 switch (_dbus_auth_do_work (transport->auth))
2149 case DBUS_AUTH_STATE_WAITING_FOR_INPUT:
2150 _dbus_verbose (" %s auth state: waiting for input\n",
2151 TRANSPORT_SIDE (transport));
2152 if (!do_reading || !read_data_into_auth (transport, &oom))
2156 case DBUS_AUTH_STATE_WAITING_FOR_MEMORY:
2157 _dbus_verbose (" %s auth state: waiting for memory\n",
2158 TRANSPORT_SIDE (transport));
2163 case DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND:
2164 _dbus_verbose (" %s auth state: bytes to send\n",
2165 TRANSPORT_SIDE (transport));
2166 if (!do_writing || !write_data_from_auth (transport))
2170 case DBUS_AUTH_STATE_NEED_DISCONNECT:
2171 _dbus_verbose (" %s auth state: need to disconnect\n",
2172 TRANSPORT_SIDE (transport));
2173 do_io_error (transport);
2176 case DBUS_AUTH_STATE_AUTHENTICATED:
2177 _dbus_verbose (" %s auth state: authenticated\n",
2178 TRANSPORT_SIDE (transport));
2185 *auth_completed = (orig_auth_state != _dbus_transport_get_is_authenticated (transport));
2187 check_read_watch (transport);
2188 check_write_watch (transport);
2189 _dbus_transport_unref (transport);
2198 /* returns false on oom */
2200 do_writing (DBusTransport *transport)
2202 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2205 #ifdef DBUS_AUTHENTICATION
2206 /* No messages without authentication! */
2207 if (!_dbus_transport_get_is_authenticated (transport))
2209 _dbus_verbose ("Not authenticated, not writing anything\n");
2214 if (transport->disconnected)
2216 _dbus_verbose ("Not connected, not writing anything\n");
2221 _dbus_verbose ("do_writing(), have_messages = %d, fd = %d\n",
2222 _dbus_connection_has_messages_to_send_unlocked (transport->connection),
2223 socket_transport->fd);
2228 while (!transport->disconnected && _dbus_connection_has_messages_to_send_unlocked (transport->connection))
2231 DBusMessage *message;
2232 const DBusString *header;
2233 const DBusString *body;
2234 int total_bytes_to_write;
2235 const char* pDestination;
2237 message = _dbus_connection_get_message_to_send (transport->connection);
2238 _dbus_assert (message != NULL);
2239 dbus_message_unlock(message);
2240 dbus_message_set_sender(message, socket_transport->sender);
2241 dbus_message_lock (message);
2242 _dbus_message_get_network_data (message, &header, &body);
2243 total_bytes_to_write = _dbus_string_get_length(header) + _dbus_string_get_length(body);
2244 pDestination = dbus_message_get_destination(message);
2248 if(!strcmp(pDestination, "org.freedesktop.DBus"))
2250 if(!strcmp(dbus_message_get_interface(message), DBUS_INTERFACE_DBUS))
2254 ret = emulateOrgFreedesktopDBus(transport, message);
2262 bytes_written = total_bytes_to_write;
2265 //else send to "daemon" as to normal recipient
2269 if (_dbus_auth_needs_encoding (transport->auth))
2271 if (_dbus_string_get_length (&socket_transport->encoded_outgoing) == 0)
2273 if (!_dbus_auth_encode_data (transport->auth,
2274 header, &socket_transport->encoded_outgoing))
2280 if (!_dbus_auth_encode_data (transport->auth,
2281 body, &socket_transport->encoded_outgoing))
2283 _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
2289 total_bytes_to_write = _dbus_string_get_length (&socket_transport->encoded_outgoing);
2290 if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration)
2293 bytes_written = kdbus_write_msg(socket_transport, message, TRUE);
2297 if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration)
2300 bytes_written = kdbus_write_msg(socket_transport, message, FALSE);
2304 if (bytes_written < 0)
2306 /* EINTR already handled for us */
2308 /* For some discussion of why we also ignore EPIPE here, see
2309 * http://lists.freedesktop.org/archives/dbus/2008-March/009526.html
2312 if (_dbus_get_is_errno_eagain_or_ewouldblock () || _dbus_get_is_errno_epipe ())
2316 _dbus_verbose ("Error writing to remote app: %s\n", _dbus_strerror_from_errno ());
2317 do_io_error (transport);
2323 _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
2324 total_bytes_to_write);
2326 socket_transport->message_bytes_written += bytes_written;
2328 _dbus_assert (socket_transport->message_bytes_written <=
2329 total_bytes_to_write);
2331 if (socket_transport->message_bytes_written == total_bytes_to_write)
2333 socket_transport->message_bytes_written = 0;
2334 _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
2335 _dbus_string_compact (&socket_transport->encoded_outgoing, 2048);
2337 _dbus_connection_message_sent_unlocked (transport->connection,
2349 /* returns false on out-of-memory */
2351 do_reading (DBusTransport *transport)
2353 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2356 dbus_bool_t oom = FALSE;
2359 _dbus_verbose ("fd = %d\n",socket_transport->fd);
2361 #ifdef DBUS_AUTHENTICATION
2362 /* No messages without authentication! */
2363 if (!_dbus_transport_get_is_authenticated (transport))
2369 /* See if we've exceeded max messages and need to disable reading */
2370 check_read_watch (transport);
2372 _dbus_assert (socket_transport->read_watch != NULL ||
2373 transport->disconnected);
2375 if (transport->disconnected)
2378 if (!dbus_watch_get_enabled (socket_transport->read_watch))
2381 if (!_dbus_message_loader_get_unix_fds(transport->loader, &fds, &n_fds))
2383 _dbus_verbose ("Out of memory reading file descriptors\n");
2387 _dbus_message_loader_get_buffer (transport->loader, &buffer);
2389 if (_dbus_auth_needs_decoding (transport->auth))
2391 bytes_read = kdbus_read_message(socket_transport, &socket_transport->encoded_incoming, fds, &n_fds);
2393 _dbus_assert (_dbus_string_get_length (&socket_transport->encoded_incoming) == bytes_read);
2397 if (!_dbus_auth_decode_data (transport->auth,
2398 &socket_transport->encoded_incoming,
2401 _dbus_verbose ("Out of memory decoding incoming data\n");
2402 _dbus_message_loader_return_buffer (transport->loader,
2404 _dbus_string_get_length (buffer));
2409 _dbus_string_set_length (&socket_transport->encoded_incoming, 0);
2410 _dbus_string_compact (&socket_transport->encoded_incoming, 2048);
2414 bytes_read = kdbus_read_message(socket_transport, buffer, fds, &n_fds);
2416 if (bytes_read >= 0 && n_fds > 0)
2417 _dbus_verbose("Read %i unix fds\n", n_fds);
2419 _dbus_message_loader_return_buffer (transport->loader,
2421 bytes_read < 0 ? 0 : bytes_read);
2422 _dbus_message_loader_return_unix_fds(transport->loader, fds, bytes_read < 0 ? 0 : n_fds);
2426 /* EINTR already handled for us */
2428 if (_dbus_get_is_errno_enomem ())
2430 _dbus_verbose ("Out of memory in read()/do_reading()\n");
2434 else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
2438 _dbus_verbose ("Error reading from remote app: %s\n",
2439 _dbus_strerror_from_errno ());
2440 do_io_error (transport);
2444 else if (bytes_read == 0)
2446 _dbus_verbose ("Disconnected from remote app\n");
2447 do_io_error (transport);
2452 _dbus_verbose (" read %d bytes\n", bytes_read);
2454 if (!_dbus_transport_queue_messages (transport))
2457 _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
2461 /* Try reading more data until we get EAGAIN and return, or
2462 * exceed max bytes per iteration. If in blocking mode of
2463 * course we'll block instead of returning.
2475 unix_error_with_read_to_come (DBusTransport *itransport,
2479 DBusTransportSocket *transport = (DBusTransportSocket *) itransport;
2481 if (!((flags & DBUS_WATCH_HANGUP) || (flags & DBUS_WATCH_ERROR)))
2484 /* If we have a read watch enabled ...
2485 we -might have data incoming ... => handle the HANGUP there */
2486 if (watch != transport->read_watch && _dbus_watch_get_enabled (transport->read_watch))
2493 socket_handle_watch (DBusTransport *transport,
2497 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2499 _dbus_assert (watch == socket_transport->read_watch ||
2500 watch == socket_transport->write_watch);
2501 _dbus_assert (watch != NULL);
2503 /* If we hit an error here on a write watch, don't disconnect the transport yet because data can
2504 * still be in the buffer and do_reading may need several iteration to read
2505 * it all (because of its max_bytes_read_per_iteration limit).
2507 if (!(flags & DBUS_WATCH_READABLE) && unix_error_with_read_to_come (transport, watch, flags))
2509 _dbus_verbose ("Hang up or error on watch\n");
2510 _dbus_transport_disconnect (transport);
2514 if (watch == socket_transport->read_watch &&
2515 (flags & DBUS_WATCH_READABLE))
2517 #ifdef DBUS_AUTHENTICATION
2518 dbus_bool_t auth_finished;
2521 _dbus_verbose ("handling read watch %p flags = %x\n",
2524 #ifdef DBUS_AUTHENTICATION
2525 if (!do_authentication (transport, TRUE, FALSE, &auth_finished))
2528 /* We don't want to do a read immediately following
2529 * a successful authentication. This is so we
2530 * have a chance to propagate the authentication
2531 * state further up. Specifically, we need to
2532 * process any pending data from the auth object.
2537 if (!do_reading (transport))
2539 _dbus_verbose ("no memory to read\n");
2542 #ifdef DBUS_AUTHENTICATION
2546 _dbus_verbose ("Not reading anything since we just completed the authentication\n");
2550 else if (watch == socket_transport->write_watch &&
2551 (flags & DBUS_WATCH_WRITABLE))
2554 _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n",
2555 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
2557 #ifdef DBUS_AUTHENTICATION
2558 if (!do_authentication (transport, FALSE, TRUE, NULL))
2561 if (!do_writing (transport))
2563 _dbus_verbose ("no memory to write\n");
2567 /* See if we still need the write watch */
2568 check_write_watch (transport);
2570 #ifdef DBUS_ENABLE_VERBOSE_MODE
2573 if (watch == socket_transport->read_watch)
2574 _dbus_verbose ("asked to handle read watch with non-read condition 0x%x\n",
2576 else if (watch == socket_transport->write_watch)
2577 _dbus_verbose ("asked to handle write watch with non-write condition 0x%x\n",
2580 _dbus_verbose ("asked to handle watch %p on fd %d that we don't recognize\n",
2581 watch, dbus_watch_get_socket (watch));
2583 #endif /* DBUS_ENABLE_VERBOSE_MODE */
2589 socket_disconnect (DBusTransport *transport)
2591 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2593 _dbus_verbose ("\n");
2595 free_watches (transport);
2597 _dbus_close_socket (socket_transport->fd, NULL);
2598 socket_transport->fd = -1;
2602 kdbus_connection_set (DBusTransport *transport)
2604 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2606 dbus_connection_set_is_authenticated(transport->connection); //todo remove when authentication will work
2608 _dbus_watch_set_handler (socket_transport->write_watch,
2609 _dbus_connection_handle_watch,
2610 transport->connection, NULL);
2612 _dbus_watch_set_handler (socket_transport->read_watch,
2613 _dbus_connection_handle_watch,
2614 transport->connection, NULL);
2616 if (!_dbus_connection_add_watch_unlocked (transport->connection,
2617 socket_transport->write_watch))
2620 if (!_dbus_connection_add_watch_unlocked (transport->connection,
2621 socket_transport->read_watch))
2623 _dbus_connection_remove_watch_unlocked (transport->connection,
2624 socket_transport->write_watch);
2628 check_read_watch (transport);
2629 check_write_watch (transport);
2635 * @todo We need to have a way to wake up the select sleep if
2636 * a new iteration request comes in with a flag (read/write) that
2637 * we're not currently serving. Otherwise a call that just reads
2638 * could block a write call forever (if there are no incoming
2642 kdbus_do_iteration (DBusTransport *transport,
2644 int timeout_milliseconds)
2646 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2651 _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p fd = %d\n",
2652 flags & DBUS_ITERATION_DO_READING ? "read" : "",
2653 flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
2654 timeout_milliseconds,
2655 socket_transport->read_watch,
2656 socket_transport->write_watch,
2657 socket_transport->fd);
2659 /* the passed in DO_READING/DO_WRITING flags indicate whether to
2660 * read/write messages, but regardless of those we may need to block
2661 * for reading/writing to do auth. But if we do reading for auth,
2662 * we don't want to read any messages yet if not given DO_READING.
2665 poll_fd.fd = socket_transport->fd;
2668 if (_dbus_transport_peek_is_authenticated (transport))
2670 /* This is kind of a hack; if we have stuff to write, then try
2671 * to avoid the poll. This is probably about a 5% speedup on an
2672 * echo client/server.
2674 * If both reading and writing were requested, we want to avoid this
2675 * since it could have funky effects:
2676 * - both ends spinning waiting for the other one to read
2677 * data so they can finish writing
2678 * - prioritizing all writing ahead of reading
2680 if ((flags & DBUS_ITERATION_DO_WRITING) &&
2681 !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) &&
2682 !transport->disconnected &&
2683 _dbus_connection_has_messages_to_send_unlocked (transport->connection))
2685 do_writing (transport);
2687 if (transport->disconnected ||
2688 !_dbus_connection_has_messages_to_send_unlocked (transport->connection))
2692 /* If we get here, we decided to do the poll() after all */
2693 _dbus_assert (socket_transport->read_watch);
2694 if (flags & DBUS_ITERATION_DO_READING)
2695 poll_fd.events |= _DBUS_POLLIN;
2697 _dbus_assert (socket_transport->write_watch);
2698 if (flags & DBUS_ITERATION_DO_WRITING)
2699 poll_fd.events |= _DBUS_POLLOUT;
2703 DBusAuthState auth_state;
2705 auth_state = _dbus_auth_do_work (transport->auth);
2707 if (transport->receive_credentials_pending || auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT)
2708 poll_fd.events |= _DBUS_POLLIN;
2710 if (transport->send_credentials_pending || auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND)
2711 poll_fd.events |= _DBUS_POLLOUT;
2716 if (flags & DBUS_ITERATION_BLOCK)
2717 poll_timeout = timeout_milliseconds;
2721 /* For blocking selects we drop the connection lock here
2722 * to avoid blocking out connection access during a potentially
2723 * indefinite blocking call. The io path is still protected
2724 * by the io_path_cond condvar, so we won't reenter this.
2726 if (flags & DBUS_ITERATION_BLOCK)
2728 _dbus_verbose ("unlock pre poll\n");
2729 _dbus_connection_unlock (transport->connection);
2733 poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
2735 if (poll_res < 0 && _dbus_get_is_errno_eintr ())
2737 _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
2741 if (flags & DBUS_ITERATION_BLOCK)
2743 _dbus_verbose ("lock post poll\n");
2744 _dbus_connection_lock (transport->connection);
2750 poll_fd.revents = 0; /* some concern that posix does not guarantee this;
2751 * valgrind flags it as an error. though it probably
2752 * is guaranteed on linux at least.
2755 if (poll_fd.revents & _DBUS_POLLERR)
2756 do_io_error (transport);
2759 dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
2760 dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0;
2761 #ifdef DBUS_AUTHENTICATION
2762 dbus_bool_t authentication_completed;
2765 _dbus_verbose ("in iteration, need_read=%d need_write=%d\n",
2766 need_read, need_write);
2767 #ifdef DBUS_AUTHENTICATION
2768 do_authentication (transport, need_read, need_write,
2769 &authentication_completed);
2771 /* See comment in socket_handle_watch. */
2772 if (authentication_completed)
2775 if (need_read && (flags & DBUS_ITERATION_DO_READING))
2776 do_reading (transport);
2777 if (need_write && (flags & DBUS_ITERATION_DO_WRITING))
2778 do_writing (transport);
2782 _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
2786 /* We need to install the write watch only if we did not
2787 * successfully write everything. Note we need to be careful that we
2788 * don't call check_write_watch *before* do_writing, since it's
2789 * inefficient to add the write watch, and we can avoid it most of
2790 * the time since we can write immediately.
2792 * However, we MUST always call check_write_watch(); DBusConnection code
2793 * relies on the fact that running an iteration will notice that
2794 * messages are pending.
2796 check_write_watch (transport);
2798 _dbus_verbose (" ... leaving do_iteration()\n");
2802 socket_live_messages_changed (DBusTransport *transport)
2804 /* See if we should look for incoming messages again */
2805 check_read_watch (transport);
2808 static const DBusTransportVTable kdbus_vtable = {
2810 socket_handle_watch,
2812 kdbus_connection_set,
2814 socket_live_messages_changed,
2815 socket_get_socket_fd
2819 * Creates a new transport for the given kdbus file descriptor. The file
2820 * descriptor must be nonblocking.
2822 * @param fd the file descriptor.
2823 * @param address the transport's address
2824 * @returns the new transport, or #NULL if no memory.
2826 static DBusTransport*
2827 _dbus_transport_new_for_socket_kdbus (int fd,
2828 const DBusString *address)
2830 DBusTransportSocket *socket_transport;
2832 socket_transport = dbus_new0 (DBusTransportSocket, 1);
2833 if (socket_transport == NULL)
2836 if (!_dbus_string_init (&socket_transport->encoded_outgoing))
2839 if (!_dbus_string_init (&socket_transport->encoded_incoming))
2842 socket_transport->write_watch = _dbus_watch_new (fd,
2843 DBUS_WATCH_WRITABLE,
2846 if (socket_transport->write_watch == NULL)
2849 socket_transport->read_watch = _dbus_watch_new (fd,
2850 DBUS_WATCH_READABLE,
2853 if (socket_transport->read_watch == NULL)
2856 if (!_dbus_transport_init_base (&socket_transport->base,
2861 #ifdef DBUS_AUTHENTICATION
2862 #ifdef HAVE_UNIX_FD_PASSING
2863 _dbus_auth_set_unix_fd_possible(socket_transport->base.auth, _dbus_socket_can_pass_unix_fd(fd));
2867 socket_transport->fd = fd;
2868 socket_transport->message_bytes_written = 0;
2870 /* These values should probably be tunable or something. */
2871 socket_transport->max_bytes_read_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2872 socket_transport->max_bytes_written_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2874 socket_transport->kdbus_mmap_ptr = NULL;
2875 socket_transport->memfd = -1;
2877 return (DBusTransport*) socket_transport;
2880 _dbus_watch_invalidate (socket_transport->read_watch);
2881 _dbus_watch_unref (socket_transport->read_watch);
2883 _dbus_watch_invalidate (socket_transport->write_watch);
2884 _dbus_watch_unref (socket_transport->write_watch);
2886 _dbus_string_free (&socket_transport->encoded_incoming);
2888 _dbus_string_free (&socket_transport->encoded_outgoing);
2890 dbus_free (socket_transport);
2896 * Opens a connection to the kdbus bus
2898 * This will set FD_CLOEXEC for the socket returned.
2900 * @param path the path to UNIX domain socket
2901 * @param error return location for error code
2902 * @returns connection file descriptor or -1 on error
2904 static int _dbus_connect_kdbus (const char *path, DBusError *error)
2908 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2909 _dbus_verbose ("connecting to kdbus bus %s\n", path);
2911 fd = open(path, O_RDWR|O_CLOEXEC|O_NONBLOCK);
2913 dbus_set_error(error, _dbus_error_from_errno (errno), "Failed to open file descriptor: %s", _dbus_strerror (errno));
2919 * Creates a new transport for kdbus.
2920 * This creates a client-side of a transport.
2922 * @param path the path to the bus.
2923 * @param error address where an error can be returned.
2924 * @returns a new transport, or #NULL on failure.
2926 static DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error)
2929 DBusTransport *transport;
2932 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2934 if (!_dbus_string_init (&address))
2936 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2942 if ((!_dbus_string_append (&address, "kdbus:path=")) || (!_dbus_string_append (&address, path)))
2944 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2948 fd = _dbus_connect_kdbus (path, error);
2951 _DBUS_ASSERT_ERROR_IS_SET (error);
2955 _dbus_verbose ("Successfully connected to kdbus bus %s\n", path);
2957 transport = _dbus_transport_new_for_socket_kdbus (fd, &address);
2958 if (transport == NULL)
2960 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2964 _dbus_string_free (&address);
2969 _dbus_close_socket (fd, NULL);
2971 _dbus_string_free (&address);
2977 * Opens kdbus transport if method from address entry is kdbus
2979 * @param entry the address entry to try opening
2980 * @param transport_p return location for the opened transport
2981 * @param error error to be set
2982 * @returns result of the attempt
2984 DBusTransportOpenResult _dbus_transport_open_kdbus(DBusAddressEntry *entry,
2985 DBusTransport **transport_p,
2990 method = dbus_address_entry_get_method (entry);
2991 _dbus_assert (method != NULL);
2993 if (strcmp (method, "kdbus") == 0)
2995 const char *path = dbus_address_entry_get_value (entry, "path");
2999 _dbus_set_bad_address (error, "kdbus", "path", NULL);
3000 return DBUS_TRANSPORT_OPEN_BAD_ADDRESS;
3003 *transport_p = _dbus_transport_new_for_kdbus (path, error);
3005 if (*transport_p == NULL)
3007 _DBUS_ASSERT_ERROR_IS_SET (error);
3008 return DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT;
3012 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3013 return DBUS_TRANSPORT_OPEN_OK;
3018 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3019 return DBUS_TRANSPORT_OPEN_NOT_HANDLED;