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 iter, sub;
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, &iter);
1155 if (!dbus_message_iter_open_container (&iter, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING_AS_STRING, &sub))
1157 dbus_message_unref(reply);
1160 for (pCmd_name = pCmd->names; (uint8_t *)(pCmd_name) < (uint8_t *)(pCmd) + pCmd->size; pCmd_name = KDBUS_PART_NEXT(pCmd_name))
1162 pName = pCmd_name->name;
1163 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &pName))
1165 dbus_message_unref(reply);
1170 if (!dbus_message_iter_close_container (&iter, &sub))
1172 dbus_message_unref (reply);
1176 if(add_message_to_received(reply, transport->connection))
1184 else if(!strcmp(dbus_message_get_member(message), "GetId"))
1187 char uuid[DBUS_UUID_LENGTH_BYTES];
1190 DBusString binary, encoded;
1192 path = &transport->address[11]; //start of kdbus bus path
1193 if(stat(path, &stats) < -1)
1195 _dbus_verbose("kdbus error reading stats of bus: err %d (%m)\n", errno);
1196 return reply_with_error(DBUS_ERROR_FAILED, "Could not determine bus '%s' uuid", path, message, transport->connection);
1200 MD5_Update(&md5, path, strlen(path));
1201 MD5_Update(&md5, &stats.st_ctim.tv_sec, sizeof(stats.st_ctim.tv_sec));
1202 MD5_Final(uuid, &md5);
1204 if(!_dbus_string_init (&encoded))
1206 _dbus_string_init_const_len (&binary, uuid, DBUS_UUID_LENGTH_BYTES);
1207 if(!_dbus_string_hex_encode (&binary, 0, &encoded, _dbus_string_get_length (&encoded)))
1209 path = (char*)_dbus_string_get_const_data (&encoded);
1210 ret_value = reply_1_data(message, DBUS_TYPE_STRING, &path, transport->connection);
1213 _dbus_string_free(&binary);
1214 _dbus_string_free(&encoded);
1218 else if(!strcmp(dbus_message_get_member(message), "GetAdtAuditSessionData"))
1222 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1223 return reply_with_error(DBUS_ERROR_ADT_AUDIT_DATA_UNKNOWN, "Could not determine audit session data for '%s'", name, message, transport->connection);
1225 else if(!strcmp(dbus_message_get_member(message), "GetConnectionSELinuxSecurityContext"))
1229 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
1230 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
1231 if(inter_ret == -ENOENT) //name has no owner
1232 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);
1233 else if(inter_ret < 0)
1234 return reply_with_error(DBUS_ERROR_SELINUX_SECURITY_CONTEXT_UNKNOWN, "Could not determine security context for '%s'", name, message, transport->connection);
1239 reply = dbus_message_new_method_return(message);
1242 dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
1243 if (!dbus_message_append_args (reply, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &info.sec_label, info.sec_label_len, DBUS_TYPE_INVALID))
1244 dbus_message_unref(reply);
1245 else if(add_message_to_received(reply, transport->connection))
1251 return 1; //send to daemon
1252 // return reply_with_error(DBUS_ERROR_UNKNOWN_METHOD, NULL, (char*)dbus_message_get_member(message), message, transport->connection);
1253 /* else if(!strcmp(dbus_message_get_member(message), "ListActivatableNames")) //todo
1257 else if(!strcmp(dbus_message_get_member(message), "StartServiceByName"))
1261 else if(!strcmp(dbus_message_get_member(message), "UpdateActivationEnvironment"))
1265 else if(!strcmp(dbus_message_get_member(message), "ReloadConfig"))
1272 free(info.sec_label);
1276 #if KDBUS_MSG_DECODE_DEBUG == 1
1277 static char *msg_id(uint64_t id, char *buf)
1283 sprintf(buf, "%llu", (unsigned long long)id);
1287 struct kdbus_enum_table {
1291 #define _STRINGIFY(x) #x
1292 #define STRINGIFY(x) _STRINGIFY(x)
1293 #define ELEMENTSOF(x) (sizeof(x)/sizeof((x)[0]))
1294 #define TABLE(what) static struct kdbus_enum_table kdbus_table_##what[]
1295 #define ENUM(_id) { .id=_id, .name=STRINGIFY(_id) }
1296 #define LOOKUP(what) \
1297 const char *enum_##what(long long id) { \
1299 for (i = 0; i < ELEMENTSOF(kdbus_table_##what); i++) \
1300 if (id == kdbus_table_##what[i].id) \
1301 return kdbus_table_##what[i].name; \
1304 const char *enum_MSG(long long id);
1306 ENUM(_KDBUS_MSG_NULL),
1307 ENUM(KDBUS_MSG_PAYLOAD_VEC),
1308 ENUM(KDBUS_MSG_PAYLOAD_OFF),
1309 ENUM(KDBUS_MSG_PAYLOAD_MEMFD),
1310 ENUM(KDBUS_MSG_FDS),
1311 ENUM(KDBUS_MSG_BLOOM),
1312 ENUM(KDBUS_MSG_DST_NAME),
1313 ENUM(KDBUS_MSG_SRC_CREDS),
1314 ENUM(KDBUS_MSG_SRC_PID_COMM),
1315 ENUM(KDBUS_MSG_SRC_TID_COMM),
1316 ENUM(KDBUS_MSG_SRC_EXE),
1317 ENUM(KDBUS_MSG_SRC_CMDLINE),
1318 ENUM(KDBUS_MSG_SRC_CGROUP),
1319 ENUM(KDBUS_MSG_SRC_CAPS),
1320 ENUM(KDBUS_MSG_SRC_SECLABEL),
1321 ENUM(KDBUS_MSG_SRC_AUDIT),
1322 ENUM(KDBUS_MSG_SRC_NAMES),
1323 ENUM(KDBUS_MSG_TIMESTAMP),
1324 ENUM(KDBUS_MSG_NAME_ADD),
1325 ENUM(KDBUS_MSG_NAME_REMOVE),
1326 ENUM(KDBUS_MSG_NAME_CHANGE),
1327 ENUM(KDBUS_MSG_ID_ADD),
1328 ENUM(KDBUS_MSG_ID_REMOVE),
1329 ENUM(KDBUS_MSG_REPLY_TIMEOUT),
1330 ENUM(KDBUS_MSG_REPLY_DEAD),
1333 const char *enum_PAYLOAD(long long id);
1335 ENUM(KDBUS_PAYLOAD_KERNEL),
1336 ENUM(KDBUS_PAYLOAD_DBUS1),
1337 ENUM(KDBUS_PAYLOAD_GVARIANT),
1342 * Puts locally generated message into received data buffer.
1343 * Use only during receiving phase!
1345 * @param message message to load
1346 * @param data place to load message
1347 * @return size of message
1349 static int put_message_into_data(DBusMessage *message, char* data)
1352 const DBusString *header;
1353 const DBusString *body;
1356 dbus_message_set_serial(message, 1);
1357 dbus_message_lock (message);
1358 _dbus_message_get_network_data (message, &header, &body);
1359 ret_size = _dbus_string_get_length(header);
1360 memcpy(data, _dbus_string_get_const_data(header), ret_size);
1362 size = _dbus_string_get_length(body);
1363 memcpy(data, _dbus_string_get_const_data(body), size);
1369 * Decodes kdbus message in order to extract dbus message and put it into data and fds.
1370 * Also captures and decodes kdbus error messages and kdbus kernel broadcasts and converts
1371 * all of them into dbus messages.
1373 * @param msg kdbus message
1374 * @param data place to copy dbus message to
1375 * @param socket_transport transport
1376 * @param fds place to store file descriptors received
1377 * @param n_fds place to store quantity of file descriptor
1378 * @return number of dbus message's bytes received or -1 on error
1380 static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTransportSocket* socket_transport, int* fds, int* n_fds)
1382 const struct kdbus_item *item;
1384 DBusMessage *message = NULL;
1385 DBusMessageIter args;
1386 const char* emptyString = "";
1387 const char* pString = NULL;
1388 char dbus_name[(unsigned int)(snprintf((char*)pString, 0, "%llu", ULLONG_MAX) + sizeof(":1."))];
1389 const char* pDBusName = dbus_name;
1390 #if KDBUS_MSG_DECODE_DEBUG == 1
1394 #if KDBUS_MSG_DECODE_DEBUG == 1
1395 _dbus_verbose("MESSAGE: %s (%llu bytes) flags=0x%llx, %s → %s, cookie=%llu, timeout=%llu\n",
1396 enum_PAYLOAD(msg->payload_type), (unsigned long long) msg->size,
1397 (unsigned long long) msg->flags,
1398 msg_id(msg->src_id, buf), msg_id(msg->dst_id, buf),
1399 (unsigned long long) msg->cookie, (unsigned long long) msg->timeout_ns);
1404 KDBUS_PART_FOREACH(item, msg, items)
1406 if (item->size <= KDBUS_PART_HEADER_SIZE)
1408 _dbus_verbose(" +%s (%llu bytes) invalid data record\n", enum_MSG(item->type), item->size);
1409 break; //??? continue (because dbus will find error) or break
1414 case KDBUS_MSG_PAYLOAD_OFF:
1415 memcpy(data, (char *)socket_transport->kdbus_mmap_ptr + item->vec.offset, item->vec.size);
1416 data += item->vec.size;
1417 ret_size += item->vec.size;
1419 _dbus_verbose(" +%s (%llu bytes) off=%llu size=%llu\n",
1420 enum_MSG(item->type), item->size,
1421 (unsigned long long)item->vec.offset,
1422 (unsigned long long)item->vec.size);
1425 case KDBUS_MSG_PAYLOAD_MEMFD:
1430 size = item->memfd.size;
1431 _dbus_verbose("memfd.size : %llu\n", (unsigned long long)size);
1433 buf = mmap(NULL, size, PROT_READ , MAP_SHARED, item->memfd.fd, 0);
1434 if (buf == MAP_FAILED)
1436 _dbus_verbose("mmap() fd=%i failed:%m", item->memfd.fd);
1440 memcpy(data, buf, size);
1446 _dbus_verbose(" +%s (%llu bytes) off=%llu size=%llu\n",
1447 enum_MSG(item->type), item->size,
1448 (unsigned long long)item->vec.offset,
1449 (unsigned long long)item->vec.size);
1457 *n_fds = (item->size - KDBUS_PART_HEADER_SIZE) / sizeof(int);
1458 memcpy(fds, item->fds, *n_fds * sizeof(int));
1459 for (i = 0; i < *n_fds; i++)
1460 _dbus_fd_set_close_on_exec(fds[i]);
1464 #if KDBUS_MSG_DECODE_DEBUG == 1
1465 case KDBUS_MSG_SRC_CREDS:
1466 _dbus_verbose(" +%s (%llu bytes) uid=%lld, gid=%lld, pid=%lld, tid=%lld, starttime=%lld\n",
1467 enum_MSG(item->type), item->size,
1468 item->creds.uid, item->creds.gid,
1469 item->creds.pid, item->creds.tid,
1470 item->creds.starttime);
1473 case KDBUS_MSG_SRC_PID_COMM:
1474 case KDBUS_MSG_SRC_TID_COMM:
1475 case KDBUS_MSG_SRC_EXE:
1476 case KDBUS_MSG_SRC_CGROUP:
1477 case KDBUS_MSG_SRC_SECLABEL:
1478 case KDBUS_MSG_DST_NAME:
1479 _dbus_verbose(" +%s (%llu bytes) '%s' (%zu)\n",
1480 enum_MSG(item->type), item->size, item->str, strlen(item->str));
1483 case KDBUS_MSG_SRC_CMDLINE:
1484 case KDBUS_MSG_SRC_NAMES: {
1485 __u64 size = item->size - KDBUS_PART_HEADER_SIZE;
1486 const char *str = item->str;
1489 _dbus_verbose(" +%s (%llu bytes) ", enum_MSG(item->type), item->size);
1491 _dbus_verbose("'%s' ", str);
1492 size -= strlen(str) + 1;
1493 str += strlen(str) + 1;
1497 _dbus_verbose("(%d string%s)\n", count, (count == 1) ? "" : "s");
1501 case KDBUS_MSG_SRC_AUDIT:
1502 _dbus_verbose(" +%s (%llu bytes) loginuid=%llu sessionid=%llu\n",
1503 enum_MSG(item->type), item->size,
1504 (unsigned long long)item->data64[0],
1505 (unsigned long long)item->data64[1]);
1508 case KDBUS_MSG_SRC_CAPS: {
1510 const uint32_t *cap;
1513 _dbus_verbose(" +%s (%llu bytes) len=%llu bytes)\n",
1514 enum_MSG(item->type), item->size,
1515 (unsigned long long)item->size - KDBUS_PART_HEADER_SIZE);
1518 n = (item->size - KDBUS_PART_HEADER_SIZE) / 4 / sizeof(uint32_t);
1520 _dbus_verbose(" CapInh=");
1521 for (i = 0; i < n; i++)
1522 _dbus_verbose("%08x", cap[(0 * n) + (n - i - 1)]);
1524 _dbus_verbose(" CapPrm=");
1525 for (i = 0; i < n; i++)
1526 _dbus_verbose("%08x", cap[(1 * n) + (n - i - 1)]);
1528 _dbus_verbose(" CapEff=");
1529 for (i = 0; i < n; i++)
1530 _dbus_verbose("%08x", cap[(2 * n) + (n - i - 1)]);
1532 _dbus_verbose(" CapInh=");
1533 for (i = 0; i < n; i++)
1534 _dbus_verbose("%08x", cap[(3 * n) + (n - i - 1)]);
1535 _dbus_verbose("\n");
1539 case KDBUS_MSG_TIMESTAMP:
1540 _dbus_verbose(" +%s (%llu bytes) realtime=%lluns monotonic=%lluns\n",
1541 enum_MSG(item->type), item->size,
1542 (unsigned long long)item->timestamp.realtime_ns,
1543 (unsigned long long)item->timestamp.monotonic_ns);
1547 case KDBUS_MSG_REPLY_TIMEOUT:
1548 _dbus_verbose(" +%s (%llu bytes) cookie=%llu\n",
1549 enum_MSG(item->type), item->size, msg->cookie_reply);
1551 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NO_REPLY, NULL);
1558 ret_size = put_message_into_data(message, data);
1561 case KDBUS_MSG_REPLY_DEAD:
1562 _dbus_verbose(" +%s (%llu bytes) cookie=%llu\n",
1563 enum_MSG(item->type), item->size, msg->cookie_reply);
1565 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NAME_HAS_NO_OWNER, NULL);
1572 ret_size = put_message_into_data(message, data);
1575 case KDBUS_MSG_NAME_ADD:
1576 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1577 enum_MSG(item->type), (unsigned long long) item->size,
1578 item->name_change.name, item->name_change.old_id,
1579 item->name_change.new_id, item->name_change.flags);
1581 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1588 sprintf(dbus_name,":1.%llu",item->name_change.new_id);
1589 pString = item->name_change.name;
1590 _dbus_verbose ("Name added: %s\n", pString);
1591 dbus_message_iter_init_append(message, &args);
1592 ITER_APPEND_STR(pString)
1593 ITER_APPEND_STR(emptyString)
1594 ITER_APPEND_STR(pDBusName)
1595 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1597 ret_size = put_message_into_data(message, data);
1600 case KDBUS_MSG_NAME_REMOVE:
1601 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1602 enum_MSG(item->type), (unsigned long long) item->size,
1603 item->name_change.name, item->name_change.old_id,
1604 item->name_change.new_id, item->name_change.flags);
1606 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged"); // name of the signal
1613 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
1614 pString = item->name_change.name;
1615 _dbus_verbose ("Name removed: %s\n", pString);
1616 dbus_message_iter_init_append(message, &args);
1617 ITER_APPEND_STR(pString)
1618 ITER_APPEND_STR(pDBusName)
1619 ITER_APPEND_STR(emptyString)
1620 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1622 ret_size = put_message_into_data(message, data);
1625 case KDBUS_MSG_NAME_CHANGE:
1626 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1627 enum_MSG(item->type), (unsigned long long) item->size,
1628 item->name_change.name, item->name_change.old_id,
1629 item->name_change.new_id, item->name_change.flags);
1631 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1638 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
1639 pString = item->name_change.name;
1640 _dbus_verbose ("Name changed: %s\n", pString);
1641 dbus_message_iter_init_append(message, &args);
1642 ITER_APPEND_STR(pString)
1643 ITER_APPEND_STR(pDBusName)
1644 sprintf(&dbus_name[3],"%llu",item->name_change.new_id);
1645 _dbus_verbose ("New id: %s\n", pDBusName);
1646 ITER_APPEND_STR(pDBusName)
1647 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1649 ret_size = put_message_into_data(message, data);
1652 case KDBUS_MSG_ID_ADD:
1653 _dbus_verbose(" +%s (%llu bytes) id=%llu flags=%llu\n",
1654 enum_MSG(item->type), (unsigned long long) item->size,
1655 (unsigned long long) item->id_change.id,
1656 (unsigned long long) item->id_change.flags);
1658 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1665 sprintf(dbus_name,":1.%llu",item->id_change.id);
1666 dbus_message_iter_init_append(message, &args);
1667 ITER_APPEND_STR(pDBusName)
1668 ITER_APPEND_STR(emptyString)
1669 ITER_APPEND_STR(pDBusName)
1670 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1672 ret_size = put_message_into_data(message, data);
1675 case KDBUS_MSG_ID_REMOVE:
1676 _dbus_verbose(" +%s (%llu bytes) id=%llu flags=%llu\n",
1677 enum_MSG(item->type), (unsigned long long) item->size,
1678 (unsigned long long) item->id_change.id,
1679 (unsigned long long) item->id_change.flags);
1681 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1688 sprintf(dbus_name,":1.%llu",item->id_change.id);
1689 dbus_message_iter_init_append(message, &args);
1690 ITER_APPEND_STR(pDBusName)
1691 ITER_APPEND_STR(pDBusName)
1692 ITER_APPEND_STR(emptyString)
1693 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1695 ret_size = put_message_into_data(message, data);
1697 #if KDBUS_MSG_DECODE_DEBUG == 1
1699 _dbus_verbose(" +%s (%llu bytes)\n", enum_MSG(item->type), item->size);
1705 #if KDBUS_MSG_DECODE_DEBUG == 1
1707 if ((char *)item - ((char *)msg + msg->size) >= 8)
1708 _dbus_verbose("invalid padding at end of message\n");
1713 dbus_message_unref(message);
1718 * Reads message from kdbus and puts it into dbus buffer and fds
1720 * @param transport transport
1721 * @param buffer place to copy received message to
1722 * @param fds place to store file descriptors sent in the message
1723 * @param n_fds place to store number of file descriptors
1724 * @return size of received message on success, -1 on error
1726 static int kdbus_read_message(DBusTransportSocket *socket_transport, DBusString *buffer, int* fds, int* n_fds)
1729 uint64_t __attribute__ ((__aligned__(8))) offset;
1730 struct kdbus_msg *msg;
1734 start = _dbus_string_get_length (buffer);
1735 if (!_dbus_string_lengthen (buffer, socket_transport->max_bytes_read_per_iteration))
1740 data = _dbus_string_get_data_len (buffer, start, socket_transport->max_bytes_read_per_iteration);
1743 if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RECV, &offset) < 0)
1747 _dbus_verbose("kdbus error receiving message: %d (%m)\n", errno);
1748 _dbus_string_set_length (buffer, start);
1752 msg = (struct kdbus_msg *)((char*)socket_transport->kdbus_mmap_ptr + offset);
1754 ret_size = kdbus_decode_msg(msg, data, socket_transport, fds, n_fds);
1756 if(ret_size == -1) /* error */
1758 _dbus_string_set_length (buffer, start);
1762 _dbus_string_set_length (buffer, start + ret_size);
1766 if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RELEASE, &offset) < 0)
1770 _dbus_verbose("kdbus error freeing message: %d (%m)\n", errno);
1778 free_watches (DBusTransport *transport)
1780 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1782 _dbus_verbose ("start\n");
1784 if (socket_transport->read_watch)
1786 if (transport->connection)
1787 _dbus_connection_remove_watch_unlocked (transport->connection,
1788 socket_transport->read_watch);
1789 _dbus_watch_invalidate (socket_transport->read_watch);
1790 _dbus_watch_unref (socket_transport->read_watch);
1791 socket_transport->read_watch = NULL;
1794 if (socket_transport->write_watch)
1796 if (transport->connection)
1797 _dbus_connection_remove_watch_unlocked (transport->connection,
1798 socket_transport->write_watch);
1799 _dbus_watch_invalidate (socket_transport->write_watch);
1800 _dbus_watch_unref (socket_transport->write_watch);
1801 socket_transport->write_watch = NULL;
1804 _dbus_verbose ("end\n");
1808 socket_finalize (DBusTransport *transport)
1810 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1812 _dbus_verbose ("\n");
1814 free_watches (transport);
1816 _dbus_string_free (&socket_transport->encoded_outgoing);
1817 _dbus_string_free (&socket_transport->encoded_incoming);
1819 _dbus_transport_finalize_base (transport);
1821 _dbus_assert (socket_transport->read_watch == NULL);
1822 _dbus_assert (socket_transport->write_watch == NULL);
1824 dbus_free (transport);
1828 check_write_watch (DBusTransport *transport)
1830 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1833 if (transport->connection == NULL)
1836 if (transport->disconnected)
1838 _dbus_assert (socket_transport->write_watch == NULL);
1842 _dbus_transport_ref (transport);
1844 #ifdef DBUS_AUTHENTICATION
1845 if (_dbus_transport_get_is_authenticated (transport))
1847 needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection);
1848 #ifdef DBUS_AUTHENTICATION
1851 if (transport->send_credentials_pending)
1855 DBusAuthState auth_state;
1857 auth_state = _dbus_auth_do_work (transport->auth);
1859 /* If we need memory we install the write watch just in case,
1860 * if there's no need for it, it will get de-installed
1861 * next time we try reading.
1863 if (auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND ||
1864 auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY)
1871 _dbus_verbose ("check_write_watch(): needed = %d on connection %p watch %p fd = %d outgoing messages exist %d\n",
1872 needed, transport->connection, socket_transport->write_watch,
1873 socket_transport->fd,
1874 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1876 _dbus_connection_toggle_watch_unlocked (transport->connection,
1877 socket_transport->write_watch,
1880 _dbus_transport_unref (transport);
1884 check_read_watch (DBusTransport *transport)
1886 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1887 dbus_bool_t need_read_watch;
1889 _dbus_verbose ("fd = %d\n",socket_transport->fd);
1891 if (transport->connection == NULL)
1894 if (transport->disconnected)
1896 _dbus_assert (socket_transport->read_watch == NULL);
1900 _dbus_transport_ref (transport);
1902 #ifdef DBUS_AUTHENTICATION
1903 if (_dbus_transport_get_is_authenticated (transport))
1906 (_dbus_counter_get_size_value (transport->live_messages) < transport->max_live_messages_size) &&
1907 (_dbus_counter_get_unix_fd_value (transport->live_messages) < transport->max_live_messages_unix_fds);
1908 #ifdef DBUS_AUTHENTICATION
1911 if (transport->receive_credentials_pending)
1912 need_read_watch = TRUE;
1915 /* The reason to disable need_read_watch when not WAITING_FOR_INPUT
1916 * is to avoid spinning on the file descriptor when we're waiting
1917 * to write or for some other part of the auth process
1919 DBusAuthState auth_state;
1921 auth_state = _dbus_auth_do_work (transport->auth);
1923 /* If we need memory we install the read watch just in case,
1924 * if there's no need for it, it will get de-installed
1925 * next time we try reading. If we're authenticated we
1926 * install it since we normally have it installed while
1929 if (auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT ||
1930 auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY ||
1931 auth_state == DBUS_AUTH_STATE_AUTHENTICATED)
1932 need_read_watch = TRUE;
1934 need_read_watch = FALSE;
1939 _dbus_verbose (" setting read watch enabled = %d\n", need_read_watch);
1940 _dbus_connection_toggle_watch_unlocked (transport->connection,
1941 socket_transport->read_watch,
1944 _dbus_transport_unref (transport);
1948 do_io_error (DBusTransport *transport)
1950 _dbus_transport_ref (transport);
1951 _dbus_transport_disconnect (transport);
1952 _dbus_transport_unref (transport);
1955 #ifdef DBUS_AUTHENTICATION
1956 /* return value is whether we successfully read any new data. */
1958 read_data_into_auth (DBusTransport *transport,
1961 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1967 _dbus_auth_get_buffer (transport->auth, &buffer);
1969 bytes_read = kdbus_read_message(socket_transport, buffer);
1971 _dbus_auth_return_buffer (transport->auth, buffer,
1972 bytes_read > 0 ? bytes_read : 0);
1976 _dbus_verbose (" read %d bytes in auth phase\n", bytes_read);
1979 else if (bytes_read < 0)
1981 /* EINTR already handled for us */
1983 if (_dbus_get_is_errno_enomem ())
1987 else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1988 ; /* do nothing, just return FALSE below */
1991 _dbus_verbose ("Error reading from remote app: %s\n",
1992 _dbus_strerror_from_errno ());
1993 do_io_error (transport);
2000 _dbus_assert (bytes_read == 0);
2002 _dbus_verbose ("Disconnected from remote app\n");
2003 do_io_error (transport);
2009 /* Return value is whether we successfully wrote any bytes */
2011 write_data_from_auth (DBusTransport *transport)
2013 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2015 const DBusString *buffer;
2017 if (!_dbus_auth_get_bytes_to_send (transport->auth,
2021 bytes_written = _dbus_write_socket (socket_transport->fd,
2023 0, _dbus_string_get_length (buffer));
2025 if (bytes_written > 0)
2027 _dbus_auth_bytes_sent (transport->auth, bytes_written);
2030 else if (bytes_written < 0)
2032 /* EINTR already handled for us */
2034 if (_dbus_get_is_errno_eagain_or_ewouldblock ())
2038 _dbus_verbose ("Error writing to remote app: %s\n",
2039 _dbus_strerror_from_errno ());
2040 do_io_error (transport);
2049 exchange_credentials (DBusTransport *transport,
2050 dbus_bool_t do_reading,
2051 dbus_bool_t do_writing)
2053 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2054 DBusError error = DBUS_ERROR_INIT;
2056 _dbus_verbose ("exchange_credentials: do_reading = %d, do_writing = %d\n",
2057 do_reading, do_writing);
2059 if (do_writing && transport->send_credentials_pending)
2061 if (_dbus_send_credentials_socket (socket_transport->fd,
2064 transport->send_credentials_pending = FALSE;
2068 _dbus_verbose ("Failed to write credentials: %s\n", error.message);
2069 dbus_error_free (&error);
2070 do_io_error (transport);
2074 if (do_reading && transport->receive_credentials_pending)
2076 /* FIXME this can fail due to IO error _or_ OOM, broken
2077 * (somewhat tricky to fix since the OOM error can be set after
2078 * we already read the credentials byte, so basically we need to
2079 * separate reading the byte and storing it in the
2080 * transport->credentials). Does not really matter for now
2081 * because storing in credentials never actually fails on unix.
2083 if (_dbus_read_credentials_socket (socket_transport->fd,
2084 transport->credentials,
2087 transport->receive_credentials_pending = FALSE;
2091 _dbus_verbose ("Failed to read credentials %s\n", error.message);
2092 dbus_error_free (&error);
2093 do_io_error (transport);
2097 if (!(transport->send_credentials_pending ||
2098 transport->receive_credentials_pending))
2100 if (!_dbus_auth_set_credentials (transport->auth,
2101 transport->credentials))
2109 do_authentication (DBusTransport *transport,
2110 dbus_bool_t do_reading,
2111 dbus_bool_t do_writing,
2112 dbus_bool_t *auth_completed)
2115 dbus_bool_t orig_auth_state;
2119 orig_auth_state = _dbus_transport_get_is_authenticated (transport);
2121 /* This is essential to avoid the check_write_watch() at the end,
2122 * we don't want to add a write watch in do_iteration before
2123 * we try writing and get EAGAIN
2125 if (orig_auth_state)
2128 *auth_completed = FALSE;
2132 _dbus_transport_ref (transport);
2134 while (!_dbus_transport_get_is_authenticated (transport) &&
2135 _dbus_transport_get_is_connected (transport))
2137 if (!exchange_credentials (transport, do_reading, do_writing))
2143 if (transport->send_credentials_pending ||
2144 transport->receive_credentials_pending)
2146 _dbus_verbose ("send_credentials_pending = %d receive_credentials_pending = %d\n",
2147 transport->send_credentials_pending,
2148 transport->receive_credentials_pending);
2152 #define TRANSPORT_SIDE(t) ((t)->is_server ? "server" : "client")
2153 switch (_dbus_auth_do_work (transport->auth))
2155 case DBUS_AUTH_STATE_WAITING_FOR_INPUT:
2156 _dbus_verbose (" %s auth state: waiting for input\n",
2157 TRANSPORT_SIDE (transport));
2158 if (!do_reading || !read_data_into_auth (transport, &oom))
2162 case DBUS_AUTH_STATE_WAITING_FOR_MEMORY:
2163 _dbus_verbose (" %s auth state: waiting for memory\n",
2164 TRANSPORT_SIDE (transport));
2169 case DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND:
2170 _dbus_verbose (" %s auth state: bytes to send\n",
2171 TRANSPORT_SIDE (transport));
2172 if (!do_writing || !write_data_from_auth (transport))
2176 case DBUS_AUTH_STATE_NEED_DISCONNECT:
2177 _dbus_verbose (" %s auth state: need to disconnect\n",
2178 TRANSPORT_SIDE (transport));
2179 do_io_error (transport);
2182 case DBUS_AUTH_STATE_AUTHENTICATED:
2183 _dbus_verbose (" %s auth state: authenticated\n",
2184 TRANSPORT_SIDE (transport));
2191 *auth_completed = (orig_auth_state != _dbus_transport_get_is_authenticated (transport));
2193 check_read_watch (transport);
2194 check_write_watch (transport);
2195 _dbus_transport_unref (transport);
2204 /* returns false on oom */
2206 do_writing (DBusTransport *transport)
2208 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2211 #ifdef DBUS_AUTHENTICATION
2212 /* No messages without authentication! */
2213 if (!_dbus_transport_get_is_authenticated (transport))
2215 _dbus_verbose ("Not authenticated, not writing anything\n");
2220 if (transport->disconnected)
2222 _dbus_verbose ("Not connected, not writing anything\n");
2227 _dbus_verbose ("do_writing(), have_messages = %d, fd = %d\n",
2228 _dbus_connection_has_messages_to_send_unlocked (transport->connection),
2229 socket_transport->fd);
2234 while (!transport->disconnected && _dbus_connection_has_messages_to_send_unlocked (transport->connection))
2237 DBusMessage *message;
2238 const DBusString *header;
2239 const DBusString *body;
2240 int total_bytes_to_write;
2241 const char* pDestination;
2243 message = _dbus_connection_get_message_to_send (transport->connection);
2244 _dbus_assert (message != NULL);
2245 dbus_message_unlock(message);
2246 dbus_message_set_sender(message, socket_transport->sender);
2247 dbus_message_lock (message);
2248 _dbus_message_get_network_data (message, &header, &body);
2249 total_bytes_to_write = _dbus_string_get_length(header) + _dbus_string_get_length(body);
2250 pDestination = dbus_message_get_destination(message);
2254 if(!strcmp(pDestination, "org.freedesktop.DBus"))
2256 if(!strcmp(dbus_message_get_interface(message), DBUS_INTERFACE_DBUS))
2260 ret = emulateOrgFreedesktopDBus(transport, message);
2268 bytes_written = total_bytes_to_write;
2271 //else send to "daemon" as to normal recipient
2275 if (_dbus_auth_needs_encoding (transport->auth))
2277 if (_dbus_string_get_length (&socket_transport->encoded_outgoing) == 0)
2279 if (!_dbus_auth_encode_data (transport->auth,
2280 header, &socket_transport->encoded_outgoing))
2286 if (!_dbus_auth_encode_data (transport->auth,
2287 body, &socket_transport->encoded_outgoing))
2289 _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
2295 total_bytes_to_write = _dbus_string_get_length (&socket_transport->encoded_outgoing);
2296 if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration)
2299 bytes_written = kdbus_write_msg(socket_transport, message, TRUE);
2303 if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration)
2306 bytes_written = kdbus_write_msg(socket_transport, message, FALSE);
2310 if (bytes_written < 0)
2312 /* EINTR already handled for us */
2314 /* For some discussion of why we also ignore EPIPE here, see
2315 * http://lists.freedesktop.org/archives/dbus/2008-March/009526.html
2318 if (_dbus_get_is_errno_eagain_or_ewouldblock () || _dbus_get_is_errno_epipe ())
2322 _dbus_verbose ("Error writing to remote app: %s\n", _dbus_strerror_from_errno ());
2323 do_io_error (transport);
2329 _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
2330 total_bytes_to_write);
2332 socket_transport->message_bytes_written += bytes_written;
2334 _dbus_assert (socket_transport->message_bytes_written <=
2335 total_bytes_to_write);
2337 if (socket_transport->message_bytes_written == total_bytes_to_write)
2339 socket_transport->message_bytes_written = 0;
2340 _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
2341 _dbus_string_compact (&socket_transport->encoded_outgoing, 2048);
2343 _dbus_connection_message_sent_unlocked (transport->connection,
2355 /* returns false on out-of-memory */
2357 do_reading (DBusTransport *transport)
2359 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2362 dbus_bool_t oom = FALSE;
2365 _dbus_verbose ("fd = %d\n",socket_transport->fd);
2367 #ifdef DBUS_AUTHENTICATION
2368 /* No messages without authentication! */
2369 if (!_dbus_transport_get_is_authenticated (transport))
2375 /* See if we've exceeded max messages and need to disable reading */
2376 check_read_watch (transport);
2378 _dbus_assert (socket_transport->read_watch != NULL ||
2379 transport->disconnected);
2381 if (transport->disconnected)
2384 if (!dbus_watch_get_enabled (socket_transport->read_watch))
2387 if (!_dbus_message_loader_get_unix_fds(transport->loader, &fds, &n_fds))
2389 _dbus_verbose ("Out of memory reading file descriptors\n");
2393 _dbus_message_loader_get_buffer (transport->loader, &buffer);
2395 if (_dbus_auth_needs_decoding (transport->auth))
2397 bytes_read = kdbus_read_message(socket_transport, &socket_transport->encoded_incoming, fds, &n_fds);
2399 _dbus_assert (_dbus_string_get_length (&socket_transport->encoded_incoming) == bytes_read);
2403 if (!_dbus_auth_decode_data (transport->auth,
2404 &socket_transport->encoded_incoming,
2407 _dbus_verbose ("Out of memory decoding incoming data\n");
2408 _dbus_message_loader_return_buffer (transport->loader,
2410 _dbus_string_get_length (buffer));
2415 _dbus_string_set_length (&socket_transport->encoded_incoming, 0);
2416 _dbus_string_compact (&socket_transport->encoded_incoming, 2048);
2420 bytes_read = kdbus_read_message(socket_transport, buffer, fds, &n_fds);
2422 if (bytes_read >= 0 && n_fds > 0)
2423 _dbus_verbose("Read %i unix fds\n", n_fds);
2425 _dbus_message_loader_return_buffer (transport->loader,
2427 bytes_read < 0 ? 0 : bytes_read);
2428 _dbus_message_loader_return_unix_fds(transport->loader, fds, bytes_read < 0 ? 0 : n_fds);
2432 /* EINTR already handled for us */
2434 if (_dbus_get_is_errno_enomem ())
2436 _dbus_verbose ("Out of memory in read()/do_reading()\n");
2440 else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
2444 _dbus_verbose ("Error reading from remote app: %s\n",
2445 _dbus_strerror_from_errno ());
2446 do_io_error (transport);
2450 else if (bytes_read == 0)
2452 _dbus_verbose ("Disconnected from remote app\n");
2453 do_io_error (transport);
2458 _dbus_verbose (" read %d bytes\n", bytes_read);
2460 if (!_dbus_transport_queue_messages (transport))
2463 _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
2467 /* Try reading more data until we get EAGAIN and return, or
2468 * exceed max bytes per iteration. If in blocking mode of
2469 * course we'll block instead of returning.
2481 unix_error_with_read_to_come (DBusTransport *itransport,
2485 DBusTransportSocket *transport = (DBusTransportSocket *) itransport;
2487 if (!((flags & DBUS_WATCH_HANGUP) || (flags & DBUS_WATCH_ERROR)))
2490 /* If we have a read watch enabled ...
2491 we -might have data incoming ... => handle the HANGUP there */
2492 if (watch != transport->read_watch && _dbus_watch_get_enabled (transport->read_watch))
2499 socket_handle_watch (DBusTransport *transport,
2503 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2505 _dbus_assert (watch == socket_transport->read_watch ||
2506 watch == socket_transport->write_watch);
2507 _dbus_assert (watch != NULL);
2509 /* If we hit an error here on a write watch, don't disconnect the transport yet because data can
2510 * still be in the buffer and do_reading may need several iteration to read
2511 * it all (because of its max_bytes_read_per_iteration limit).
2513 if (!(flags & DBUS_WATCH_READABLE) && unix_error_with_read_to_come (transport, watch, flags))
2515 _dbus_verbose ("Hang up or error on watch\n");
2516 _dbus_transport_disconnect (transport);
2520 if (watch == socket_transport->read_watch &&
2521 (flags & DBUS_WATCH_READABLE))
2523 #ifdef DBUS_AUTHENTICATION
2524 dbus_bool_t auth_finished;
2527 _dbus_verbose ("handling read watch %p flags = %x\n",
2530 #ifdef DBUS_AUTHENTICATION
2531 if (!do_authentication (transport, TRUE, FALSE, &auth_finished))
2534 /* We don't want to do a read immediately following
2535 * a successful authentication. This is so we
2536 * have a chance to propagate the authentication
2537 * state further up. Specifically, we need to
2538 * process any pending data from the auth object.
2543 if (!do_reading (transport))
2545 _dbus_verbose ("no memory to read\n");
2548 #ifdef DBUS_AUTHENTICATION
2552 _dbus_verbose ("Not reading anything since we just completed the authentication\n");
2556 else if (watch == socket_transport->write_watch &&
2557 (flags & DBUS_WATCH_WRITABLE))
2560 _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n",
2561 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
2563 #ifdef DBUS_AUTHENTICATION
2564 if (!do_authentication (transport, FALSE, TRUE, NULL))
2567 if (!do_writing (transport))
2569 _dbus_verbose ("no memory to write\n");
2573 /* See if we still need the write watch */
2574 check_write_watch (transport);
2576 #ifdef DBUS_ENABLE_VERBOSE_MODE
2579 if (watch == socket_transport->read_watch)
2580 _dbus_verbose ("asked to handle read watch with non-read condition 0x%x\n",
2582 else if (watch == socket_transport->write_watch)
2583 _dbus_verbose ("asked to handle write watch with non-write condition 0x%x\n",
2586 _dbus_verbose ("asked to handle watch %p on fd %d that we don't recognize\n",
2587 watch, dbus_watch_get_socket (watch));
2589 #endif /* DBUS_ENABLE_VERBOSE_MODE */
2595 socket_disconnect (DBusTransport *transport)
2597 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2599 _dbus_verbose ("\n");
2601 free_watches (transport);
2603 _dbus_close_socket (socket_transport->fd, NULL);
2604 socket_transport->fd = -1;
2608 kdbus_connection_set (DBusTransport *transport)
2610 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2612 dbus_connection_set_is_authenticated(transport->connection); //todo remove when authentication will work
2614 _dbus_watch_set_handler (socket_transport->write_watch,
2615 _dbus_connection_handle_watch,
2616 transport->connection, NULL);
2618 _dbus_watch_set_handler (socket_transport->read_watch,
2619 _dbus_connection_handle_watch,
2620 transport->connection, NULL);
2622 if (!_dbus_connection_add_watch_unlocked (transport->connection,
2623 socket_transport->write_watch))
2626 if (!_dbus_connection_add_watch_unlocked (transport->connection,
2627 socket_transport->read_watch))
2629 _dbus_connection_remove_watch_unlocked (transport->connection,
2630 socket_transport->write_watch);
2634 check_read_watch (transport);
2635 check_write_watch (transport);
2641 * @todo We need to have a way to wake up the select sleep if
2642 * a new iteration request comes in with a flag (read/write) that
2643 * we're not currently serving. Otherwise a call that just reads
2644 * could block a write call forever (if there are no incoming
2648 kdbus_do_iteration (DBusTransport *transport,
2650 int timeout_milliseconds)
2652 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2657 _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p fd = %d\n",
2658 flags & DBUS_ITERATION_DO_READING ? "read" : "",
2659 flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
2660 timeout_milliseconds,
2661 socket_transport->read_watch,
2662 socket_transport->write_watch,
2663 socket_transport->fd);
2665 /* the passed in DO_READING/DO_WRITING flags indicate whether to
2666 * read/write messages, but regardless of those we may need to block
2667 * for reading/writing to do auth. But if we do reading for auth,
2668 * we don't want to read any messages yet if not given DO_READING.
2671 poll_fd.fd = socket_transport->fd;
2674 if (_dbus_transport_peek_is_authenticated (transport))
2676 /* This is kind of a hack; if we have stuff to write, then try
2677 * to avoid the poll. This is probably about a 5% speedup on an
2678 * echo client/server.
2680 * If both reading and writing were requested, we want to avoid this
2681 * since it could have funky effects:
2682 * - both ends spinning waiting for the other one to read
2683 * data so they can finish writing
2684 * - prioritizing all writing ahead of reading
2686 if ((flags & DBUS_ITERATION_DO_WRITING) &&
2687 !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) &&
2688 !transport->disconnected &&
2689 _dbus_connection_has_messages_to_send_unlocked (transport->connection))
2691 do_writing (transport);
2693 if (transport->disconnected ||
2694 !_dbus_connection_has_messages_to_send_unlocked (transport->connection))
2698 /* If we get here, we decided to do the poll() after all */
2699 _dbus_assert (socket_transport->read_watch);
2700 if (flags & DBUS_ITERATION_DO_READING)
2701 poll_fd.events |= _DBUS_POLLIN;
2703 _dbus_assert (socket_transport->write_watch);
2704 if (flags & DBUS_ITERATION_DO_WRITING)
2705 poll_fd.events |= _DBUS_POLLOUT;
2709 DBusAuthState auth_state;
2711 auth_state = _dbus_auth_do_work (transport->auth);
2713 if (transport->receive_credentials_pending || auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT)
2714 poll_fd.events |= _DBUS_POLLIN;
2716 if (transport->send_credentials_pending || auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND)
2717 poll_fd.events |= _DBUS_POLLOUT;
2722 if (flags & DBUS_ITERATION_BLOCK)
2723 poll_timeout = timeout_milliseconds;
2727 /* For blocking selects we drop the connection lock here
2728 * to avoid blocking out connection access during a potentially
2729 * indefinite blocking call. The io path is still protected
2730 * by the io_path_cond condvar, so we won't reenter this.
2732 if (flags & DBUS_ITERATION_BLOCK)
2734 _dbus_verbose ("unlock pre poll\n");
2735 _dbus_connection_unlock (transport->connection);
2739 poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
2741 if (poll_res < 0 && _dbus_get_is_errno_eintr ())
2743 _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
2747 if (flags & DBUS_ITERATION_BLOCK)
2749 _dbus_verbose ("lock post poll\n");
2750 _dbus_connection_lock (transport->connection);
2756 poll_fd.revents = 0; /* some concern that posix does not guarantee this;
2757 * valgrind flags it as an error. though it probably
2758 * is guaranteed on linux at least.
2761 if (poll_fd.revents & _DBUS_POLLERR)
2762 do_io_error (transport);
2765 dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
2766 dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0;
2767 #ifdef DBUS_AUTHENTICATION
2768 dbus_bool_t authentication_completed;
2771 _dbus_verbose ("in iteration, need_read=%d need_write=%d\n",
2772 need_read, need_write);
2773 #ifdef DBUS_AUTHENTICATION
2774 do_authentication (transport, need_read, need_write,
2775 &authentication_completed);
2777 /* See comment in socket_handle_watch. */
2778 if (authentication_completed)
2781 if (need_read && (flags & DBUS_ITERATION_DO_READING))
2782 do_reading (transport);
2783 if (need_write && (flags & DBUS_ITERATION_DO_WRITING))
2784 do_writing (transport);
2788 _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
2792 /* We need to install the write watch only if we did not
2793 * successfully write everything. Note we need to be careful that we
2794 * don't call check_write_watch *before* do_writing, since it's
2795 * inefficient to add the write watch, and we can avoid it most of
2796 * the time since we can write immediately.
2798 * However, we MUST always call check_write_watch(); DBusConnection code
2799 * relies on the fact that running an iteration will notice that
2800 * messages are pending.
2802 check_write_watch (transport);
2804 _dbus_verbose (" ... leaving do_iteration()\n");
2808 socket_live_messages_changed (DBusTransport *transport)
2810 /* See if we should look for incoming messages again */
2811 check_read_watch (transport);
2814 static const DBusTransportVTable kdbus_vtable = {
2816 socket_handle_watch,
2818 kdbus_connection_set,
2820 socket_live_messages_changed,
2821 socket_get_socket_fd
2825 * Creates a new transport for the given kdbus file descriptor. The file
2826 * descriptor must be nonblocking.
2828 * @param fd the file descriptor.
2829 * @param address the transport's address
2830 * @returns the new transport, or #NULL if no memory.
2832 static DBusTransport*
2833 _dbus_transport_new_for_socket_kdbus (int fd,
2834 const DBusString *address)
2836 DBusTransportSocket *socket_transport;
2838 socket_transport = dbus_new0 (DBusTransportSocket, 1);
2839 if (socket_transport == NULL)
2842 if (!_dbus_string_init (&socket_transport->encoded_outgoing))
2845 if (!_dbus_string_init (&socket_transport->encoded_incoming))
2848 socket_transport->write_watch = _dbus_watch_new (fd,
2849 DBUS_WATCH_WRITABLE,
2852 if (socket_transport->write_watch == NULL)
2855 socket_transport->read_watch = _dbus_watch_new (fd,
2856 DBUS_WATCH_READABLE,
2859 if (socket_transport->read_watch == NULL)
2862 if (!_dbus_transport_init_base (&socket_transport->base,
2867 #ifdef DBUS_AUTHENTICATION
2868 #ifdef HAVE_UNIX_FD_PASSING
2869 _dbus_auth_set_unix_fd_possible(socket_transport->base.auth, _dbus_socket_can_pass_unix_fd(fd));
2873 socket_transport->fd = fd;
2874 socket_transport->message_bytes_written = 0;
2876 /* These values should probably be tunable or something. */
2877 socket_transport->max_bytes_read_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2878 socket_transport->max_bytes_written_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2880 socket_transport->kdbus_mmap_ptr = NULL;
2881 socket_transport->memfd = -1;
2883 return (DBusTransport*) socket_transport;
2886 _dbus_watch_invalidate (socket_transport->read_watch);
2887 _dbus_watch_unref (socket_transport->read_watch);
2889 _dbus_watch_invalidate (socket_transport->write_watch);
2890 _dbus_watch_unref (socket_transport->write_watch);
2892 _dbus_string_free (&socket_transport->encoded_incoming);
2894 _dbus_string_free (&socket_transport->encoded_outgoing);
2896 dbus_free (socket_transport);
2902 * Opens a connection to the kdbus bus
2904 * This will set FD_CLOEXEC for the socket returned.
2906 * @param path the path to UNIX domain socket
2907 * @param error return location for error code
2908 * @returns connection file descriptor or -1 on error
2910 static int _dbus_connect_kdbus (const char *path, DBusError *error)
2914 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2915 _dbus_verbose ("connecting to kdbus bus %s\n", path);
2917 fd = open(path, O_RDWR|O_CLOEXEC|O_NONBLOCK);
2919 dbus_set_error(error, _dbus_error_from_errno (errno), "Failed to open file descriptor: %s", _dbus_strerror (errno));
2925 * Creates a new transport for kdbus.
2926 * This creates a client-side of a transport.
2928 * @param path the path to the bus.
2929 * @param error address where an error can be returned.
2930 * @returns a new transport, or #NULL on failure.
2932 static DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error)
2935 DBusTransport *transport;
2938 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2940 if (!_dbus_string_init (&address))
2942 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2948 if ((!_dbus_string_append (&address, "kdbus:path=")) || (!_dbus_string_append (&address, path)))
2950 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2954 fd = _dbus_connect_kdbus (path, error);
2957 _DBUS_ASSERT_ERROR_IS_SET (error);
2961 _dbus_verbose ("Successfully connected to kdbus bus %s\n", path);
2963 transport = _dbus_transport_new_for_socket_kdbus (fd, &address);
2964 if (transport == NULL)
2966 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2970 _dbus_string_free (&address);
2975 _dbus_close_socket (fd, NULL);
2977 _dbus_string_free (&address);
2983 * Opens kdbus transport if method from address entry is kdbus
2985 * @param entry the address entry to try opening
2986 * @param transport_p return location for the opened transport
2987 * @param error error to be set
2988 * @returns result of the attempt
2990 DBusTransportOpenResult _dbus_transport_open_kdbus(DBusAddressEntry *entry,
2991 DBusTransport **transport_p,
2996 method = dbus_address_entry_get_method (entry);
2997 _dbus_assert (method != NULL);
2999 if (strcmp (method, "kdbus") == 0)
3001 const char *path = dbus_address_entry_get_value (entry, "path");
3005 _dbus_set_bad_address (error, "kdbus", "path", NULL);
3006 return DBUS_TRANSPORT_OPEN_BAD_ADDRESS;
3009 *transport_p = _dbus_transport_new_for_kdbus (path, error);
3011 if (*transport_p == NULL)
3013 _DBUS_ASSERT_ERROR_IS_SET (error);
3014 return DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT;
3018 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3019 return DBUS_TRANSPORT_OPEN_OK;
3024 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3025 return DBUS_TRANSPORT_OPEN_NOT_HANDLED;