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_PART_HEADER_SIZE offsetof(struct kdbus_item, data)
36 #define KDBUS_ITEM_SIZE(s) KDBUS_ALIGN8((s) + KDBUS_PART_HEADER_SIZE)
38 #define KDBUS_PART_NEXT(part) \
39 (typeof(part))(((uint8_t *)part) + KDBUS_ALIGN8((part)->size))
40 #define KDBUS_PART_FOREACH(part, head, first) \
41 for (part = (head)->first; \
42 (uint8_t *)(part) < (uint8_t *)(head) + (head)->size; \
43 part = KDBUS_PART_NEXT(part))
44 #define RECEIVE_POOL_SIZE (10 * 1024LU * 1024LU)
45 #define MEMFD_SIZE_THRESHOLD (2 * 1024 * 1024LU) // over this memfd is used
47 #define KDBUS_MSG_DECODE_DEBUG 0
49 #define ITER_APPEND_STR(string) \
50 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &string)) \
56 #define MSG_ITEM_BUILD_VEC(data, datasize) \
57 item->type = KDBUS_MSG_PAYLOAD_VEC; \
58 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec); \
59 item->vec.address = (unsigned long) data; \
60 item->vec.size = datasize;
63 * Opaque object representing a socket file descriptor transport.
65 typedef struct DBusTransportSocket DBusTransportSocket;
68 * Implementation details of DBusTransportSocket. All members are private.
70 struct DBusTransportSocket
72 DBusTransport base; /**< Parent instance */
73 int fd; /**< File descriptor. */
74 DBusWatch *read_watch; /**< Watch for readability. */
75 DBusWatch *write_watch; /**< Watch for writability. */
77 int max_bytes_read_per_iteration; /**< In kdbus only to control overall message size*/
78 int max_bytes_written_per_iteration; /**< In kdbus only to control overall message size*/
80 int message_bytes_written; /**< Number of bytes of current
81 * outgoing message that have
84 DBusString encoded_outgoing; /**< Encoded version of current
87 DBusString encoded_incoming; /**< Encoded version of current
90 void* kdbus_mmap_ptr; /**< Mapped memory where Kdbus (kernel) writes
91 * messages incoming to us.
93 int memfd; /**< File descriptor to special
94 * memory pool for bulk data
95 * transfer. Retrieved from
96 * Kdbus kernel module.
98 __u64 bloom_size; /**< bloom filter field size */
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 dbus_bool_t 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 dbus_bool_t 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))
176 * Retrieves file descriptor to memory pool from kdbus module.
177 * It is then used for bulk data sending.
178 * Triggered when message payload is over MEMFD_SIZE_THRESHOLD
181 static int kdbus_init_memfd(DBusTransportSocket* socket_transport)
185 if (ioctl(socket_transport->fd, KDBUS_CMD_MEMFD_NEW, &memfd) < 0) {
186 _dbus_verbose("KDBUS_CMD_MEMFD_NEW failed: \n");
190 socket_transport->memfd = memfd;
191 _dbus_verbose("kdbus_init_memfd: %d!!\n", socket_transport->memfd);
196 * Initiates Kdbus message structure.
197 * Calculates it's size, allocates memory and fills some fields.
198 * @param name Well-known name or NULL
199 * @param dst_id Numeric id of recipient
200 * @param body_size size of message body if present
201 * @param use_memfd flag to build memfd message
202 * @param fds_count number of file descriptors used
203 * @param transport transport
204 * @return initialized kdbus message
206 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)
208 struct kdbus_msg* msg;
211 msg_size = sizeof(struct kdbus_msg);
213 if(use_memfd == TRUE) // bulk data - memfd - encoded and plain
214 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_memfd));
216 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
218 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
222 msg_size += KDBUS_ITEM_SIZE(sizeof(int)*fds_count);
225 msg_size += KDBUS_ITEM_SIZE(strlen(name) + 1);
226 else if (dst_id == KDBUS_DST_ID_BROADCAST)
227 msg_size += KDBUS_PART_HEADER_SIZE + transport->bloom_size;
229 msg = malloc(msg_size);
232 _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
236 memset(msg, 0, msg_size);
237 msg->size = msg_size;
238 msg->payload_type = KDBUS_PAYLOAD_DBUS1;
239 msg->dst_id = name ? 0 : dst_id;
240 msg->src_id = strtoull(dbus_bus_get_unique_name(transport->base.connection), NULL , 10);
246 * Builds and sends kdbus message using Dbus message.
247 * Decide whether used payload vector or memfd memory pool.
248 * Handles broadcasts and unicast messages, and passing of Unix fds.
249 * Does error handling.
250 * TODO refactor to be more compact
252 * @param transport transport
253 * @param message DBus message to be sent
254 * @param encoded flag if the message is encoded
255 * @return size of data sent
257 static int kdbus_write_msg(DBusTransportSocket *transport, DBusMessage *message, dbus_bool_t encoded)
259 struct kdbus_msg *msg;
260 struct kdbus_item *item;
262 uint64_t dst_id = KDBUS_DST_ID_BROADCAST;
263 const DBusString *header;
264 const DBusString *body;
265 uint64_t ret_size = 0;
266 uint64_t body_size = 0;
267 uint64_t header_size = 0;
268 dbus_bool_t use_memfd;
271 dbus_bool_t autostart;
273 // determine name and destination id
274 if((name = dbus_message_get_destination(message)))
276 dst_id = KDBUS_DST_ID_WELL_KNOWN_NAME;
277 if((name[0] == ':') && (name[1] == '1') && (name[2] == '.')) /* if name starts with ":1." it is a unique name and should be send as number */
279 dst_id = strtoull(&name[3], NULL, 10);
286 ret_size = _dbus_string_get_length (&transport->encoded_outgoing);
289 _dbus_message_get_network_data (message, &header, &body);
290 header_size = _dbus_string_get_length(header);
291 body_size = _dbus_string_get_length(body);
292 ret_size = header_size + body_size;
295 // check if message size is big enough to use memfd kdbus transport
296 use_memfd = ret_size > MEMFD_SIZE_THRESHOLD ? TRUE : FALSE;
297 if(use_memfd) kdbus_init_memfd(transport);
299 _dbus_message_get_unix_fds(message, &unix_fds, &fds_count);
301 // init basic message fields
302 msg = kdbus_init_msg(name, dst_id, body_size, use_memfd, fds_count, transport);
303 msg->cookie = dbus_message_get_serial(message);
304 autostart = dbus_message_get_auto_start (message);
306 msg->flags |= KDBUS_MSG_FLAGS_NO_AUTO_START;
308 // build message contents
311 // case 1 - bulk data transfer - memfd - encoded and plain
316 if(ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 0) < 0)
318 _dbus_verbose("memfd sealing failed: \n");
322 buf = mmap(NULL, ret_size, PROT_WRITE, MAP_SHARED, transport->memfd, 0);
323 if (buf == MAP_FAILED)
325 _dbus_verbose("mmap() fd=%i failed:%m", transport->memfd);
330 memcpy(buf, &transport->encoded_outgoing, ret_size);
333 memcpy(buf, _dbus_string_get_const_data(header), header_size);
336 memcpy(buf, _dbus_string_get_const_data(body), body_size);
341 munmap(buf, ret_size);
343 // seal data - kdbus module needs it
344 if(ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 1) < 0) {
345 _dbus_verbose("memfd sealing failed: %d (%m)\n", errno);
350 item->type = KDBUS_MSG_PAYLOAD_MEMFD;
351 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_memfd);
352 item->memfd.size = ret_size;
353 item->memfd.fd = transport->memfd;
354 // case 2 - small encoded - don't use memfd
356 _dbus_verbose("sending encoded data\n");
357 MSG_ITEM_BUILD_VEC(&transport->encoded_outgoing, _dbus_string_get_length (&transport->encoded_outgoing));
359 // case 3 - small not encoded - don't use memfd
361 _dbus_verbose("sending normal vector data\n");
362 MSG_ITEM_BUILD_VEC(_dbus_string_get_const_data(header), header_size);
366 _dbus_verbose("body attaching\n");
367 MSG_ITEM_BUILD_VEC(_dbus_string_get_const_data(body), body_size);
373 item = KDBUS_PART_NEXT(item);
374 item->type = KDBUS_MSG_FDS;
375 item->size = KDBUS_PART_HEADER_SIZE + (sizeof(int) * fds_count);
376 memcpy(item->fds, unix_fds, sizeof(int) * fds_count);
381 item = KDBUS_PART_NEXT(item);
382 item->type = KDBUS_MSG_DST_NAME;
383 item->size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1;
384 strcpy(item->str, name);
386 else if (dst_id == KDBUS_DST_ID_BROADCAST)
388 item = KDBUS_PART_NEXT(item);
389 item->type = KDBUS_MSG_BLOOM;
390 item->size = KDBUS_PART_HEADER_SIZE + transport->bloom_size;
391 strncpy(item->data, dbus_message_get_interface(message), transport->bloom_size);
395 if (ioctl(transport->fd, KDBUS_CMD_MSG_SEND, msg))
399 if((errno == ESRCH) || (errno == ENXIO) || (errno = EADDRNOTAVAIL)) //when recipient is not available on the bus
403 //todo start service here, otherwise
404 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))
408 if(reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Name \"%s\" does not exist", dbus_message_get_destination(message), message, transport->base.connection))
412 _dbus_verbose("kdbus error sending message: err %d (%m)\n", errno);
417 close(transport->memfd);
432 * Performs kdbus query of id of the given name
434 * @param name name to query for
436 * @param ownerID place to store id of the name
437 * @return 0 on success, -errno if failed
439 static int kdbus_NameQuery(char* name, int fd, struct nameInfo* pInfo)
441 struct kdbus_cmd_name_info *msg;
442 struct kdbus_item *item;
447 pInfo->sec_label_len = 0;
448 pInfo->sec_label = NULL;
450 item_size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1;
451 item_size = (item_size < 56) ? 56 : item_size; //at least 56 bytes are needed by kernel to place info about name, otherwise error
452 size = sizeof(struct kdbus_cmd_name_info) + item_size;
457 _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
461 memset(msg, 0, size);
463 if((name[0] == ':') && (name[1] == '1') && (name[2] == '.')) /* if name starts with ":1." it is a unique name and should be send as number */
464 msg->id = strtoull(&name[3], NULL, 10);
469 item->type = KDBUS_NAME_INFO_ITEM_NAME;
470 item->size = item_size;
471 strcpy(item->str, name);
474 ret = ioctl(fd, KDBUS_CMD_NAME_QUERY, msg);
479 else if(ret == -ENOBUFS)
481 msg = realloc(msg, msg->size); //prepare memory
490 pInfo->uniqueId = msg->id;
491 pInfo->userId = msg->creds.uid;
492 pInfo->processId = msg->creds.pid;
493 _dbus_verbose ("I'm alive 1\n");
495 while((uint8_t *)(item) < (uint8_t *)(msg) + msg->size)
497 if(item->type == KDBUS_NAME_INFO_ITEM_SECLABEL)
499 pInfo->sec_label_len = item->size - KDBUS_PART_HEADER_SIZE - 1;
500 if(pInfo->sec_label_len != 0)
501 pInfo->sec_label = malloc(pInfo->sec_label_len);
502 if(pInfo->sec_label == NULL)
505 memcpy(pInfo->sec_label, item->data, pInfo->sec_label_len);
509 item = KDBUS_PART_NEXT(item);
518 * Handles messages sent to bus daemon - "org.freedesktop.DBus" and translates them to appropriate
519 * kdbus ioctl commands. Than translate kdbus reply into dbus message and put it into recived messages queue.
521 * !!! Not all methods are handled !!! Doubt if it is even possible.
522 * If method is not handled, returns error reply org.freedesktop.DBus.Error.UnknownMethod
529 * Not handled methods:
530 * - ListActivatableNames
531 * - StartServiceByName
532 * - UpdateActivationEnvironment
533 * - GetConnectionUnixUser
536 static dbus_bool_t emulateOrgFreedesktopDBus(DBusTransport *transport, DBusMessage *message)
539 struct nameInfo info;
540 dbus_bool_t ret_value;
542 if(!strcmp(dbus_message_get_member(message), "GetNameOwner")) //returns id of the well known name
546 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
547 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
548 if(inter_ret == 0) //unique id of the name
550 char unique_name[(unsigned int)(snprintf(name, 0, "%llu", ULLONG_MAX) + sizeof(":1."))];
551 const char* pString = unique_name;
553 sprintf(unique_name, ":1.%llu", (unsigned long long int)info.uniqueId);
554 _dbus_verbose("Unique name discovered:%s\n", unique_name);
555 ret_value = reply_1_data(message, DBUS_TYPE_STRING, &pString, transport->connection);
557 else if(inter_ret == -ENOENT) //name has no owner
558 return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get owner of name '%s': no such name", name, message, transport->connection);
561 _dbus_verbose("kdbus error sending name query: err %d (%m)\n", errno);
562 ret_value = reply_with_error(DBUS_ERROR_FAILED, "Could not determine unique name for '%s'", name, message, transport->connection);
565 else if(!strcmp(dbus_message_get_member(message), "NameHasOwner")) //returns if name is currently registered on the bus
570 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
571 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
572 if((inter_ret == 0) || (inter_ret == -ENOENT))
574 result = (inter_ret == 0) ? TRUE : FALSE;
575 ret_value = reply_1_data(message, DBUS_TYPE_BOOLEAN, &result, transport->connection);
579 _dbus_verbose("kdbus error checking if name exists: err %d (%m)\n", errno);
580 ret_value = reply_with_error(DBUS_ERROR_FAILED, "Could not determine whether name '%s' exists", name, message, transport->connection);
583 else if(!strcmp(dbus_message_get_member(message), "GetConnectionUnixUser"))
587 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
588 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
589 if(inter_ret == 0) //name found
591 _dbus_verbose("User id:%llu\n", (unsigned long long) info.userId);
592 ret_value = reply_1_data(message, DBUS_TYPE_UINT32, &info.userId, transport->connection);
594 else if(inter_ret == -ENOENT) //name has no owner
595 return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get UID of name '%s': no such name", name, message, transport->connection);
598 _dbus_verbose("kdbus error determining UID: err %d (%m)\n", errno);
599 ret_value = reply_with_error(DBUS_ERROR_FAILED, "Could not determine UID for '%s'", name, message, transport->connection);
602 else if(!strcmp(dbus_message_get_member(message), "GetConnectionUnixProcessID"))
606 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
607 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
608 if(inter_ret == 0) //name found
609 ret_value = reply_1_data(message, DBUS_TYPE_UINT32, &info.processId, transport->connection);
610 else if(inter_ret == -ENOENT) //name has no owner
611 return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get PID of name '%s': no such name", name, message, transport->connection);
614 _dbus_verbose("kdbus error determining PID: err %d (%m)\n", errno);
615 ret_value = reply_with_error(DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN,"Could not determine PID for '%s'", name, message, transport->connection);
618 else if(!strcmp(dbus_message_get_member(message), "ListNames")) //return all well known names on he bus
620 struct kdbus_cmd_names* pCmd;
623 cmd_size = sizeof(struct kdbus_cmd_names) + KDBUS_ITEM_SIZE(1);
624 pCmd = malloc(cmd_size);
627 pCmd->size = cmd_size;
631 if(ioctl(((DBusTransportSocket*)transport)->fd, KDBUS_CMD_NAME_LIST, pCmd))
635 if(errno == ENOBUFS) //buffer to small to put all names into it
636 cmd_size = pCmd->size; //here kernel tells how much memory it needs
639 _dbus_verbose("kdbus error asking for name list: err %d (%m)\n",errno);
643 if(cmd_size) //kernel needs more memory
645 pCmd = realloc(pCmd, cmd_size); //prepare memory
648 goto again; //and try again
653 DBusMessageIter args;
654 struct kdbus_cmd_name* pCmd_name;
657 reply = dbus_message_new_method_return(message);
660 dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
661 dbus_message_iter_init_append(reply, &args);
663 for (pCmd_name = pCmd->names; (uint8_t *)(pCmd_name) < (uint8_t *)(pCmd) + pCmd->size; pCmd_name = KDBUS_PART_NEXT(pCmd_name))
665 pName = pCmd_name->name;
666 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pName))
668 dbus_message_unref(reply);
673 if(add_message_to_received(reply, transport->connection))
684 else if(!strcmp(dbus_message_get_member(message), "GetId"))
687 char uuid[DBUS_UUID_LENGTH_BYTES];
690 DBusString binary, encoded;
693 path = &transport->address[11]; //start of kdbus bus path
694 if(stat(path, &stats) < -1)
696 _dbus_verbose("kdbus error reading stats of bus: err %d (%m)\n", errno);
697 return reply_with_error(DBUS_ERROR_FAILED, "Could not determine bus '%s' uuid", path, message, transport->connection);
701 MD5_Update(&md5, path, strlen(path));
702 MD5_Update(&md5, &stats.st_ctim.tv_sec, sizeof(stats.st_ctim.tv_sec));
703 MD5_Final(uuid, &md5);
705 if(!_dbus_string_init (&encoded))
707 _dbus_string_init_const_len (&binary, uuid, DBUS_UUID_LENGTH_BYTES);
708 if(!_dbus_string_hex_encode (&binary, 0, &encoded, _dbus_string_get_length (&encoded)))
710 path = (char*)_dbus_string_get_const_data (&encoded);
711 ret_value = reply_1_data(message, DBUS_TYPE_STRING, &path, transport->connection);
714 _dbus_string_free(&binary);
715 _dbus_string_free(&encoded);
719 else if(!strcmp(dbus_message_get_member(message), "GetAdtAuditSessionData"))
723 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
724 return reply_with_error(DBUS_ERROR_ADT_AUDIT_DATA_UNKNOWN, "Could not determine audit session data for '%s'", name, message, transport->connection);
726 else if(!strcmp(dbus_message_get_member(message), "GetConnectionSELinuxSecurityContext"))
730 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
731 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
732 if(inter_ret == -ENOENT) //name has no owner
733 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);
734 else if(inter_ret < 0)
735 return reply_with_error(DBUS_ERROR_SELINUX_SECURITY_CONTEXT_UNKNOWN, "Could not determine security context for '%s'", name, message, transport->connection);
741 reply = dbus_message_new_method_return(message);
744 dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
745 if (!dbus_message_append_args (reply, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &info.sec_label, info.sec_label_len, DBUS_TYPE_INVALID))
746 dbus_message_unref(reply);
747 else if(add_message_to_received(reply, transport->connection))
753 return reply_with_error(DBUS_ERROR_UNKNOWN_METHOD, NULL, (char*)dbus_message_get_member(message), message, transport->connection);
754 /* else if(!strcmp(dbus_message_get_member(message), "ListActivatableNames")) //todo
758 else if(!strcmp(dbus_message_get_member(message), "StartServiceByName"))
762 else if(!strcmp(dbus_message_get_member(message), "UpdateActivationEnvironment"))
766 else if(!strcmp(dbus_message_get_member(message), "ReloadConfig"))
773 free(info.sec_label);
777 #if KDBUS_MSG_DECODE_DEBUG == 1
778 static char *msg_id(uint64_t id, char *buf)
784 sprintf(buf, "%llu", (unsigned long long)id);
788 struct kdbus_enum_table {
792 #define _STRINGIFY(x) #x
793 #define STRINGIFY(x) _STRINGIFY(x)
794 #define ELEMENTSOF(x) (sizeof(x)/sizeof((x)[0]))
795 #define TABLE(what) static struct kdbus_enum_table kdbus_table_##what[]
796 #define ENUM(_id) { .id=_id, .name=STRINGIFY(_id) }
797 #define LOOKUP(what) \
798 const char *enum_##what(long long id) { \
800 for (i = 0; i < ELEMENTSOF(kdbus_table_##what); i++) \
801 if (id == kdbus_table_##what[i].id) \
802 return kdbus_table_##what[i].name; \
805 const char *enum_MSG(long long id);
807 ENUM(_KDBUS_MSG_NULL),
808 ENUM(KDBUS_MSG_PAYLOAD_VEC),
809 ENUM(KDBUS_MSG_PAYLOAD_OFF),
810 ENUM(KDBUS_MSG_PAYLOAD_MEMFD),
812 ENUM(KDBUS_MSG_BLOOM),
813 ENUM(KDBUS_MSG_DST_NAME),
814 ENUM(KDBUS_MSG_SRC_CREDS),
815 ENUM(KDBUS_MSG_SRC_PID_COMM),
816 ENUM(KDBUS_MSG_SRC_TID_COMM),
817 ENUM(KDBUS_MSG_SRC_EXE),
818 ENUM(KDBUS_MSG_SRC_CMDLINE),
819 ENUM(KDBUS_MSG_SRC_CGROUP),
820 ENUM(KDBUS_MSG_SRC_CAPS),
821 ENUM(KDBUS_MSG_SRC_SECLABEL),
822 ENUM(KDBUS_MSG_SRC_AUDIT),
823 ENUM(KDBUS_MSG_SRC_NAMES),
824 ENUM(KDBUS_MSG_TIMESTAMP),
825 ENUM(KDBUS_MSG_NAME_ADD),
826 ENUM(KDBUS_MSG_NAME_REMOVE),
827 ENUM(KDBUS_MSG_NAME_CHANGE),
828 ENUM(KDBUS_MSG_ID_ADD),
829 ENUM(KDBUS_MSG_ID_REMOVE),
830 ENUM(KDBUS_MSG_REPLY_TIMEOUT),
831 ENUM(KDBUS_MSG_REPLY_DEAD),
834 const char *enum_PAYLOAD(long long id);
836 ENUM(KDBUS_PAYLOAD_KERNEL),
837 ENUM(KDBUS_PAYLOAD_DBUS1),
838 ENUM(KDBUS_PAYLOAD_GVARIANT),
843 * Puts locally generated message into received data buffer.
844 * Use only during receiving phase!
846 * @param message message to load
847 * @param data place to load message
848 * @return size of message
850 static int put_message_into_data(DBusMessage *message, char* data)
853 const DBusString *header;
854 const DBusString *body;
857 dbus_message_lock (message);
858 _dbus_message_get_network_data (message, &header, &body);
859 ret_size = _dbus_string_get_length(header);
860 memcpy(data, _dbus_string_get_const_data(header), ret_size);
862 size = _dbus_string_get_length(body);
863 memcpy(data, _dbus_string_get_const_data(body), size);
865 dbus_message_unref(message);
870 * Decodes kdbus message in order to extract dbus message and put it into data and fds.
871 * Also captures and decodes kdbus error messages and kdbus kernel broadcasts and converts
872 * all of them into dbus messages.
874 * @param msg kdbus message
875 * @param data place to copy dbus message to
876 * @param socket_transport transport
877 * @param fds place to store file descriptors received
878 * @param n_fds place to store quantity of file descriptor
879 * @return number of dbus message's bytes received or -1 on error
881 static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTransportSocket* socket_transport, int* fds, int* n_fds)
883 const struct kdbus_item *item;
885 DBusMessage *message = NULL;
886 DBusMessageIter args;
887 const char* emptyString = "";
888 const char* pString = NULL;
889 char dbus_name[(unsigned int)(snprintf((char*)pString, 0, "%llu", ULLONG_MAX) + sizeof(":1."))];
890 const char* pDBusName = dbus_name;
891 #if KDBUS_MSG_DECODE_DEBUG == 1
895 #if KDBUS_MSG_DECODE_DEBUG == 1
896 _dbus_verbose("MESSAGE: %s (%llu bytes) flags=0x%llx, %s → %s, cookie=%llu, timeout=%llu\n",
897 enum_PAYLOAD(msg->payload_type), (unsigned long long) msg->size,
898 (unsigned long long) msg->flags,
899 msg_id(msg->src_id, buf), msg_id(msg->dst_id, buf),
900 (unsigned long long) msg->cookie, (unsigned long long) msg->timeout_ns);
905 KDBUS_PART_FOREACH(item, msg, items)
907 if (item->size <= KDBUS_PART_HEADER_SIZE)
909 _dbus_verbose(" +%s (%llu bytes) invalid data record\n", enum_MSG(item->type), item->size);
910 break; //??? continue (because dbus will find error) or break
915 case KDBUS_MSG_PAYLOAD_OFF:
916 memcpy(data, (char *)socket_transport->kdbus_mmap_ptr + item->vec.offset, item->vec.size);
917 data += item->vec.size;
918 ret_size += item->vec.size;
920 _dbus_verbose(" +%s (%llu bytes) off=%llu size=%llu\n",
921 enum_MSG(item->type), item->size,
922 (unsigned long long)item->vec.offset,
923 (unsigned long long)item->vec.size);
926 case KDBUS_MSG_PAYLOAD_MEMFD:
931 size = item->memfd.size;
932 _dbus_verbose("memfd.size : %llu\n", (unsigned long long)size);
934 buf = mmap(NULL, size, PROT_READ , MAP_SHARED, item->memfd.fd, 0);
935 if (buf == MAP_FAILED)
937 _dbus_verbose("mmap() fd=%i failed:%m", item->memfd.fd);
941 memcpy(data, buf, size);
947 _dbus_verbose(" +%s (%llu bytes) off=%llu size=%llu\n",
948 enum_MSG(item->type), item->size,
949 (unsigned long long)item->vec.offset,
950 (unsigned long long)item->vec.size);
958 *n_fds = (item->size - KDBUS_PART_HEADER_SIZE) / sizeof(int);
959 memcpy(fds, item->fds, *n_fds * sizeof(int));
960 for (i = 0; i < *n_fds; i++)
961 _dbus_fd_set_close_on_exec(fds[i]);
965 #if KDBUS_MSG_DECODE_DEBUG == 1
966 case KDBUS_MSG_SRC_CREDS:
967 _dbus_verbose(" +%s (%llu bytes) uid=%lld, gid=%lld, pid=%lld, tid=%lld, starttime=%lld\n",
968 enum_MSG(item->type), item->size,
969 item->creds.uid, item->creds.gid,
970 item->creds.pid, item->creds.tid,
971 item->creds.starttime);
974 case KDBUS_MSG_SRC_PID_COMM:
975 case KDBUS_MSG_SRC_TID_COMM:
976 case KDBUS_MSG_SRC_EXE:
977 case KDBUS_MSG_SRC_CGROUP:
978 case KDBUS_MSG_SRC_SECLABEL:
979 case KDBUS_MSG_DST_NAME:
980 _dbus_verbose(" +%s (%llu bytes) '%s' (%zu)\n",
981 enum_MSG(item->type), item->size, item->str, strlen(item->str));
984 case KDBUS_MSG_SRC_CMDLINE:
985 case KDBUS_MSG_SRC_NAMES: {
986 __u64 size = item->size - KDBUS_PART_HEADER_SIZE;
987 const char *str = item->str;
990 _dbus_verbose(" +%s (%llu bytes) ", enum_MSG(item->type), item->size);
992 _dbus_verbose("'%s' ", str);
993 size -= strlen(str) + 1;
994 str += strlen(str) + 1;
998 _dbus_verbose("(%d string%s)\n", count, (count == 1) ? "" : "s");
1002 case KDBUS_MSG_SRC_AUDIT:
1003 _dbus_verbose(" +%s (%llu bytes) loginuid=%llu sessionid=%llu\n",
1004 enum_MSG(item->type), item->size,
1005 (unsigned long long)item->data64[0],
1006 (unsigned long long)item->data64[1]);
1009 case KDBUS_MSG_SRC_CAPS: {
1011 const uint32_t *cap;
1014 _dbus_verbose(" +%s (%llu bytes) len=%llu bytes)\n",
1015 enum_MSG(item->type), item->size,
1016 (unsigned long long)item->size - KDBUS_PART_HEADER_SIZE);
1019 n = (item->size - KDBUS_PART_HEADER_SIZE) / 4 / sizeof(uint32_t);
1021 _dbus_verbose(" CapInh=");
1022 for (i = 0; i < n; i++)
1023 _dbus_verbose("%08x", cap[(0 * n) + (n - i - 1)]);
1025 _dbus_verbose(" CapPrm=");
1026 for (i = 0; i < n; i++)
1027 _dbus_verbose("%08x", cap[(1 * n) + (n - i - 1)]);
1029 _dbus_verbose(" CapEff=");
1030 for (i = 0; i < n; i++)
1031 _dbus_verbose("%08x", cap[(2 * n) + (n - i - 1)]);
1033 _dbus_verbose(" CapInh=");
1034 for (i = 0; i < n; i++)
1035 _dbus_verbose("%08x", cap[(3 * n) + (n - i - 1)]);
1036 _dbus_verbose("\n");
1040 case KDBUS_MSG_TIMESTAMP:
1041 _dbus_verbose(" +%s (%llu bytes) realtime=%lluns monotonic=%lluns\n",
1042 enum_MSG(item->type), item->size,
1043 (unsigned long long)item->timestamp.realtime_ns,
1044 (unsigned long long)item->timestamp.monotonic_ns);
1048 case KDBUS_MSG_REPLY_TIMEOUT:
1049 _dbus_verbose(" +%s (%llu bytes) cookie=%llu\n",
1050 enum_MSG(item->type), item->size, msg->cookie_reply);
1052 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NO_REPLY, NULL);
1059 ret_size = put_message_into_data(message, data);
1062 case KDBUS_MSG_REPLY_DEAD:
1063 _dbus_verbose(" +%s (%llu bytes) cookie=%llu\n",
1064 enum_MSG(item->type), item->size, msg->cookie_reply);
1066 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NAME_HAS_NO_OWNER, NULL);
1073 ret_size = put_message_into_data(message, data);
1076 case KDBUS_MSG_NAME_ADD:
1077 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1078 enum_MSG(item->type), (unsigned long long) item->size,
1079 item->name_change.name, item->name_change.old_id,
1080 item->name_change.new_id, item->name_change.flags);
1082 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1089 sprintf(dbus_name,":1.%llu",item->name_change.new_id);
1090 pString = item->name_change.name;
1091 _dbus_verbose ("Name added: %s\n", pString);
1092 dbus_message_iter_init_append(message, &args);
1093 ITER_APPEND_STR(pString)
1094 ITER_APPEND_STR(emptyString)
1095 ITER_APPEND_STR(pDBusName)
1096 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1098 ret_size = put_message_into_data(message, data);
1101 case KDBUS_MSG_NAME_REMOVE:
1102 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1103 enum_MSG(item->type), (unsigned long long) item->size,
1104 item->name_change.name, item->name_change.old_id,
1105 item->name_change.new_id, item->name_change.flags);
1107 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged"); // name of the signal
1114 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
1115 pString = item->name_change.name;
1116 _dbus_verbose ("Name removed: %s\n", pString);
1117 dbus_message_iter_init_append(message, &args);
1118 ITER_APPEND_STR(pString)
1119 ITER_APPEND_STR(pDBusName)
1120 ITER_APPEND_STR(emptyString)
1121 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1123 ret_size = put_message_into_data(message, data);
1126 case KDBUS_MSG_NAME_CHANGE:
1127 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1128 enum_MSG(item->type), (unsigned long long) item->size,
1129 item->name_change.name, item->name_change.old_id,
1130 item->name_change.new_id, item->name_change.flags);
1132 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1139 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
1140 pString = item->name_change.name;
1141 _dbus_verbose ("Name changed: %s\n", pString);
1142 dbus_message_iter_init_append(message, &args);
1143 ITER_APPEND_STR(pString)
1144 ITER_APPEND_STR(pDBusName)
1145 sprintf(&dbus_name[3],"%llu",item->name_change.new_id);
1146 _dbus_verbose ("New id: %s\n", pDBusName);
1147 ITER_APPEND_STR(pDBusName)
1148 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1150 ret_size = put_message_into_data(message, data);
1153 case KDBUS_MSG_ID_ADD:
1154 _dbus_verbose(" +%s (%llu bytes) id=%llu flags=%llu\n",
1155 enum_MSG(item->type), (unsigned long long) item->size,
1156 (unsigned long long) item->id_change.id,
1157 (unsigned long long) item->id_change.flags);
1159 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1166 sprintf(dbus_name,":1.%llu",item->id_change.id);
1167 dbus_message_iter_init_append(message, &args);
1168 ITER_APPEND_STR(pDBusName)
1169 ITER_APPEND_STR(emptyString)
1170 ITER_APPEND_STR(pDBusName)
1171 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1173 ret_size = put_message_into_data(message, data);
1176 case KDBUS_MSG_ID_REMOVE:
1177 _dbus_verbose(" +%s (%llu bytes) id=%llu flags=%llu\n",
1178 enum_MSG(item->type), (unsigned long long) item->size,
1179 (unsigned long long) item->id_change.id,
1180 (unsigned long long) item->id_change.flags);
1182 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1189 sprintf(dbus_name,":1.%llu",item->id_change.id);
1190 dbus_message_iter_init_append(message, &args);
1191 ITER_APPEND_STR(pDBusName)
1192 ITER_APPEND_STR(pDBusName)
1193 ITER_APPEND_STR(emptyString)
1194 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1196 ret_size = put_message_into_data(message, data);
1198 #if KDBUS_MSG_DECODE_DEBUG == 1
1200 _dbus_verbose(" +%s (%llu bytes)\n", enum_MSG(item->type), item->size);
1206 #if KDBUS_MSG_DECODE_DEBUG == 1
1208 if ((char *)item - ((char *)msg + msg->size) >= 8)
1209 _dbus_verbose("invalid padding at end of message\n");
1214 dbus_message_unref(message);
1219 * Reads message from kdbus and puts it into dbus buffer and fds
1221 * @param transport transport
1222 * @param buffer place to copy received message to
1223 * @param fds place to store file descriptors sent in the message
1224 * @param n_fds place to store number of file descriptors
1225 * @return size of received message on success, -1 on error
1227 static int kdbus_read_message(DBusTransportSocket *socket_transport, DBusString *buffer, int* fds, int* n_fds)
1230 uint64_t __attribute__ ((__aligned__(8))) offset;
1231 struct kdbus_msg *msg;
1235 start = _dbus_string_get_length (buffer);
1236 if (!_dbus_string_lengthen (buffer, socket_transport->max_bytes_read_per_iteration))
1241 data = _dbus_string_get_data_len (buffer, start, socket_transport->max_bytes_read_per_iteration);
1244 if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RECV, &offset) < 0)
1248 _dbus_verbose("kdbus error receiving message: %d (%m)\n", errno);
1249 _dbus_string_set_length (buffer, start);
1253 msg = (struct kdbus_msg *)((char*)socket_transport->kdbus_mmap_ptr + offset);
1255 ret_size = kdbus_decode_msg(msg, data, socket_transport, fds, n_fds);
1257 if(ret_size == -1) /* error */
1259 _dbus_string_set_length (buffer, start);
1263 _dbus_string_set_length (buffer, start + ret_size);
1267 if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RELEASE, &offset) < 0)
1271 _dbus_verbose("kdbus error freeing message: %d (%m)\n", errno);
1279 free_watches (DBusTransport *transport)
1281 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1283 _dbus_verbose ("start\n");
1285 if (socket_transport->read_watch)
1287 if (transport->connection)
1288 _dbus_connection_remove_watch_unlocked (transport->connection,
1289 socket_transport->read_watch);
1290 _dbus_watch_invalidate (socket_transport->read_watch);
1291 _dbus_watch_unref (socket_transport->read_watch);
1292 socket_transport->read_watch = NULL;
1295 if (socket_transport->write_watch)
1297 if (transport->connection)
1298 _dbus_connection_remove_watch_unlocked (transport->connection,
1299 socket_transport->write_watch);
1300 _dbus_watch_invalidate (socket_transport->write_watch);
1301 _dbus_watch_unref (socket_transport->write_watch);
1302 socket_transport->write_watch = NULL;
1305 _dbus_verbose ("end\n");
1309 socket_finalize (DBusTransport *transport)
1311 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1313 _dbus_verbose ("\n");
1315 free_watches (transport);
1317 _dbus_string_free (&socket_transport->encoded_outgoing);
1318 _dbus_string_free (&socket_transport->encoded_incoming);
1320 _dbus_transport_finalize_base (transport);
1322 _dbus_assert (socket_transport->read_watch == NULL);
1323 _dbus_assert (socket_transport->write_watch == NULL);
1325 dbus_free (transport);
1329 check_write_watch (DBusTransport *transport)
1331 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1334 if (transport->connection == NULL)
1337 if (transport->disconnected)
1339 _dbus_assert (socket_transport->write_watch == NULL);
1343 _dbus_transport_ref (transport);
1345 #ifdef DBUS_AUTHENTICATION
1346 if (_dbus_transport_get_is_authenticated (transport))
1348 needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection);
1349 #ifdef DBUS_AUTHENTICATION
1352 if (transport->send_credentials_pending)
1356 DBusAuthState auth_state;
1358 auth_state = _dbus_auth_do_work (transport->auth);
1360 /* If we need memory we install the write watch just in case,
1361 * if there's no need for it, it will get de-installed
1362 * next time we try reading.
1364 if (auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND ||
1365 auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY)
1372 _dbus_verbose ("check_write_watch(): needed = %d on connection %p watch %p fd = %d outgoing messages exist %d\n",
1373 needed, transport->connection, socket_transport->write_watch,
1374 socket_transport->fd,
1375 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1377 _dbus_connection_toggle_watch_unlocked (transport->connection,
1378 socket_transport->write_watch,
1381 _dbus_transport_unref (transport);
1385 check_read_watch (DBusTransport *transport)
1387 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1388 dbus_bool_t need_read_watch;
1390 _dbus_verbose ("fd = %d\n",socket_transport->fd);
1392 if (transport->connection == NULL)
1395 if (transport->disconnected)
1397 _dbus_assert (socket_transport->read_watch == NULL);
1401 _dbus_transport_ref (transport);
1403 #ifdef DBUS_AUTHENTICATION
1404 if (_dbus_transport_get_is_authenticated (transport))
1407 (_dbus_counter_get_size_value (transport->live_messages) < transport->max_live_messages_size) &&
1408 (_dbus_counter_get_unix_fd_value (transport->live_messages) < transport->max_live_messages_unix_fds);
1409 #ifdef DBUS_AUTHENTICATION
1412 if (transport->receive_credentials_pending)
1413 need_read_watch = TRUE;
1416 /* The reason to disable need_read_watch when not WAITING_FOR_INPUT
1417 * is to avoid spinning on the file descriptor when we're waiting
1418 * to write or for some other part of the auth process
1420 DBusAuthState auth_state;
1422 auth_state = _dbus_auth_do_work (transport->auth);
1424 /* If we need memory we install the read watch just in case,
1425 * if there's no need for it, it will get de-installed
1426 * next time we try reading. If we're authenticated we
1427 * install it since we normally have it installed while
1430 if (auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT ||
1431 auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY ||
1432 auth_state == DBUS_AUTH_STATE_AUTHENTICATED)
1433 need_read_watch = TRUE;
1435 need_read_watch = FALSE;
1440 _dbus_verbose (" setting read watch enabled = %d\n", need_read_watch);
1441 _dbus_connection_toggle_watch_unlocked (transport->connection,
1442 socket_transport->read_watch,
1445 _dbus_transport_unref (transport);
1449 do_io_error (DBusTransport *transport)
1451 _dbus_transport_ref (transport);
1452 _dbus_transport_disconnect (transport);
1453 _dbus_transport_unref (transport);
1456 #ifdef DBUS_AUTHENTICATION
1457 /* return value is whether we successfully read any new data. */
1459 read_data_into_auth (DBusTransport *transport,
1462 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1468 _dbus_auth_get_buffer (transport->auth, &buffer);
1470 bytes_read = kdbus_read_message(socket_transport, buffer);
1472 _dbus_auth_return_buffer (transport->auth, buffer,
1473 bytes_read > 0 ? bytes_read : 0);
1477 _dbus_verbose (" read %d bytes in auth phase\n", bytes_read);
1480 else if (bytes_read < 0)
1482 /* EINTR already handled for us */
1484 if (_dbus_get_is_errno_enomem ())
1488 else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1489 ; /* do nothing, just return FALSE below */
1492 _dbus_verbose ("Error reading from remote app: %s\n",
1493 _dbus_strerror_from_errno ());
1494 do_io_error (transport);
1501 _dbus_assert (bytes_read == 0);
1503 _dbus_verbose ("Disconnected from remote app\n");
1504 do_io_error (transport);
1510 /* Return value is whether we successfully wrote any bytes */
1512 write_data_from_auth (DBusTransport *transport)
1514 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1516 const DBusString *buffer;
1518 if (!_dbus_auth_get_bytes_to_send (transport->auth,
1522 bytes_written = _dbus_write_socket (socket_transport->fd,
1524 0, _dbus_string_get_length (buffer));
1526 if (bytes_written > 0)
1528 _dbus_auth_bytes_sent (transport->auth, bytes_written);
1531 else if (bytes_written < 0)
1533 /* EINTR already handled for us */
1535 if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1539 _dbus_verbose ("Error writing to remote app: %s\n",
1540 _dbus_strerror_from_errno ());
1541 do_io_error (transport);
1550 exchange_credentials (DBusTransport *transport,
1551 dbus_bool_t do_reading,
1552 dbus_bool_t do_writing)
1554 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1555 DBusError error = DBUS_ERROR_INIT;
1557 _dbus_verbose ("exchange_credentials: do_reading = %d, do_writing = %d\n",
1558 do_reading, do_writing);
1560 if (do_writing && transport->send_credentials_pending)
1562 if (_dbus_send_credentials_socket (socket_transport->fd,
1565 transport->send_credentials_pending = FALSE;
1569 _dbus_verbose ("Failed to write credentials: %s\n", error.message);
1570 dbus_error_free (&error);
1571 do_io_error (transport);
1575 if (do_reading && transport->receive_credentials_pending)
1577 /* FIXME this can fail due to IO error _or_ OOM, broken
1578 * (somewhat tricky to fix since the OOM error can be set after
1579 * we already read the credentials byte, so basically we need to
1580 * separate reading the byte and storing it in the
1581 * transport->credentials). Does not really matter for now
1582 * because storing in credentials never actually fails on unix.
1584 if (_dbus_read_credentials_socket (socket_transport->fd,
1585 transport->credentials,
1588 transport->receive_credentials_pending = FALSE;
1592 _dbus_verbose ("Failed to read credentials %s\n", error.message);
1593 dbus_error_free (&error);
1594 do_io_error (transport);
1598 if (!(transport->send_credentials_pending ||
1599 transport->receive_credentials_pending))
1601 if (!_dbus_auth_set_credentials (transport->auth,
1602 transport->credentials))
1610 do_authentication (DBusTransport *transport,
1611 dbus_bool_t do_reading,
1612 dbus_bool_t do_writing,
1613 dbus_bool_t *auth_completed)
1616 dbus_bool_t orig_auth_state;
1620 orig_auth_state = _dbus_transport_get_is_authenticated (transport);
1622 /* This is essential to avoid the check_write_watch() at the end,
1623 * we don't want to add a write watch in do_iteration before
1624 * we try writing and get EAGAIN
1626 if (orig_auth_state)
1629 *auth_completed = FALSE;
1633 _dbus_transport_ref (transport);
1635 while (!_dbus_transport_get_is_authenticated (transport) &&
1636 _dbus_transport_get_is_connected (transport))
1638 if (!exchange_credentials (transport, do_reading, do_writing))
1644 if (transport->send_credentials_pending ||
1645 transport->receive_credentials_pending)
1647 _dbus_verbose ("send_credentials_pending = %d receive_credentials_pending = %d\n",
1648 transport->send_credentials_pending,
1649 transport->receive_credentials_pending);
1653 #define TRANSPORT_SIDE(t) ((t)->is_server ? "server" : "client")
1654 switch (_dbus_auth_do_work (transport->auth))
1656 case DBUS_AUTH_STATE_WAITING_FOR_INPUT:
1657 _dbus_verbose (" %s auth state: waiting for input\n",
1658 TRANSPORT_SIDE (transport));
1659 if (!do_reading || !read_data_into_auth (transport, &oom))
1663 case DBUS_AUTH_STATE_WAITING_FOR_MEMORY:
1664 _dbus_verbose (" %s auth state: waiting for memory\n",
1665 TRANSPORT_SIDE (transport));
1670 case DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND:
1671 _dbus_verbose (" %s auth state: bytes to send\n",
1672 TRANSPORT_SIDE (transport));
1673 if (!do_writing || !write_data_from_auth (transport))
1677 case DBUS_AUTH_STATE_NEED_DISCONNECT:
1678 _dbus_verbose (" %s auth state: need to disconnect\n",
1679 TRANSPORT_SIDE (transport));
1680 do_io_error (transport);
1683 case DBUS_AUTH_STATE_AUTHENTICATED:
1684 _dbus_verbose (" %s auth state: authenticated\n",
1685 TRANSPORT_SIDE (transport));
1692 *auth_completed = (orig_auth_state != _dbus_transport_get_is_authenticated (transport));
1694 check_read_watch (transport);
1695 check_write_watch (transport);
1696 _dbus_transport_unref (transport);
1705 /* returns false on oom */
1707 do_writing (DBusTransport *transport)
1709 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1712 #ifdef DBUS_AUTHENTICATION
1713 /* No messages without authentication! */
1714 if (!_dbus_transport_get_is_authenticated (transport))
1716 _dbus_verbose ("Not authenticated, not writing anything\n");
1721 if (transport->disconnected)
1723 _dbus_verbose ("Not connected, not writing anything\n");
1728 _dbus_verbose ("do_writing(), have_messages = %d, fd = %d\n",
1729 _dbus_connection_has_messages_to_send_unlocked (transport->connection),
1730 socket_transport->fd);
1735 while (!transport->disconnected && _dbus_connection_has_messages_to_send_unlocked (transport->connection))
1738 DBusMessage *message;
1739 const DBusString *header;
1740 const DBusString *body;
1741 int total_bytes_to_write;
1742 const char* pDestination;
1744 message = _dbus_connection_get_message_to_send (transport->connection);
1745 _dbus_assert (message != NULL);
1746 dbus_message_lock (message);
1747 _dbus_message_get_network_data (message, &header, &body);
1748 total_bytes_to_write = _dbus_string_get_length(header) + _dbus_string_get_length(body);
1749 pDestination = dbus_message_get_destination(message);
1753 if(!strcmp(pDestination, "org.freedesktop.DBus"))
1755 if(emulateOrgFreedesktopDBus(transport, message))
1756 bytes_written = total_bytes_to_write;
1762 if (_dbus_auth_needs_encoding (transport->auth))
1764 if (_dbus_string_get_length (&socket_transport->encoded_outgoing) == 0)
1766 if (!_dbus_auth_encode_data (transport->auth,
1767 header, &socket_transport->encoded_outgoing))
1773 if (!_dbus_auth_encode_data (transport->auth,
1774 body, &socket_transport->encoded_outgoing))
1776 _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
1782 total_bytes_to_write = _dbus_string_get_length (&socket_transport->encoded_outgoing);
1783 if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration)
1786 bytes_written = kdbus_write_msg(socket_transport, message, TRUE);
1790 if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration)
1793 bytes_written = kdbus_write_msg(socket_transport, message, FALSE);
1797 if (bytes_written < 0)
1799 /* EINTR already handled for us */
1801 /* For some discussion of why we also ignore EPIPE here, see
1802 * http://lists.freedesktop.org/archives/dbus/2008-March/009526.html
1805 if (_dbus_get_is_errno_eagain_or_ewouldblock () || _dbus_get_is_errno_epipe ())
1809 _dbus_verbose ("Error writing to remote app: %s\n", _dbus_strerror_from_errno ());
1810 do_io_error (transport);
1816 _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
1817 total_bytes_to_write);
1819 socket_transport->message_bytes_written += bytes_written;
1821 _dbus_assert (socket_transport->message_bytes_written <=
1822 total_bytes_to_write);
1824 if (socket_transport->message_bytes_written == total_bytes_to_write)
1826 socket_transport->message_bytes_written = 0;
1827 _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
1828 _dbus_string_compact (&socket_transport->encoded_outgoing, 2048);
1830 _dbus_connection_message_sent_unlocked (transport->connection,
1842 /* returns false on out-of-memory */
1844 do_reading (DBusTransport *transport)
1846 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1849 dbus_bool_t oom = FALSE;
1852 _dbus_verbose ("fd = %d\n",socket_transport->fd);
1854 #ifdef DBUS_AUTHENTICATION
1855 /* No messages without authentication! */
1856 if (!_dbus_transport_get_is_authenticated (transport))
1862 /* See if we've exceeded max messages and need to disable reading */
1863 check_read_watch (transport);
1865 _dbus_assert (socket_transport->read_watch != NULL ||
1866 transport->disconnected);
1868 if (transport->disconnected)
1871 if (!dbus_watch_get_enabled (socket_transport->read_watch))
1874 if (!_dbus_message_loader_get_unix_fds(transport->loader, &fds, &n_fds))
1876 _dbus_verbose ("Out of memory reading file descriptors\n");
1880 _dbus_message_loader_get_buffer (transport->loader, &buffer);
1882 if (_dbus_auth_needs_decoding (transport->auth))
1884 bytes_read = kdbus_read_message(socket_transport, &socket_transport->encoded_incoming, fds, &n_fds);
1886 _dbus_assert (_dbus_string_get_length (&socket_transport->encoded_incoming) == bytes_read);
1890 if (!_dbus_auth_decode_data (transport->auth,
1891 &socket_transport->encoded_incoming,
1894 _dbus_verbose ("Out of memory decoding incoming data\n");
1895 _dbus_message_loader_return_buffer (transport->loader,
1897 _dbus_string_get_length (buffer));
1902 _dbus_string_set_length (&socket_transport->encoded_incoming, 0);
1903 _dbus_string_compact (&socket_transport->encoded_incoming, 2048);
1907 bytes_read = kdbus_read_message(socket_transport, buffer, fds, &n_fds);
1909 if (bytes_read >= 0 && n_fds > 0)
1910 _dbus_verbose("Read %i unix fds\n", n_fds);
1912 _dbus_message_loader_return_buffer (transport->loader,
1914 bytes_read < 0 ? 0 : bytes_read);
1915 _dbus_message_loader_return_unix_fds(transport->loader, fds, bytes_read < 0 ? 0 : n_fds);
1919 /* EINTR already handled for us */
1921 if (_dbus_get_is_errno_enomem ())
1923 _dbus_verbose ("Out of memory in read()/do_reading()\n");
1927 else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1931 _dbus_verbose ("Error reading from remote app: %s\n",
1932 _dbus_strerror_from_errno ());
1933 do_io_error (transport);
1937 else if (bytes_read == 0)
1939 _dbus_verbose ("Disconnected from remote app\n");
1940 do_io_error (transport);
1945 _dbus_verbose (" read %d bytes\n", bytes_read);
1947 if (!_dbus_transport_queue_messages (transport))
1950 _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
1954 /* Try reading more data until we get EAGAIN and return, or
1955 * exceed max bytes per iteration. If in blocking mode of
1956 * course we'll block instead of returning.
1968 unix_error_with_read_to_come (DBusTransport *itransport,
1972 DBusTransportSocket *transport = (DBusTransportSocket *) itransport;
1974 if (!((flags & DBUS_WATCH_HANGUP) || (flags & DBUS_WATCH_ERROR)))
1977 /* If we have a read watch enabled ...
1978 we -might have data incoming ... => handle the HANGUP there */
1979 if (watch != transport->read_watch && _dbus_watch_get_enabled (transport->read_watch))
1986 socket_handle_watch (DBusTransport *transport,
1990 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1992 _dbus_assert (watch == socket_transport->read_watch ||
1993 watch == socket_transport->write_watch);
1994 _dbus_assert (watch != NULL);
1996 /* If we hit an error here on a write watch, don't disconnect the transport yet because data can
1997 * still be in the buffer and do_reading may need several iteration to read
1998 * it all (because of its max_bytes_read_per_iteration limit).
2000 if (!(flags & DBUS_WATCH_READABLE) && unix_error_with_read_to_come (transport, watch, flags))
2002 _dbus_verbose ("Hang up or error on watch\n");
2003 _dbus_transport_disconnect (transport);
2007 if (watch == socket_transport->read_watch &&
2008 (flags & DBUS_WATCH_READABLE))
2010 #ifdef DBUS_AUTHENTICATION
2011 dbus_bool_t auth_finished;
2014 _dbus_verbose ("handling read watch %p flags = %x\n",
2017 #ifdef DBUS_AUTHENTICATION
2018 if (!do_authentication (transport, TRUE, FALSE, &auth_finished))
2021 /* We don't want to do a read immediately following
2022 * a successful authentication. This is so we
2023 * have a chance to propagate the authentication
2024 * state further up. Specifically, we need to
2025 * process any pending data from the auth object.
2030 if (!do_reading (transport))
2032 _dbus_verbose ("no memory to read\n");
2035 #ifdef DBUS_AUTHENTICATION
2039 _dbus_verbose ("Not reading anything since we just completed the authentication\n");
2043 else if (watch == socket_transport->write_watch &&
2044 (flags & DBUS_WATCH_WRITABLE))
2047 _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n",
2048 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
2050 #ifdef DBUS_AUTHENTICATION
2051 if (!do_authentication (transport, FALSE, TRUE, NULL))
2054 if (!do_writing (transport))
2056 _dbus_verbose ("no memory to write\n");
2060 /* See if we still need the write watch */
2061 check_write_watch (transport);
2063 #ifdef DBUS_ENABLE_VERBOSE_MODE
2066 if (watch == socket_transport->read_watch)
2067 _dbus_verbose ("asked to handle read watch with non-read condition 0x%x\n",
2069 else if (watch == socket_transport->write_watch)
2070 _dbus_verbose ("asked to handle write watch with non-write condition 0x%x\n",
2073 _dbus_verbose ("asked to handle watch %p on fd %d that we don't recognize\n",
2074 watch, dbus_watch_get_socket (watch));
2076 #endif /* DBUS_ENABLE_VERBOSE_MODE */
2082 socket_disconnect (DBusTransport *transport)
2084 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2086 _dbus_verbose ("\n");
2088 free_watches (transport);
2090 _dbus_close_socket (socket_transport->fd, NULL);
2091 socket_transport->fd = -1;
2095 socket_connection_set (DBusTransport *transport)
2097 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2099 _dbus_watch_set_handler (socket_transport->write_watch,
2100 _dbus_connection_handle_watch,
2101 transport->connection, NULL);
2103 _dbus_watch_set_handler (socket_transport->read_watch,
2104 _dbus_connection_handle_watch,
2105 transport->connection, NULL);
2107 if (!_dbus_connection_add_watch_unlocked (transport->connection,
2108 socket_transport->write_watch))
2111 if (!_dbus_connection_add_watch_unlocked (transport->connection,
2112 socket_transport->read_watch))
2114 _dbus_connection_remove_watch_unlocked (transport->connection,
2115 socket_transport->write_watch);
2119 check_read_watch (transport);
2120 check_write_watch (transport);
2126 * @todo We need to have a way to wake up the select sleep if
2127 * a new iteration request comes in with a flag (read/write) that
2128 * we're not currently serving. Otherwise a call that just reads
2129 * could block a write call forever (if there are no incoming
2133 kdbus_do_iteration (DBusTransport *transport,
2135 int timeout_milliseconds)
2137 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2142 _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p fd = %d\n",
2143 flags & DBUS_ITERATION_DO_READING ? "read" : "",
2144 flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
2145 timeout_milliseconds,
2146 socket_transport->read_watch,
2147 socket_transport->write_watch,
2148 socket_transport->fd);
2150 /* the passed in DO_READING/DO_WRITING flags indicate whether to
2151 * read/write messages, but regardless of those we may need to block
2152 * for reading/writing to do auth. But if we do reading for auth,
2153 * we don't want to read any messages yet if not given DO_READING.
2156 poll_fd.fd = socket_transport->fd;
2159 if (_dbus_transport_get_is_authenticated (transport))
2161 /* This is kind of a hack; if we have stuff to write, then try
2162 * to avoid the poll. This is probably about a 5% speedup on an
2163 * echo client/server.
2165 * If both reading and writing were requested, we want to avoid this
2166 * since it could have funky effects:
2167 * - both ends spinning waiting for the other one to read
2168 * data so they can finish writing
2169 * - prioritizing all writing ahead of reading
2171 if ((flags & DBUS_ITERATION_DO_WRITING) &&
2172 !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) &&
2173 !transport->disconnected &&
2174 _dbus_connection_has_messages_to_send_unlocked (transport->connection))
2176 do_writing (transport);
2178 if (transport->disconnected ||
2179 !_dbus_connection_has_messages_to_send_unlocked (transport->connection))
2183 /* If we get here, we decided to do the poll() after all */
2184 _dbus_assert (socket_transport->read_watch);
2185 if (flags & DBUS_ITERATION_DO_READING)
2186 poll_fd.events |= _DBUS_POLLIN;
2188 _dbus_assert (socket_transport->write_watch);
2189 if (flags & DBUS_ITERATION_DO_WRITING)
2190 poll_fd.events |= _DBUS_POLLOUT;
2194 DBusAuthState auth_state;
2196 auth_state = _dbus_auth_do_work (transport->auth);
2198 if (transport->receive_credentials_pending || auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT)
2199 poll_fd.events |= _DBUS_POLLIN;
2201 if (transport->send_credentials_pending || auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND)
2202 poll_fd.events |= _DBUS_POLLOUT;
2207 if (flags & DBUS_ITERATION_BLOCK)
2208 poll_timeout = timeout_milliseconds;
2212 /* For blocking selects we drop the connection lock here
2213 * to avoid blocking out connection access during a potentially
2214 * indefinite blocking call. The io path is still protected
2215 * by the io_path_cond condvar, so we won't reenter this.
2217 if (flags & DBUS_ITERATION_BLOCK)
2219 _dbus_verbose ("unlock pre poll\n");
2220 _dbus_connection_unlock (transport->connection);
2224 poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
2226 if (poll_res < 0 && _dbus_get_is_errno_eintr ())
2228 _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
2232 if (flags & DBUS_ITERATION_BLOCK)
2234 _dbus_verbose ("lock post poll\n");
2235 _dbus_connection_lock (transport->connection);
2241 poll_fd.revents = 0; /* some concern that posix does not guarantee this;
2242 * valgrind flags it as an error. though it probably
2243 * is guaranteed on linux at least.
2246 if (poll_fd.revents & _DBUS_POLLERR)
2247 do_io_error (transport);
2250 dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
2251 dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0;
2252 #ifdef DBUS_AUTHENTICATION
2253 dbus_bool_t authentication_completed;
2256 _dbus_verbose ("in iteration, need_read=%d need_write=%d\n",
2257 need_read, need_write);
2258 #ifdef DBUS_AUTHENTICATION
2259 do_authentication (transport, need_read, need_write,
2260 &authentication_completed);
2262 /* See comment in socket_handle_watch. */
2263 if (authentication_completed)
2266 if (need_read && (flags & DBUS_ITERATION_DO_READING))
2267 do_reading (transport);
2268 if (need_write && (flags & DBUS_ITERATION_DO_WRITING))
2269 do_writing (transport);
2273 _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
2277 /* We need to install the write watch only if we did not
2278 * successfully write everything. Note we need to be careful that we
2279 * don't call check_write_watch *before* do_writing, since it's
2280 * inefficient to add the write watch, and we can avoid it most of
2281 * the time since we can write immediately.
2283 * However, we MUST always call check_write_watch(); DBusConnection code
2284 * relies on the fact that running an iteration will notice that
2285 * messages are pending.
2287 check_write_watch (transport);
2289 _dbus_verbose (" ... leaving do_iteration()\n");
2293 socket_live_messages_changed (DBusTransport *transport)
2295 /* See if we should look for incoming messages again */
2296 check_read_watch (transport);
2299 static const DBusTransportVTable kdbus_vtable = {
2301 socket_handle_watch,
2303 socket_connection_set,
2305 socket_live_messages_changed,
2306 socket_get_socket_fd
2310 * Creates a new transport for the given kdbus file descriptor. The file
2311 * descriptor must be nonblocking.
2313 * @param fd the file descriptor.
2314 * @param address the transport's address
2315 * @returns the new transport, or #NULL if no memory.
2317 static DBusTransport*
2318 _dbus_transport_new_for_socket_kdbus (int fd,
2319 const DBusString *address)
2321 DBusTransportSocket *socket_transport;
2323 socket_transport = dbus_new0 (DBusTransportSocket, 1);
2324 if (socket_transport == NULL)
2327 if (!_dbus_string_init (&socket_transport->encoded_outgoing))
2330 if (!_dbus_string_init (&socket_transport->encoded_incoming))
2333 socket_transport->write_watch = _dbus_watch_new (fd,
2334 DBUS_WATCH_WRITABLE,
2337 if (socket_transport->write_watch == NULL)
2340 socket_transport->read_watch = _dbus_watch_new (fd,
2341 DBUS_WATCH_READABLE,
2344 if (socket_transport->read_watch == NULL)
2347 if (!_dbus_transport_init_base (&socket_transport->base,
2352 #ifdef DBUS_AUTHENTICATION
2353 #ifdef HAVE_UNIX_FD_PASSING
2354 _dbus_auth_set_unix_fd_possible(socket_transport->base.auth, _dbus_socket_can_pass_unix_fd(fd));
2358 socket_transport->fd = fd;
2359 socket_transport->message_bytes_written = 0;
2361 /* These values should probably be tunable or something. */
2362 socket_transport->max_bytes_read_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2363 socket_transport->max_bytes_written_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2365 socket_transport->kdbus_mmap_ptr = NULL;
2366 socket_transport->memfd = -1;
2368 return (DBusTransport*) socket_transport;
2371 _dbus_watch_invalidate (socket_transport->read_watch);
2372 _dbus_watch_unref (socket_transport->read_watch);
2374 _dbus_watch_invalidate (socket_transport->write_watch);
2375 _dbus_watch_unref (socket_transport->write_watch);
2377 _dbus_string_free (&socket_transport->encoded_incoming);
2379 _dbus_string_free (&socket_transport->encoded_outgoing);
2381 dbus_free (socket_transport);
2387 * Opens a connection to the kdbus bus
2389 * This will set FD_CLOEXEC for the socket returned.
2391 * @param path the path to UNIX domain socket
2392 * @param error return location for error code
2393 * @returns connection file descriptor or -1 on error
2395 static int _dbus_connect_kdbus (const char *path, DBusError *error)
2399 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2400 _dbus_verbose ("connecting to kdbus bus %s\n", path);
2402 fd = open(path, O_RDWR|O_CLOEXEC|O_NONBLOCK);
2404 dbus_set_error(error, _dbus_error_from_errno (errno), "Failed to open file descriptor: %s", _dbus_strerror (errno));
2410 * maps memory pool for messages received by the kdbus transport
2412 * @param transport transport
2413 * @returns #TRUE on success, otherwise FALSE
2415 static dbus_bool_t kdbus_mmap(DBusTransport* transport)
2417 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2419 socket_transport->kdbus_mmap_ptr = mmap(NULL, RECEIVE_POOL_SIZE, PROT_READ, MAP_SHARED, socket_transport->fd, 0);
2420 if (socket_transport->kdbus_mmap_ptr == MAP_FAILED)
2427 * Creates a new transport for kdbus.
2428 * This creates a client-side of a transport.
2430 * @param path the path to the bus.
2431 * @param error address where an error can be returned.
2432 * @returns a new transport, or #NULL on failure.
2434 static DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error)
2437 DBusTransport *transport;
2440 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2442 if (!_dbus_string_init (&address))
2444 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2450 if ((!_dbus_string_append (&address, "kdbus:path=")) || (!_dbus_string_append (&address, path)))
2452 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2456 fd = _dbus_connect_kdbus (path, error);
2459 _DBUS_ASSERT_ERROR_IS_SET (error);
2463 _dbus_verbose ("Successfully connected to kdbus bus %s\n", path);
2465 transport = _dbus_transport_new_for_socket_kdbus (fd, &address);
2466 if (transport == NULL)
2468 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2472 _dbus_string_free (&address);
2477 _dbus_close_socket (fd, NULL);
2479 _dbus_string_free (&address);
2485 * Opens kdbus transport if method from address entry is kdbus
2487 * @param entry the address entry to try opening
2488 * @param transport_p return location for the opened transport
2489 * @param error error to be set
2490 * @returns result of the attempt
2492 DBusTransportOpenResult _dbus_transport_open_kdbus(DBusAddressEntry *entry,
2493 DBusTransport **transport_p,
2498 method = dbus_address_entry_get_method (entry);
2499 _dbus_assert (method != NULL);
2501 if (strcmp (method, "kdbus") == 0)
2503 const char *path = dbus_address_entry_get_value (entry, "path");
2507 _dbus_set_bad_address (error, "kdbus", "path", NULL);
2508 return DBUS_TRANSPORT_OPEN_BAD_ADDRESS;
2511 *transport_p = _dbus_transport_new_for_kdbus (path, error);
2513 if (*transport_p == NULL)
2515 _DBUS_ASSERT_ERROR_IS_SET (error);
2516 return DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT;
2520 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2521 return DBUS_TRANSPORT_OPEN_OK;
2526 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2527 return DBUS_TRANSPORT_OPEN_NOT_HANDLED;
2531 static struct kdbus_policy *make_policy_name(const char *name)
2533 struct kdbus_policy *p;
2536 size = offsetof(struct kdbus_policy, name) + strlen(name) + 1;
2542 p->type = KDBUS_POLICY_NAME;
2543 strcpy(p->name, name);
2548 static struct kdbus_policy *make_policy_access(__u64 type, __u64 bits, __u64 id)
2550 struct kdbus_policy *p;
2551 __u64 size = sizeof(*p);
2559 p->type = KDBUS_POLICY_ACCESS;
2560 p->access.type = type;
2561 p->access.bits = bits;
2567 static void append_policy(struct kdbus_cmd_policy *cmd_policy, struct kdbus_policy *policy, __u64 max_size)
2569 struct kdbus_policy *dst = (struct kdbus_policy *) ((char *) cmd_policy + cmd_policy->size);
2571 if (cmd_policy->size + policy->size > max_size)
2574 memcpy(dst, policy, policy->size);
2575 cmd_policy->size += KDBUS_ALIGN8(policy->size);
2580 * Registers kdbus policy for given connection.
2582 * Policy sets rights of the name (unique or well known) on the bus. Without policy it is
2583 * not possible to send or receive messages. It must be set separately for unique id and
2584 * well known name of the connection. It is set after registering on the bus, but before
2585 * requesting for name. The policy is valid for the given name, not for the connection.
2587 * Name of the policy equals name on the bus.
2589 * @param name name of the policy = name of the connection
2590 * @param connection the connection
2591 * @param error place to store errors
2593 * @returns #TRUE on success
2595 dbus_bool_t bus_register_policy_kdbus(const char* name, DBusConnection *connection, DBusError *error)
2597 struct kdbus_cmd_policy *cmd_policy;
2598 struct kdbus_policy *policy;
2602 if(!dbus_connection_get_socket(connection, &fd))
2604 dbus_set_error (error, "Failed to get fd for registering policy", NULL);
2608 cmd_policy = alloca(size);
2609 memset(cmd_policy, 0, size);
2611 policy = (struct kdbus_policy *) cmd_policy->policies;
2612 cmd_policy->size = offsetof(struct kdbus_cmd_policy, policies);
2614 policy = make_policy_name(name);
2615 append_policy(cmd_policy, policy, size);
2617 policy = make_policy_access(KDBUS_POLICY_ACCESS_USER, KDBUS_POLICY_OWN, getuid());
2618 append_policy(cmd_policy, policy, size);
2620 policy = make_policy_access(KDBUS_POLICY_ACCESS_WORLD, KDBUS_POLICY_RECV, 0);
2621 append_policy(cmd_policy, policy, size);
2623 policy = make_policy_access(KDBUS_POLICY_ACCESS_WORLD, KDBUS_POLICY_SEND, 0);
2624 append_policy(cmd_policy, policy, size);
2626 if (ioctl(fd, KDBUS_CMD_EP_POLICY_SET, cmd_policy) < 0)
2628 dbus_set_error(error,_dbus_error_from_errno (errno), "Error setting EP policy: %s", _dbus_strerror (errno));
2632 _dbus_verbose("Policy %s set correctly\n", name);
2637 * Kdbus part of dbus_bus_register.
2638 * Shouldn't be used separately because it needs to be surrounded
2639 * by other functions as it is done in dbus_bus_register.
2641 * @param name place to store unique name given by bus
2642 * @param connection the connection
2643 * @param error place to store errors
2644 * @returns #TRUE on success
2646 dbus_bool_t bus_register_kdbus(char* name, DBusConnection *connection, DBusError *error)
2648 struct kdbus_cmd_hello __attribute__ ((__aligned__(8))) hello;
2651 hello.conn_flags = KDBUS_HELLO_ACCEPT_FD/* |
2652 KDBUS_HELLO_ATTACH_COMM |
2653 KDBUS_HELLO_ATTACH_EXE |
2654 KDBUS_HELLO_ATTACH_CMDLINE |
2655 KDBUS_HELLO_ATTACH_CAPS |
2656 KDBUS_HELLO_ATTACH_CGROUP |
2657 KDBUS_HELLO_ATTACH_SECLABEL |
2658 KDBUS_HELLO_ATTACH_AUDIT*/;
2659 hello.size = sizeof(struct kdbus_cmd_hello);
2660 hello.pool_size = RECEIVE_POOL_SIZE;
2662 if(!dbus_connection_get_socket(connection, &fd))
2664 dbus_set_error (error, "failed to get fd for bus registration", NULL);
2667 if (ioctl(fd, KDBUS_CMD_HELLO, &hello))
2669 dbus_set_error(error,_dbus_error_from_errno (errno), "Failed to send hello: %s", _dbus_strerror (errno));
2673 sprintf(name, "%llu", (unsigned long long)hello.id);
2674 _dbus_verbose("-- Our peer ID is: %s\n", name);
2675 ((DBusTransportSocket*)dbus_connection_get_transport(connection))->bloom_size = hello.bloom_size;
2677 if(!kdbus_mmap(dbus_connection_get_transport(connection)))
2679 dbus_set_error(error,_dbus_error_from_errno (errno), "Error when mmap: %s", _dbus_strerror (errno));
2687 * kdbus version of dbus_bus_request_name.
2689 * Asks the bus to assign the given name to this connection.
2691 * Use same flags as original dbus version with one exception below.
2692 * Result flag #DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER is currently
2693 * never returned by kdbus, instead DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER
2694 * is returned by kdbus.
2696 * @param connection the connection
2697 * @param name the name to request
2698 * @param flags flags
2699 * @param error location to store the error
2700 * @returns a result code, -1 if error is set
2702 int bus_request_name_kdbus(DBusConnection *connection, const char *name, const uint64_t flags, DBusError *error)
2704 struct kdbus_cmd_name *cmd_name;
2706 uint64_t size = sizeof(*cmd_name) + strlen(name) + 1;
2707 uint64_t flags_kdbus = 0;
2709 cmd_name = alloca(size);
2711 memset(cmd_name, 0, size);
2712 strcpy(cmd_name->name, name);
2713 cmd_name->size = size;
2715 if(flags & DBUS_NAME_FLAG_ALLOW_REPLACEMENT)
2716 flags_kdbus |= KDBUS_NAME_ALLOW_REPLACEMENT;
2717 if(!(flags & DBUS_NAME_FLAG_DO_NOT_QUEUE))
2718 flags_kdbus |= KDBUS_NAME_QUEUE;
2719 if(flags & DBUS_NAME_FLAG_REPLACE_EXISTING)
2720 flags_kdbus |= KDBUS_NAME_REPLACE_EXISTING;
2722 cmd_name->conn_flags = flags_kdbus;
2724 if(!dbus_connection_get_socket(connection, &fd))
2726 dbus_set_error (error, "failed to get fd for name request", NULL);
2730 _dbus_verbose("Request name - flags sent: 0x%llx !!!!!!!!!\n", cmd_name->conn_flags);
2732 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2733 if (ioctl(fd, KDBUS_CMD_NAME_ACQUIRE, cmd_name))
2735 dbus_set_error(error,_dbus_error_from_errno (errno), "error acquiring name: %s", _dbus_strerror (errno));
2737 return DBUS_REQUEST_NAME_REPLY_EXISTS;
2741 _dbus_verbose("Request name - received flag: 0x%llx !!!!!!!!!\n", cmd_name->conn_flags);
2743 if(cmd_name->conn_flags & KDBUS_NAME_IN_QUEUE)
2744 return DBUS_REQUEST_NAME_REPLY_IN_QUEUE;
2746 return DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER;
2747 /*todo now 1 code is never returned - DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER
2748 * because kdbus never returns it now
2753 * Checks if the connection's transport is kdbus on the basis of its address
2755 * @param pointer to the connection
2756 * @returns TRUE if kdbus transport, otherwise FALSE
2758 dbus_bool_t dbus_transport_is_kdbus(DBusConnection *connection)
2760 const char* address = _dbus_connection_get_address(connection);
2763 if(address == strstr(address, "kdbus:path="))
2769 * Seeks key in rule string, and duplicates value of the key into pValue.
2770 * If value is "org.freedesktop.DBus" it is indicated by returning -1, because it
2771 * needs to be handled in different manner.
2772 * Value is duplicated from rule string to newly allocated memory pointe by pValue,
2773 * so it must be freed after use.
2775 * @param rule rule to look through
2776 * @param key key to look for
2777 * @param pValue pointer to value of the key found
2778 * @return length of the value string, 0 means not found, -1 means "org.freedesktop.DBus"
2780 static int parse_match_key(const char *rule, const char* key, char** pValue)
2783 const char* pValueEnd;
2784 int value_length = 0;
2786 pBegin = strstr(rule, key);
2789 pBegin += strlen(key);
2790 pValueEnd = strchr(pBegin, '\'');
2793 value_length = pValueEnd - pBegin;
2794 *pValue = strndup(pBegin, value_length);
2797 if(strcmp(*pValue, "org.freedesktop.DBus") == 0)
2799 _dbus_verbose ("found for key: %s value:'%s'\n", key, *pValue);
2803 return value_length;
2807 * Adds a match rule to match broadcast messages going through the message bus.
2808 * Do no affect messages addressed directly.
2810 * The "rule" argument is the string form of a match rule.
2812 * In kdbus function do not blocks.
2814 * Upper function returns nothing because of blocking issues
2815 * so there is no point to return true or false here.
2817 * Only part of the dbus's matching capabilities is implemented in kdbus now, because of different mechanism.
2819 * interface match key mapped to bloom
2820 * sender match key mapped to src_name
2821 * also handled org.freedesktop.dbus members: NameOwnerChanged, NameLost, NameAcquired
2823 * @param connection connection to the message bus
2824 * @param rule textual form of match rule
2825 * @param error location to store any errors - may be NULL
2827 void dbus_bus_add_match_kdbus (DBusConnection *connection, const char *rule, DBusError *error)
2829 struct kdbus_cmd_match* pCmd_match;
2830 struct kdbus_item *pItem;
2832 __u64 src_id = KDBUS_MATCH_SRC_ID_ANY;
2834 unsigned int kernel_item = 0;
2837 char* pInterface = NULL;
2838 __u64 bloom_size = ((DBusTransportSocket*)dbus_connection_get_transport(connection))->bloom_size;
2840 dbus_connection_get_socket(connection, &fd);
2842 /*parsing rule and calculating size of command*/
2843 size = sizeof(struct kdbus_cmd_match);
2845 if(strstr(rule, "member='NameOwnerChanged'"))
2847 kernel_item = KDBUS_MATCH_NAME_CHANGE;
2848 size += KDBUS_ITEM_SIZE(1);
2850 else if(strstr(rule, "member='NameLost'"))
2852 kernel_item = KDBUS_MATCH_NAME_REMOVE;
2853 size += KDBUS_ITEM_SIZE(1);
2855 else if(strstr(rule, "member='NameAcquired'"))
2857 kernel_item = KDBUS_MATCH_NAME_ADD;
2858 size += KDBUS_ITEM_SIZE(1);
2861 name_size = parse_match_key(rule, "interface='", &pInterface);
2862 if((name_size == -1) && (kernel_item == 0)) //means org.freedesktop.DBus without specified member
2865 size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2; /* 3 above name related items plus 2 id related items*/
2867 else if(name_size > 0) /*actual size is not important for interface because bloom size is defined by bus*/
2868 size += KDBUS_PART_HEADER_SIZE + bloom_size;
2870 name_size = parse_match_key(rule, "sender='", &pName);
2871 if((name_size == -1) && (kernel_item == 0)) //means org.freedesktop.DBus without specified name - same as interface few line above
2874 size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2; /* 3 above name related items plus 2 id related items*/
2876 else if(name_size > 0)
2878 if(!strncmp(pName, ":1.", 3)) /*if name is unique name it must be converted to unique id*/
2880 src_id = strtoull(&pName[3], NULL, 10);
2885 size += KDBUS_ITEM_SIZE(name_size + 1); //well known name
2888 pCmd_match = alloca(size);
2889 if(pCmd_match == NULL)
2893 pCmd_match->size = size;
2894 pCmd_match->cookie = strtoull(dbus_bus_get_unique_name(connection), NULL , 10);
2896 pItem = pCmd_match->items;
2897 if(kernel_item == ~0) //all signals from kernel
2899 pCmd_match->src_id = 0;
2900 pItem->type = KDBUS_MATCH_NAME_CHANGE;
2901 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2902 pItem = KDBUS_PART_NEXT(pItem);
2903 pItem->type = KDBUS_MATCH_NAME_ADD;
2904 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2905 pItem = KDBUS_PART_NEXT(pItem);
2906 pItem->type = KDBUS_MATCH_NAME_REMOVE;
2907 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2908 pItem = KDBUS_PART_NEXT(pItem);
2909 pItem->type = KDBUS_MATCH_ID_ADD;
2910 pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64);
2911 pItem = KDBUS_PART_NEXT(pItem);
2912 pItem->type = KDBUS_MATCH_ID_REMOVE;
2913 pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64);
2915 else if(kernel_item) //only one item
2917 pCmd_match->src_id = 0;
2918 pItem->type = kernel_item;
2919 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2923 pCmd_match->src_id = src_id;
2926 pItem->type = KDBUS_MATCH_SRC_NAME;
2927 pItem->size = KDBUS_PART_HEADER_SIZE + name_size + 1;
2928 strcpy(pItem->str, pName);
2929 pItem = KDBUS_PART_NEXT(pItem);
2934 pItem->type = KDBUS_MATCH_BLOOM;
2935 pItem->size = KDBUS_PART_HEADER_SIZE + bloom_size;
2936 strncpy(pItem->data, pInterface, bloom_size);
2940 if(ioctl(fd, KDBUS_CMD_MATCH_ADD, pCmd_match))
2943 dbus_set_error(error,_dbus_error_from_errno (errno), "error adding match: %s", _dbus_strerror (errno));
2944 _dbus_verbose("Failed adding match bus rule %s,\nerror: %d, %m\n", rule, errno);
2947 _dbus_verbose("Added match bus rule %s\n", rule);
2957 * Opposing to dbus, in kdbus removes all match rules with given
2958 * cookie, which now is equal to uniqe id.
2960 * In kdbus this function will not block
2962 * @param connection connection to the message bus
2963 * @param error location to store any errors - may be NULL
2965 void dbus_bus_remove_match_kdbus (DBusConnection *connection, DBusError *error)
2967 struct kdbus_cmd_match __attribute__ ((__aligned__(8))) cmd;
2970 dbus_connection_get_socket(connection, &fd);
2971 cmd.cookie = strtoull(dbus_bus_get_unique_name(connection), NULL , 10);
2972 cmd.id = cmd.cookie;
2973 cmd.size = sizeof(struct kdbus_cmd_match);
2975 if(ioctl(fd, KDBUS_CMD_MATCH_ADD, &cmd))
2978 dbus_set_error(error,_dbus_error_from_errno (errno), "error removing match: %s", _dbus_strerror (errno));
2979 _dbus_verbose("Failed removing match rule; error: %d, %m\n", errno);
2982 _dbus_verbose("Match rule removed correctly.\n");