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)) \
57 * Opaque object representing a socket file descriptor transport.
59 typedef struct DBusTransportSocket DBusTransportSocket;
62 * Implementation details of DBusTransportSocket. All members are private.
64 struct DBusTransportSocket
66 DBusTransport base; /**< Parent instance */
67 int fd; /**< File descriptor. */
68 DBusWatch *read_watch; /**< Watch for readability. */
69 DBusWatch *write_watch; /**< Watch for writability. */
71 int max_bytes_read_per_iteration; /**< In kdbus only to control overall message size*/
72 int max_bytes_written_per_iteration; /**< In kdbus only to control overall message size*/
74 int message_bytes_written; /**< Number of bytes of current
75 * outgoing message that have
78 DBusString encoded_outgoing; /**< Encoded version of current
81 DBusString encoded_incoming; /**< Encoded version of current
84 void* kdbus_mmap_ptr; /**< Mapped memory where Kdbus (kernel) writes
85 * messages incoming to us.
87 int memfd; /**< File descriptor to special
88 * memory pool for bulk data
89 * transfer. Retrieved from
90 * Kdbus kernel module.
92 __u64 bloom_size; /**< bloom filter field size */
96 socket_get_socket_fd (DBusTransport *transport,
99 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
101 *fd_p = socket_transport->fd;
107 * Adds locally generated message to received messages queue
110 static dbus_bool_t add_message_to_received(DBusMessage *message, DBusConnection* connection)
112 DBusList *message_link;
114 message_link = _dbus_list_alloc_link (message);
115 if (message_link == NULL)
117 dbus_message_unref (message);
121 _dbus_connection_queue_synthesized_message_link(connection, message_link);
126 static dbus_bool_t reply_with_error(char* error_type, const char* template, const char* object, DBusMessage *message, DBusConnection* connection)
128 DBusMessage *errMessage;
129 char* error_msg = "";
133 error_msg = alloca(strlen(template) + strlen(object));
134 sprintf(error_msg, template, object);
137 error_msg = (char*)object;
139 errMessage = generate_local_error_message(dbus_message_get_serial(message), error_type, error_msg);
140 if(errMessage == NULL)
142 if (add_message_to_received(errMessage, connection))
148 static dbus_bool_t reply_1_data(DBusMessage *message, int data_type, void* pData, DBusConnection* connection)
150 DBusMessageIter args;
153 reply = dbus_message_new_method_return(message);
156 dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
157 dbus_message_iter_init_append(reply, &args);
158 if (!dbus_message_iter_append_basic(&args, data_type, pData))
160 dbus_message_unref(reply);
163 if(add_message_to_received(reply, connection))
170 * Retrieves file descriptor to memory pool from kdbus module.
171 * It is then used for bulk data sending.
172 * Triggered when message payload is over MEMFD_SIZE_THRESHOLD
175 static int kdbus_init_memfd(DBusTransportSocket* socket_transport)
179 if (ioctl(socket_transport->fd, KDBUS_CMD_MEMFD_NEW, &memfd) < 0) {
180 _dbus_verbose("KDBUS_CMD_MEMFD_NEW failed: \n");
184 socket_transport->memfd = memfd;
185 _dbus_verbose("kdbus_init_memfd: %d!!\n", socket_transport->memfd);
190 * Initiates Kdbus message structure.
191 * Calculates it's size, allocates memory and fills some fields.
192 * @param name Well-known name or NULL
193 * @param dst_id Numeric id of recipient
194 * @param body_size size of message body if present
195 * @param use_memfd flag to build memfd message
196 * @param fds_count number of file descriptors used
197 * @param transport transport
198 * @return initialized kdbus message
200 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)
202 struct kdbus_msg* msg;
205 msg_size = sizeof(struct kdbus_msg);
207 if(use_memfd == TRUE) // bulk data - memfd - encoded and plain
208 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_memfd));
210 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
212 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
216 msg_size += KDBUS_ITEM_SIZE(sizeof(int)*fds_count);
219 msg_size += KDBUS_ITEM_SIZE(strlen(name) + 1);
220 else if (dst_id == KDBUS_DST_ID_BROADCAST)
221 msg_size += KDBUS_PART_HEADER_SIZE + transport->bloom_size;
223 msg = malloc(msg_size);
226 _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
230 memset(msg, 0, msg_size);
231 msg->size = msg_size;
232 msg->payload_type = KDBUS_PAYLOAD_DBUS1;
233 msg->dst_id = name ? 0 : dst_id;
234 msg->src_id = strtoull(dbus_bus_get_unique_name(transport->base.connection), NULL , 10);
240 * Builds and sends kdbus message using Dbus message.
241 * Decide whether used payload vector or memfd memory pool.
242 * Handles broadcasts and unicast messages, and passing of Unix fds.
243 * Does error handling.
244 * TODO refactor to be more compact
246 * @param transport transport
247 * @param message DBus message to be sent
248 * @param encoded flag if the message is encoded
249 * @return size of data sent
251 static int kdbus_write_msg(DBusTransportSocket *transport, DBusMessage *message, dbus_bool_t encoded)
253 struct kdbus_msg *msg;
254 struct kdbus_item *item;
256 uint64_t dst_id = KDBUS_DST_ID_BROADCAST;
257 const DBusString *header;
258 const DBusString *body;
259 uint64_t ret_size = 0;
260 uint64_t body_size = 0;
261 uint64_t header_size = 0;
262 dbus_bool_t use_memfd;
265 dbus_bool_t autostart;
267 // determine name and destination id
268 if((name = dbus_message_get_destination(message)))
270 dst_id = KDBUS_DST_ID_WELL_KNOWN_NAME;
271 if((name[0] == ':') && (name[1] == '1') && (name[2] == '.')) /* if name starts with ":1." it is a unique name and should be send as number */
273 dst_id = strtoull(&name[3], NULL, 10);
280 ret_size = _dbus_string_get_length (&transport->encoded_outgoing);
283 _dbus_message_get_network_data (message, &header, &body);
284 header_size = _dbus_string_get_length(header);
285 body_size = _dbus_string_get_length(body);
286 ret_size = header_size + body_size;
289 // check if message size is big enough to use memfd kdbus transport
290 use_memfd = ret_size > MEMFD_SIZE_THRESHOLD ? TRUE : FALSE;
291 if(use_memfd) kdbus_init_memfd(transport);
293 _dbus_message_get_unix_fds(message, &unix_fds, &fds_count);
295 // init basic message fields
296 msg = kdbus_init_msg(name, dst_id, body_size, use_memfd, fds_count, transport);
297 msg->cookie = dbus_message_get_serial(message);
298 autostart = dbus_message_get_auto_start (message);
300 msg->flags |= KDBUS_MSG_FLAGS_NO_AUTO_START;
302 // build message contents
305 // case 1 - bulk data transfer - memfd - encoded and plain
310 if(ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 0) < 0)
312 _dbus_verbose("memfd sealing failed: \n");
316 buf = mmap(NULL, ret_size, PROT_WRITE, MAP_SHARED, transport->memfd, 0);
317 if (buf == MAP_FAILED)
319 _dbus_verbose("mmap() fd=%i failed:%m", transport->memfd);
324 memcpy(buf, &transport->encoded_outgoing, ret_size);
327 memcpy(buf, _dbus_string_get_const_data(header), header_size);
330 memcpy(buf, _dbus_string_get_const_data(body), body_size);
335 munmap(buf, ret_size);
337 // seal data - kdbus module needs it
338 if(ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 1) < 0) {
339 _dbus_verbose("memfd sealing failed: %d (%m)\n", errno);
344 item->type = KDBUS_MSG_PAYLOAD_MEMFD;
345 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_memfd);
346 item->memfd.size = ret_size;
347 item->memfd.fd = transport->memfd;
348 // case 2 - small encoded - don't use memfd
350 _dbus_verbose("sending encoded data\n");
352 item->type = KDBUS_MSG_PAYLOAD_VEC;
353 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec);
354 item->vec.address = (unsigned long) &transport->encoded_outgoing;
355 item->vec.size = _dbus_string_get_length (&transport->encoded_outgoing);
357 // case 3 - small not encoded - don't use memfd
359 _dbus_verbose("sending normal vector data\n");
361 item->type = KDBUS_MSG_PAYLOAD_VEC;
362 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec);
363 item->vec.address = (unsigned long) _dbus_string_get_const_data(header);
364 item->vec.size = header_size;
368 _dbus_verbose("body attaching\n");
369 item = KDBUS_PART_NEXT(item);
370 item->type = KDBUS_MSG_PAYLOAD_VEC;
371 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec);
372 item->vec.address = (unsigned long) _dbus_string_get_const_data(body);
373 item->vec.size = body_size;
379 item = KDBUS_PART_NEXT(item);
380 item->type = KDBUS_MSG_FDS;
381 item->size = KDBUS_PART_HEADER_SIZE + (sizeof(int) * fds_count);
382 memcpy(item->fds, unix_fds, sizeof(int) * fds_count);
387 item = KDBUS_PART_NEXT(item);
388 item->type = KDBUS_MSG_DST_NAME;
389 item->size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1;
390 strcpy(item->str, name);
392 else if (dst_id == KDBUS_DST_ID_BROADCAST)
394 item = KDBUS_PART_NEXT(item);
395 item->type = KDBUS_MSG_BLOOM;
396 item->size = KDBUS_PART_HEADER_SIZE + transport->bloom_size;
397 strncpy(item->data, dbus_message_get_interface(message), transport->bloom_size);
401 if (ioctl(transport->fd, KDBUS_CMD_MSG_SEND, msg))
405 if((errno == ESRCH) || (errno == ENXIO) || (errno = EADDRNOTAVAIL)) //when recipient is not available on the bus
409 //todo start service here, otherwise
410 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))
414 if(reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Name \"%s\" does not exist", dbus_message_get_destination(message), message, transport->base.connection))
418 _dbus_verbose("kdbus error sending message: err %d (%m)\n", errno);
423 close(transport->memfd);
438 * Performs kdbus query of id of the given name
440 * @param name name to query for
442 * @param ownerID place to store id of the name
443 * @return 0 on success, -errno if failed
445 static int kdbus_NameQuery(char* name, int fd, struct nameInfo* pInfo)
447 struct kdbus_cmd_name_info *msg;
448 struct kdbus_item *item;
453 pInfo->sec_label_len = 0;
454 pInfo->sec_label = NULL;
456 item_size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1;
457 item_size = (item_size < 56) ? 56 : item_size; //at least 56 bytes are needed by kernel to place info about name, otherwise error
458 size = sizeof(struct kdbus_cmd_name_info) + item_size;
463 _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
467 memset(msg, 0, size);
469 if((name[0] == ':') && (name[1] == '1') && (name[2] == '.')) /* if name starts with ":1." it is a unique name and should be send as number */
470 msg->id = strtoull(&name[3], NULL, 10);
475 item->type = KDBUS_NAME_INFO_ITEM_NAME;
476 item->size = item_size;
477 strcpy(item->str, name);
480 ret = ioctl(fd, KDBUS_CMD_NAME_QUERY, msg);
485 else if(ret == -ENOBUFS)
487 msg = realloc(msg, msg->size); //prepare memory
496 pInfo->uniqueId = msg->id;
497 pInfo->userId = msg->creds.uid;
498 pInfo->processId = msg->creds.pid;
499 _dbus_verbose ("I'm alive 1\n");
501 while((uint8_t *)(item) < (uint8_t *)(msg) + msg->size)
503 if(item->type == KDBUS_NAME_INFO_ITEM_SECLABEL)
505 pInfo->sec_label_len = item->size - KDBUS_PART_HEADER_SIZE - 1;
506 if(pInfo->sec_label_len != 0)
507 pInfo->sec_label = malloc(pInfo->sec_label_len);
508 if(pInfo->sec_label == NULL)
511 memcpy(pInfo->sec_label, item->data, pInfo->sec_label_len);
515 item = KDBUS_PART_NEXT(item);
524 * Handles messages sent to bus daemon - "org.freedesktop.DBus" and translates them to appropriate
525 * kdbus ioctl commands. Than translate kdbus reply into dbus message and put it into recived messages queue.
527 * !!! Not all methods are handled !!! Doubt if it is even possible.
528 * If method is not handled, returns error reply org.freedesktop.DBus.Error.UnknownMethod
535 * Not handled methods:
536 * - ListActivatableNames
537 * - StartServiceByName
538 * - UpdateActivationEnvironment
539 * - GetConnectionUnixUser
542 static dbus_bool_t emulateOrgFreedesktopDBus(DBusTransport *transport, DBusMessage *message)
545 struct nameInfo info;
546 dbus_bool_t ret_value;
548 if(!strcmp(dbus_message_get_member(message), "GetNameOwner")) //returns id of the well known name
552 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
553 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
554 if(inter_ret == 0) //unique id of the name
556 char unique_name[(unsigned int)(snprintf(name, 0, "%llu", ULLONG_MAX) + sizeof(":1."))];
557 const char* pString = unique_name;
559 sprintf(unique_name, ":1.%llu", (unsigned long long int)info.uniqueId);
560 _dbus_verbose("Unique name discovered:%s\n", unique_name);
561 ret_value = reply_1_data(message, DBUS_TYPE_STRING, &pString, transport->connection);
563 else if(inter_ret == -ENOENT) //name has no owner
564 return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get owner of name '%s': no such name", name, message, transport->connection);
567 _dbus_verbose("kdbus error sending name query: err %d (%m)\n", errno);
568 ret_value = reply_with_error(DBUS_ERROR_FAILED, "Could not determine unique name for '%s'", name, message, transport->connection);
571 else if(!strcmp(dbus_message_get_member(message), "NameHasOwner")) //returns if name is currently registered on the bus
576 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
577 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
578 if((inter_ret == 0) || (inter_ret == -ENOENT))
580 result = (inter_ret == 0) ? TRUE : FALSE;
581 ret_value = reply_1_data(message, DBUS_TYPE_BOOLEAN, &result, transport->connection);
585 _dbus_verbose("kdbus error checking if name exists: err %d (%m)\n", errno);
586 ret_value = reply_with_error(DBUS_ERROR_FAILED, "Could not determine whether name '%s' exists", name, message, transport->connection);
589 else if(!strcmp(dbus_message_get_member(message), "GetConnectionUnixUser"))
593 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
594 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
595 if(inter_ret == 0) //name found
597 _dbus_verbose("User id:%llu\n", (unsigned long long) info.userId);
598 ret_value = reply_1_data(message, DBUS_TYPE_UINT32, &info.userId, transport->connection);
600 else if(inter_ret == -ENOENT) //name has no owner
601 return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get UID of name '%s': no such name", name, message, transport->connection);
604 _dbus_verbose("kdbus error determining UID: err %d (%m)\n", errno);
605 ret_value = reply_with_error(DBUS_ERROR_FAILED, "Could not determine UID for '%s'", name, message, transport->connection);
608 else if(!strcmp(dbus_message_get_member(message), "GetConnectionUnixProcessID"))
612 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
613 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
614 if(inter_ret == 0) //name found
615 ret_value = reply_1_data(message, DBUS_TYPE_UINT32, &info.processId, transport->connection);
616 else if(inter_ret == -ENOENT) //name has no owner
617 return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get PID of name '%s': no such name", name, message, transport->connection);
620 _dbus_verbose("kdbus error determining PID: err %d (%m)\n", errno);
621 ret_value = reply_with_error(DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN,"Could not determine PID for '%s'", name, message, transport->connection);
624 else if(!strcmp(dbus_message_get_member(message), "ListNames")) //return all well known names on he bus
626 struct kdbus_cmd_names* pCmd;
629 cmd_size = sizeof(struct kdbus_cmd_names) + KDBUS_ITEM_SIZE(1);
630 pCmd = malloc(cmd_size);
633 pCmd->size = cmd_size;
637 if(ioctl(((DBusTransportSocket*)transport)->fd, KDBUS_CMD_NAME_LIST, pCmd))
641 if(errno == ENOBUFS) //buffer to small to put all names into it
642 cmd_size = pCmd->size; //here kernel tells how much memory it needs
645 _dbus_verbose("kdbus error asking for name list: err %d (%m)\n",errno);
649 if(cmd_size) //kernel needs more memory
651 pCmd = realloc(pCmd, cmd_size); //prepare memory
654 goto again; //and try again
659 DBusMessageIter args;
660 struct kdbus_cmd_name* pCmd_name;
663 reply = dbus_message_new_method_return(message);
666 dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
667 dbus_message_iter_init_append(reply, &args);
669 for (pCmd_name = pCmd->names; (uint8_t *)(pCmd_name) < (uint8_t *)(pCmd) + pCmd->size; pCmd_name = KDBUS_PART_NEXT(pCmd_name))
671 pName = pCmd_name->name;
672 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pName))
674 dbus_message_unref(reply);
679 if(add_message_to_received(reply, transport->connection))
690 else if(!strcmp(dbus_message_get_member(message), "GetId"))
693 char uuid[DBUS_UUID_LENGTH_BYTES];
696 DBusString binary, encoded;
699 path = &transport->address[11]; //start of kdbus bus path
700 if(stat(path, &stats) < -1)
702 _dbus_verbose("kdbus error reading stats of bus: err %d (%m)\n", errno);
703 return reply_with_error(DBUS_ERROR_FAILED, "Could not determine bus '%s' uuid", path, message, transport->connection);
707 MD5_Update(&md5, path, strlen(path));
708 MD5_Update(&md5, &stats.st_ctim.tv_sec, sizeof(stats.st_ctim.tv_sec));
709 MD5_Final(uuid, &md5);
711 if(!_dbus_string_init (&encoded))
713 _dbus_string_init_const_len (&binary, uuid, DBUS_UUID_LENGTH_BYTES);
714 if(!_dbus_string_hex_encode (&binary, 0, &encoded, _dbus_string_get_length (&encoded)))
716 path = (char*)_dbus_string_get_const_data (&encoded);
717 ret_value = reply_1_data(message, DBUS_TYPE_STRING, &path, transport->connection);
720 _dbus_string_free(&binary);
721 _dbus_string_free(&encoded);
725 else if(!strcmp(dbus_message_get_member(message), "GetAdtAuditSessionData"))
729 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
730 return reply_with_error(DBUS_ERROR_ADT_AUDIT_DATA_UNKNOWN, "Could not determine audit session data for '%s'", name, message, transport->connection);
732 else if(!strcmp(dbus_message_get_member(message), "GetConnectionSELinuxSecurityContext"))
736 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
737 inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
738 if(inter_ret == -ENOENT) //name has no owner
739 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);
740 else if(inter_ret < 0)
741 return reply_with_error(DBUS_ERROR_SELINUX_SECURITY_CONTEXT_UNKNOWN, "Could not determine security context for '%s'", name, message, transport->connection);
747 reply = dbus_message_new_method_return(message);
750 dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
751 if (!dbus_message_append_args (reply, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &info.sec_label, info.sec_label_len, DBUS_TYPE_INVALID))
752 dbus_message_unref(reply);
753 else if(add_message_to_received(reply, transport->connection))
759 return reply_with_error(DBUS_ERROR_UNKNOWN_METHOD, NULL, (char*)dbus_message_get_member(message), message, transport->connection);
760 /* else if(!strcmp(dbus_message_get_member(message), "ListActivatableNames")) //todo
764 else if(!strcmp(dbus_message_get_member(message), "StartServiceByName"))
768 else if(!strcmp(dbus_message_get_member(message), "UpdateActivationEnvironment"))
772 else if(!strcmp(dbus_message_get_member(message), "ReloadConfig"))
779 free(info.sec_label);
783 #if KDBUS_MSG_DECODE_DEBUG == 1
784 static char *msg_id(uint64_t id, char *buf)
790 sprintf(buf, "%llu", (unsigned long long)id);
794 struct kdbus_enum_table {
798 #define _STRINGIFY(x) #x
799 #define STRINGIFY(x) _STRINGIFY(x)
800 #define ELEMENTSOF(x) (sizeof(x)/sizeof((x)[0]))
801 #define TABLE(what) static struct kdbus_enum_table kdbus_table_##what[]
802 #define ENUM(_id) { .id=_id, .name=STRINGIFY(_id) }
803 #define LOOKUP(what) \
804 const char *enum_##what(long long id) { \
806 for (i = 0; i < ELEMENTSOF(kdbus_table_##what); i++) \
807 if (id == kdbus_table_##what[i].id) \
808 return kdbus_table_##what[i].name; \
811 const char *enum_MSG(long long id);
813 ENUM(_KDBUS_MSG_NULL),
814 ENUM(KDBUS_MSG_PAYLOAD_VEC),
815 ENUM(KDBUS_MSG_PAYLOAD_OFF),
816 ENUM(KDBUS_MSG_PAYLOAD_MEMFD),
818 ENUM(KDBUS_MSG_BLOOM),
819 ENUM(KDBUS_MSG_DST_NAME),
820 ENUM(KDBUS_MSG_SRC_CREDS),
821 ENUM(KDBUS_MSG_SRC_PID_COMM),
822 ENUM(KDBUS_MSG_SRC_TID_COMM),
823 ENUM(KDBUS_MSG_SRC_EXE),
824 ENUM(KDBUS_MSG_SRC_CMDLINE),
825 ENUM(KDBUS_MSG_SRC_CGROUP),
826 ENUM(KDBUS_MSG_SRC_CAPS),
827 ENUM(KDBUS_MSG_SRC_SECLABEL),
828 ENUM(KDBUS_MSG_SRC_AUDIT),
829 ENUM(KDBUS_MSG_SRC_NAMES),
830 ENUM(KDBUS_MSG_TIMESTAMP),
831 ENUM(KDBUS_MSG_NAME_ADD),
832 ENUM(KDBUS_MSG_NAME_REMOVE),
833 ENUM(KDBUS_MSG_NAME_CHANGE),
834 ENUM(KDBUS_MSG_ID_ADD),
835 ENUM(KDBUS_MSG_ID_REMOVE),
836 ENUM(KDBUS_MSG_REPLY_TIMEOUT),
837 ENUM(KDBUS_MSG_REPLY_DEAD),
840 const char *enum_PAYLOAD(long long id);
842 ENUM(KDBUS_PAYLOAD_KERNEL),
843 ENUM(KDBUS_PAYLOAD_DBUS1),
844 ENUM(KDBUS_PAYLOAD_GVARIANT),
849 * Puts locally generated message into received data buffer.
850 * Use only during receiving phase!
852 * @param message message to load
853 * @param data place to load message
854 * @return size of message
856 static int put_message_into_data(DBusMessage *message, char* data)
859 const DBusString *header;
860 const DBusString *body;
863 dbus_message_lock (message);
864 _dbus_message_get_network_data (message, &header, &body);
865 ret_size = _dbus_string_get_length(header);
866 memcpy(data, _dbus_string_get_const_data(header), ret_size);
868 size = _dbus_string_get_length(body);
869 memcpy(data, _dbus_string_get_const_data(body), size);
871 dbus_message_unref(message);
876 * Decodes kdbus message in order to extract dbus message and put it into data and fds.
877 * Also captures and decodes kdbus error messages and kdbus kernel broadcasts and converts
878 * all of them into dbus messages.
880 * @param msg kdbus message
881 * @param data place to copy dbus message to
882 * @param socket_transport transport
883 * @param fds place to store file descriptors received
884 * @param n_fds place to store quantity of file descriptor
885 * @return number of dbus message's bytes received or -1 on error
887 static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTransportSocket* socket_transport, int* fds, int* n_fds)
889 const struct kdbus_item *item;
891 DBusMessage *message = NULL;
892 DBusMessageIter args;
893 const char* emptyString = "";
894 const char* pString = NULL;
895 char dbus_name[(unsigned int)(snprintf((char*)pString, 0, "%llu", ULLONG_MAX) + sizeof(":1."))];
896 const char* pDBusName = dbus_name;
897 #if KDBUS_MSG_DECODE_DEBUG == 1
901 #if KDBUS_MSG_DECODE_DEBUG == 1
902 _dbus_verbose("MESSAGE: %s (%llu bytes) flags=0x%llx, %s → %s, cookie=%llu, timeout=%llu\n",
903 enum_PAYLOAD(msg->payload_type), (unsigned long long) msg->size,
904 (unsigned long long) msg->flags,
905 msg_id(msg->src_id, buf), msg_id(msg->dst_id, buf),
906 (unsigned long long) msg->cookie, (unsigned long long) msg->timeout_ns);
911 KDBUS_PART_FOREACH(item, msg, items)
913 if (item->size <= KDBUS_PART_HEADER_SIZE)
915 _dbus_verbose(" +%s (%llu bytes) invalid data record\n", enum_MSG(item->type), item->size);
916 break; //??? continue (because dbus will find error) or break
921 case KDBUS_MSG_PAYLOAD_OFF:
922 memcpy(data, (char *)socket_transport->kdbus_mmap_ptr + item->vec.offset, item->vec.size);
923 data += item->vec.size;
924 ret_size += item->vec.size;
926 _dbus_verbose(" +%s (%llu bytes) off=%llu size=%llu\n",
927 enum_MSG(item->type), item->size,
928 (unsigned long long)item->vec.offset,
929 (unsigned long long)item->vec.size);
932 case KDBUS_MSG_PAYLOAD_MEMFD:
937 size = item->memfd.size;
938 _dbus_verbose("memfd.size : %llu\n", (unsigned long long)size);
940 buf = mmap(NULL, size, PROT_READ , MAP_SHARED, item->memfd.fd, 0);
941 if (buf == MAP_FAILED)
943 _dbus_verbose("mmap() fd=%i failed:%m", item->memfd.fd);
947 memcpy(data, buf, size);
953 _dbus_verbose(" +%s (%llu bytes) off=%llu size=%llu\n",
954 enum_MSG(item->type), item->size,
955 (unsigned long long)item->vec.offset,
956 (unsigned long long)item->vec.size);
964 *n_fds = (item->size - KDBUS_PART_HEADER_SIZE) / sizeof(int);
965 memcpy(fds, item->fds, *n_fds * sizeof(int));
966 for (i = 0; i < *n_fds; i++)
967 _dbus_fd_set_close_on_exec(fds[i]);
971 #if KDBUS_MSG_DECODE_DEBUG == 1
972 case KDBUS_MSG_SRC_CREDS:
973 _dbus_verbose(" +%s (%llu bytes) uid=%lld, gid=%lld, pid=%lld, tid=%lld, starttime=%lld\n",
974 enum_MSG(item->type), item->size,
975 item->creds.uid, item->creds.gid,
976 item->creds.pid, item->creds.tid,
977 item->creds.starttime);
980 case KDBUS_MSG_SRC_PID_COMM:
981 case KDBUS_MSG_SRC_TID_COMM:
982 case KDBUS_MSG_SRC_EXE:
983 case KDBUS_MSG_SRC_CGROUP:
984 case KDBUS_MSG_SRC_SECLABEL:
985 case KDBUS_MSG_DST_NAME:
986 _dbus_verbose(" +%s (%llu bytes) '%s' (%zu)\n",
987 enum_MSG(item->type), item->size, item->str, strlen(item->str));
990 case KDBUS_MSG_SRC_CMDLINE:
991 case KDBUS_MSG_SRC_NAMES: {
992 __u64 size = item->size - KDBUS_PART_HEADER_SIZE;
993 const char *str = item->str;
996 _dbus_verbose(" +%s (%llu bytes) ", enum_MSG(item->type), item->size);
998 _dbus_verbose("'%s' ", str);
999 size -= strlen(str) + 1;
1000 str += strlen(str) + 1;
1004 _dbus_verbose("(%d string%s)\n", count, (count == 1) ? "" : "s");
1008 case KDBUS_MSG_SRC_AUDIT:
1009 _dbus_verbose(" +%s (%llu bytes) loginuid=%llu sessionid=%llu\n",
1010 enum_MSG(item->type), item->size,
1011 (unsigned long long)item->data64[0],
1012 (unsigned long long)item->data64[1]);
1015 case KDBUS_MSG_SRC_CAPS: {
1017 const uint32_t *cap;
1020 _dbus_verbose(" +%s (%llu bytes) len=%llu bytes)\n",
1021 enum_MSG(item->type), item->size,
1022 (unsigned long long)item->size - KDBUS_PART_HEADER_SIZE);
1025 n = (item->size - KDBUS_PART_HEADER_SIZE) / 4 / sizeof(uint32_t);
1027 _dbus_verbose(" CapInh=");
1028 for (i = 0; i < n; i++)
1029 _dbus_verbose("%08x", cap[(0 * n) + (n - i - 1)]);
1031 _dbus_verbose(" CapPrm=");
1032 for (i = 0; i < n; i++)
1033 _dbus_verbose("%08x", cap[(1 * n) + (n - i - 1)]);
1035 _dbus_verbose(" CapEff=");
1036 for (i = 0; i < n; i++)
1037 _dbus_verbose("%08x", cap[(2 * n) + (n - i - 1)]);
1039 _dbus_verbose(" CapInh=");
1040 for (i = 0; i < n; i++)
1041 _dbus_verbose("%08x", cap[(3 * n) + (n - i - 1)]);
1042 _dbus_verbose("\n");
1046 case KDBUS_MSG_TIMESTAMP:
1047 _dbus_verbose(" +%s (%llu bytes) realtime=%lluns monotonic=%lluns\n",
1048 enum_MSG(item->type), item->size,
1049 (unsigned long long)item->timestamp.realtime_ns,
1050 (unsigned long long)item->timestamp.monotonic_ns);
1054 case KDBUS_MSG_REPLY_TIMEOUT:
1055 _dbus_verbose(" +%s (%llu bytes) cookie=%llu\n",
1056 enum_MSG(item->type), item->size, msg->cookie_reply);
1058 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NO_REPLY, NULL);
1065 ret_size = put_message_into_data(message, data);
1068 case KDBUS_MSG_REPLY_DEAD:
1069 _dbus_verbose(" +%s (%llu bytes) cookie=%llu\n",
1070 enum_MSG(item->type), item->size, msg->cookie_reply);
1072 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NAME_HAS_NO_OWNER, NULL);
1079 ret_size = put_message_into_data(message, data);
1082 case KDBUS_MSG_NAME_ADD:
1083 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1084 enum_MSG(item->type), (unsigned long long) item->size,
1085 item->name_change.name, item->name_change.old_id,
1086 item->name_change.new_id, item->name_change.flags);
1088 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1095 sprintf(dbus_name,":1.%llu",item->name_change.new_id);
1096 pString = item->name_change.name;
1097 _dbus_verbose ("Name added: %s\n", pString);
1098 dbus_message_iter_init_append(message, &args);
1099 ITER_APPEND_STR(pString)
1100 ITER_APPEND_STR(emptyString)
1101 ITER_APPEND_STR(pDBusName)
1102 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1104 ret_size = put_message_into_data(message, data);
1107 case KDBUS_MSG_NAME_REMOVE:
1108 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1109 enum_MSG(item->type), (unsigned long long) item->size,
1110 item->name_change.name, item->name_change.old_id,
1111 item->name_change.new_id, item->name_change.flags);
1113 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged"); // name of the signal
1120 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
1121 pString = item->name_change.name;
1122 _dbus_verbose ("Name removed: %s\n", pString);
1123 dbus_message_iter_init_append(message, &args);
1124 ITER_APPEND_STR(pString)
1125 ITER_APPEND_STR(pDBusName)
1126 ITER_APPEND_STR(emptyString)
1127 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1129 ret_size = put_message_into_data(message, data);
1132 case KDBUS_MSG_NAME_CHANGE:
1133 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
1134 enum_MSG(item->type), (unsigned long long) item->size,
1135 item->name_change.name, item->name_change.old_id,
1136 item->name_change.new_id, item->name_change.flags);
1138 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1145 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
1146 pString = item->name_change.name;
1147 _dbus_verbose ("Name changed: %s\n", pString);
1148 dbus_message_iter_init_append(message, &args);
1149 ITER_APPEND_STR(pString)
1150 ITER_APPEND_STR(pDBusName)
1151 sprintf(&dbus_name[3],"%llu",item->name_change.new_id);
1152 _dbus_verbose ("New id: %s\n", pDBusName);
1153 ITER_APPEND_STR(pDBusName)
1154 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1156 ret_size = put_message_into_data(message, data);
1159 case KDBUS_MSG_ID_ADD:
1160 _dbus_verbose(" +%s (%llu bytes) id=%llu flags=%llu\n",
1161 enum_MSG(item->type), (unsigned long long) item->size,
1162 (unsigned long long) item->id_change.id,
1163 (unsigned long long) item->id_change.flags);
1165 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1172 sprintf(dbus_name,":1.%llu",item->id_change.id);
1173 dbus_message_iter_init_append(message, &args);
1174 ITER_APPEND_STR(pDBusName)
1175 ITER_APPEND_STR(emptyString)
1176 ITER_APPEND_STR(pDBusName)
1177 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1179 ret_size = put_message_into_data(message, data);
1182 case KDBUS_MSG_ID_REMOVE:
1183 _dbus_verbose(" +%s (%llu bytes) id=%llu flags=%llu\n",
1184 enum_MSG(item->type), (unsigned long long) item->size,
1185 (unsigned long long) item->id_change.id,
1186 (unsigned long long) item->id_change.flags);
1188 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
1195 sprintf(dbus_name,":1.%llu",item->id_change.id);
1196 dbus_message_iter_init_append(message, &args);
1197 ITER_APPEND_STR(pDBusName)
1198 ITER_APPEND_STR(pDBusName)
1199 ITER_APPEND_STR(emptyString)
1200 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1202 ret_size = put_message_into_data(message, data);
1204 #if KDBUS_MSG_DECODE_DEBUG == 1
1206 _dbus_verbose(" +%s (%llu bytes)\n", enum_MSG(item->type), item->size);
1212 #if KDBUS_MSG_DECODE_DEBUG == 1
1214 if ((char *)item - ((char *)msg + msg->size) >= 8)
1215 _dbus_verbose("invalid padding at end of message\n");
1220 dbus_message_unref(message);
1225 * Reads message from kdbus and puts it into dbus buffer and fds
1227 * @param transport transport
1228 * @param buffer place to copy received message to
1229 * @param fds place to store file descriptors sent in the message
1230 * @param n_fds place to store number of file descriptors
1231 * @return size of received message on success, -1 on error
1233 static int kdbus_read_message(DBusTransportSocket *socket_transport, DBusString *buffer, int* fds, int* n_fds)
1236 uint64_t __attribute__ ((__aligned__(8))) offset;
1237 struct kdbus_msg *msg;
1241 start = _dbus_string_get_length (buffer);
1242 if (!_dbus_string_lengthen (buffer, socket_transport->max_bytes_read_per_iteration))
1247 data = _dbus_string_get_data_len (buffer, start, socket_transport->max_bytes_read_per_iteration);
1250 if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RECV, &offset) < 0)
1254 _dbus_verbose("kdbus error receiving message: %d (%m)\n", errno);
1255 _dbus_string_set_length (buffer, start);
1259 msg = (struct kdbus_msg *)((char*)socket_transport->kdbus_mmap_ptr + offset);
1261 ret_size = kdbus_decode_msg(msg, data, socket_transport, fds, n_fds);
1263 if(ret_size == -1) /* error */
1265 _dbus_string_set_length (buffer, start);
1269 _dbus_string_set_length (buffer, start + ret_size);
1273 if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RELEASE, &offset) < 0)
1277 _dbus_verbose("kdbus error freeing message: %d (%m)\n", errno);
1285 free_watches (DBusTransport *transport)
1287 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1289 _dbus_verbose ("start\n");
1291 if (socket_transport->read_watch)
1293 if (transport->connection)
1294 _dbus_connection_remove_watch_unlocked (transport->connection,
1295 socket_transport->read_watch);
1296 _dbus_watch_invalidate (socket_transport->read_watch);
1297 _dbus_watch_unref (socket_transport->read_watch);
1298 socket_transport->read_watch = NULL;
1301 if (socket_transport->write_watch)
1303 if (transport->connection)
1304 _dbus_connection_remove_watch_unlocked (transport->connection,
1305 socket_transport->write_watch);
1306 _dbus_watch_invalidate (socket_transport->write_watch);
1307 _dbus_watch_unref (socket_transport->write_watch);
1308 socket_transport->write_watch = NULL;
1311 _dbus_verbose ("end\n");
1315 socket_finalize (DBusTransport *transport)
1317 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1319 _dbus_verbose ("\n");
1321 free_watches (transport);
1323 _dbus_string_free (&socket_transport->encoded_outgoing);
1324 _dbus_string_free (&socket_transport->encoded_incoming);
1326 _dbus_transport_finalize_base (transport);
1328 _dbus_assert (socket_transport->read_watch == NULL);
1329 _dbus_assert (socket_transport->write_watch == NULL);
1331 dbus_free (transport);
1335 check_write_watch (DBusTransport *transport)
1337 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1340 if (transport->connection == NULL)
1343 if (transport->disconnected)
1345 _dbus_assert (socket_transport->write_watch == NULL);
1349 _dbus_transport_ref (transport);
1351 #ifdef DBUS_AUTHENTICATION
1352 if (_dbus_transport_get_is_authenticated (transport))
1354 needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection);
1355 #ifdef DBUS_AUTHENTICATION
1358 if (transport->send_credentials_pending)
1362 DBusAuthState auth_state;
1364 auth_state = _dbus_auth_do_work (transport->auth);
1366 /* If we need memory we install the write watch just in case,
1367 * if there's no need for it, it will get de-installed
1368 * next time we try reading.
1370 if (auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND ||
1371 auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY)
1378 _dbus_verbose ("check_write_watch(): needed = %d on connection %p watch %p fd = %d outgoing messages exist %d\n",
1379 needed, transport->connection, socket_transport->write_watch,
1380 socket_transport->fd,
1381 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1383 _dbus_connection_toggle_watch_unlocked (transport->connection,
1384 socket_transport->write_watch,
1387 _dbus_transport_unref (transport);
1391 check_read_watch (DBusTransport *transport)
1393 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1394 dbus_bool_t need_read_watch;
1396 _dbus_verbose ("fd = %d\n",socket_transport->fd);
1398 if (transport->connection == NULL)
1401 if (transport->disconnected)
1403 _dbus_assert (socket_transport->read_watch == NULL);
1407 _dbus_transport_ref (transport);
1409 #ifdef DBUS_AUTHENTICATION
1410 if (_dbus_transport_get_is_authenticated (transport))
1413 (_dbus_counter_get_size_value (transport->live_messages) < transport->max_live_messages_size) &&
1414 (_dbus_counter_get_unix_fd_value (transport->live_messages) < transport->max_live_messages_unix_fds);
1415 #ifdef DBUS_AUTHENTICATION
1418 if (transport->receive_credentials_pending)
1419 need_read_watch = TRUE;
1422 /* The reason to disable need_read_watch when not WAITING_FOR_INPUT
1423 * is to avoid spinning on the file descriptor when we're waiting
1424 * to write or for some other part of the auth process
1426 DBusAuthState auth_state;
1428 auth_state = _dbus_auth_do_work (transport->auth);
1430 /* If we need memory we install the read watch just in case,
1431 * if there's no need for it, it will get de-installed
1432 * next time we try reading. If we're authenticated we
1433 * install it since we normally have it installed while
1436 if (auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT ||
1437 auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY ||
1438 auth_state == DBUS_AUTH_STATE_AUTHENTICATED)
1439 need_read_watch = TRUE;
1441 need_read_watch = FALSE;
1446 _dbus_verbose (" setting read watch enabled = %d\n", need_read_watch);
1447 _dbus_connection_toggle_watch_unlocked (transport->connection,
1448 socket_transport->read_watch,
1451 _dbus_transport_unref (transport);
1455 do_io_error (DBusTransport *transport)
1457 _dbus_transport_ref (transport);
1458 _dbus_transport_disconnect (transport);
1459 _dbus_transport_unref (transport);
1462 #ifdef DBUS_AUTHENTICATION
1463 /* return value is whether we successfully read any new data. */
1465 read_data_into_auth (DBusTransport *transport,
1468 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1474 _dbus_auth_get_buffer (transport->auth, &buffer);
1476 bytes_read = kdbus_read_message(socket_transport, buffer);
1478 _dbus_auth_return_buffer (transport->auth, buffer,
1479 bytes_read > 0 ? bytes_read : 0);
1483 _dbus_verbose (" read %d bytes in auth phase\n", bytes_read);
1486 else if (bytes_read < 0)
1488 /* EINTR already handled for us */
1490 if (_dbus_get_is_errno_enomem ())
1494 else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1495 ; /* do nothing, just return FALSE below */
1498 _dbus_verbose ("Error reading from remote app: %s\n",
1499 _dbus_strerror_from_errno ());
1500 do_io_error (transport);
1507 _dbus_assert (bytes_read == 0);
1509 _dbus_verbose ("Disconnected from remote app\n");
1510 do_io_error (transport);
1516 /* Return value is whether we successfully wrote any bytes */
1518 write_data_from_auth (DBusTransport *transport)
1520 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1522 const DBusString *buffer;
1524 if (!_dbus_auth_get_bytes_to_send (transport->auth,
1528 bytes_written = _dbus_write_socket (socket_transport->fd,
1530 0, _dbus_string_get_length (buffer));
1532 if (bytes_written > 0)
1534 _dbus_auth_bytes_sent (transport->auth, bytes_written);
1537 else if (bytes_written < 0)
1539 /* EINTR already handled for us */
1541 if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1545 _dbus_verbose ("Error writing to remote app: %s\n",
1546 _dbus_strerror_from_errno ());
1547 do_io_error (transport);
1556 exchange_credentials (DBusTransport *transport,
1557 dbus_bool_t do_reading,
1558 dbus_bool_t do_writing)
1560 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1561 DBusError error = DBUS_ERROR_INIT;
1563 _dbus_verbose ("exchange_credentials: do_reading = %d, do_writing = %d\n",
1564 do_reading, do_writing);
1566 if (do_writing && transport->send_credentials_pending)
1568 if (_dbus_send_credentials_socket (socket_transport->fd,
1571 transport->send_credentials_pending = FALSE;
1575 _dbus_verbose ("Failed to write credentials: %s\n", error.message);
1576 dbus_error_free (&error);
1577 do_io_error (transport);
1581 if (do_reading && transport->receive_credentials_pending)
1583 /* FIXME this can fail due to IO error _or_ OOM, broken
1584 * (somewhat tricky to fix since the OOM error can be set after
1585 * we already read the credentials byte, so basically we need to
1586 * separate reading the byte and storing it in the
1587 * transport->credentials). Does not really matter for now
1588 * because storing in credentials never actually fails on unix.
1590 if (_dbus_read_credentials_socket (socket_transport->fd,
1591 transport->credentials,
1594 transport->receive_credentials_pending = FALSE;
1598 _dbus_verbose ("Failed to read credentials %s\n", error.message);
1599 dbus_error_free (&error);
1600 do_io_error (transport);
1604 if (!(transport->send_credentials_pending ||
1605 transport->receive_credentials_pending))
1607 if (!_dbus_auth_set_credentials (transport->auth,
1608 transport->credentials))
1616 do_authentication (DBusTransport *transport,
1617 dbus_bool_t do_reading,
1618 dbus_bool_t do_writing,
1619 dbus_bool_t *auth_completed)
1622 dbus_bool_t orig_auth_state;
1626 orig_auth_state = _dbus_transport_get_is_authenticated (transport);
1628 /* This is essential to avoid the check_write_watch() at the end,
1629 * we don't want to add a write watch in do_iteration before
1630 * we try writing and get EAGAIN
1632 if (orig_auth_state)
1635 *auth_completed = FALSE;
1639 _dbus_transport_ref (transport);
1641 while (!_dbus_transport_get_is_authenticated (transport) &&
1642 _dbus_transport_get_is_connected (transport))
1644 if (!exchange_credentials (transport, do_reading, do_writing))
1650 if (transport->send_credentials_pending ||
1651 transport->receive_credentials_pending)
1653 _dbus_verbose ("send_credentials_pending = %d receive_credentials_pending = %d\n",
1654 transport->send_credentials_pending,
1655 transport->receive_credentials_pending);
1659 #define TRANSPORT_SIDE(t) ((t)->is_server ? "server" : "client")
1660 switch (_dbus_auth_do_work (transport->auth))
1662 case DBUS_AUTH_STATE_WAITING_FOR_INPUT:
1663 _dbus_verbose (" %s auth state: waiting for input\n",
1664 TRANSPORT_SIDE (transport));
1665 if (!do_reading || !read_data_into_auth (transport, &oom))
1669 case DBUS_AUTH_STATE_WAITING_FOR_MEMORY:
1670 _dbus_verbose (" %s auth state: waiting for memory\n",
1671 TRANSPORT_SIDE (transport));
1676 case DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND:
1677 _dbus_verbose (" %s auth state: bytes to send\n",
1678 TRANSPORT_SIDE (transport));
1679 if (!do_writing || !write_data_from_auth (transport))
1683 case DBUS_AUTH_STATE_NEED_DISCONNECT:
1684 _dbus_verbose (" %s auth state: need to disconnect\n",
1685 TRANSPORT_SIDE (transport));
1686 do_io_error (transport);
1689 case DBUS_AUTH_STATE_AUTHENTICATED:
1690 _dbus_verbose (" %s auth state: authenticated\n",
1691 TRANSPORT_SIDE (transport));
1698 *auth_completed = (orig_auth_state != _dbus_transport_get_is_authenticated (transport));
1700 check_read_watch (transport);
1701 check_write_watch (transport);
1702 _dbus_transport_unref (transport);
1711 /* returns false on oom */
1713 do_writing (DBusTransport *transport)
1715 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1718 #ifdef DBUS_AUTHENTICATION
1719 /* No messages without authentication! */
1720 if (!_dbus_transport_get_is_authenticated (transport))
1722 _dbus_verbose ("Not authenticated, not writing anything\n");
1727 if (transport->disconnected)
1729 _dbus_verbose ("Not connected, not writing anything\n");
1734 _dbus_verbose ("do_writing(), have_messages = %d, fd = %d\n",
1735 _dbus_connection_has_messages_to_send_unlocked (transport->connection),
1736 socket_transport->fd);
1741 while (!transport->disconnected && _dbus_connection_has_messages_to_send_unlocked (transport->connection))
1744 DBusMessage *message;
1745 const DBusString *header;
1746 const DBusString *body;
1747 int total_bytes_to_write;
1748 const char* pDestination;
1750 message = _dbus_connection_get_message_to_send (transport->connection);
1751 _dbus_assert (message != NULL);
1752 dbus_message_lock (message);
1753 _dbus_message_get_network_data (message, &header, &body);
1754 total_bytes_to_write = _dbus_string_get_length(header) + _dbus_string_get_length(body);
1755 pDestination = dbus_message_get_destination(message);
1759 if(!strcmp(pDestination, "org.freedesktop.DBus"))
1761 if(emulateOrgFreedesktopDBus(transport, message))
1762 bytes_written = total_bytes_to_write;
1768 if (_dbus_auth_needs_encoding (transport->auth))
1770 if (_dbus_string_get_length (&socket_transport->encoded_outgoing) == 0)
1772 if (!_dbus_auth_encode_data (transport->auth,
1773 header, &socket_transport->encoded_outgoing))
1779 if (!_dbus_auth_encode_data (transport->auth,
1780 body, &socket_transport->encoded_outgoing))
1782 _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
1788 total_bytes_to_write = _dbus_string_get_length (&socket_transport->encoded_outgoing);
1789 if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration)
1792 bytes_written = kdbus_write_msg(socket_transport, message, TRUE);
1796 if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration)
1799 bytes_written = kdbus_write_msg(socket_transport, message, FALSE);
1803 if (bytes_written < 0)
1805 /* EINTR already handled for us */
1807 /* For some discussion of why we also ignore EPIPE here, see
1808 * http://lists.freedesktop.org/archives/dbus/2008-March/009526.html
1811 if (_dbus_get_is_errno_eagain_or_ewouldblock () || _dbus_get_is_errno_epipe ())
1815 _dbus_verbose ("Error writing to remote app: %s\n", _dbus_strerror_from_errno ());
1816 do_io_error (transport);
1822 _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
1823 total_bytes_to_write);
1825 socket_transport->message_bytes_written += bytes_written;
1827 _dbus_assert (socket_transport->message_bytes_written <=
1828 total_bytes_to_write);
1830 if (socket_transport->message_bytes_written == total_bytes_to_write)
1832 socket_transport->message_bytes_written = 0;
1833 _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
1834 _dbus_string_compact (&socket_transport->encoded_outgoing, 2048);
1836 _dbus_connection_message_sent_unlocked (transport->connection,
1848 /* returns false on out-of-memory */
1850 do_reading (DBusTransport *transport)
1852 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1855 dbus_bool_t oom = FALSE;
1858 _dbus_verbose ("fd = %d\n",socket_transport->fd);
1860 #ifdef DBUS_AUTHENTICATION
1861 /* No messages without authentication! */
1862 if (!_dbus_transport_get_is_authenticated (transport))
1868 /* See if we've exceeded max messages and need to disable reading */
1869 check_read_watch (transport);
1871 _dbus_assert (socket_transport->read_watch != NULL ||
1872 transport->disconnected);
1874 if (transport->disconnected)
1877 if (!dbus_watch_get_enabled (socket_transport->read_watch))
1880 if (!_dbus_message_loader_get_unix_fds(transport->loader, &fds, &n_fds))
1882 _dbus_verbose ("Out of memory reading file descriptors\n");
1886 _dbus_message_loader_get_buffer (transport->loader, &buffer);
1888 if (_dbus_auth_needs_decoding (transport->auth))
1890 bytes_read = kdbus_read_message(socket_transport, &socket_transport->encoded_incoming, fds, &n_fds);
1892 _dbus_assert (_dbus_string_get_length (&socket_transport->encoded_incoming) == bytes_read);
1896 if (!_dbus_auth_decode_data (transport->auth,
1897 &socket_transport->encoded_incoming,
1900 _dbus_verbose ("Out of memory decoding incoming data\n");
1901 _dbus_message_loader_return_buffer (transport->loader,
1903 _dbus_string_get_length (buffer));
1908 _dbus_string_set_length (&socket_transport->encoded_incoming, 0);
1909 _dbus_string_compact (&socket_transport->encoded_incoming, 2048);
1913 bytes_read = kdbus_read_message(socket_transport, buffer, fds, &n_fds);
1915 if (bytes_read >= 0 && n_fds > 0)
1916 _dbus_verbose("Read %i unix fds\n", n_fds);
1918 _dbus_message_loader_return_buffer (transport->loader,
1920 bytes_read < 0 ? 0 : bytes_read);
1921 _dbus_message_loader_return_unix_fds(transport->loader, fds, bytes_read < 0 ? 0 : n_fds);
1925 /* EINTR already handled for us */
1927 if (_dbus_get_is_errno_enomem ())
1929 _dbus_verbose ("Out of memory in read()/do_reading()\n");
1933 else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1937 _dbus_verbose ("Error reading from remote app: %s\n",
1938 _dbus_strerror_from_errno ());
1939 do_io_error (transport);
1943 else if (bytes_read == 0)
1945 _dbus_verbose ("Disconnected from remote app\n");
1946 do_io_error (transport);
1951 _dbus_verbose (" read %d bytes\n", bytes_read);
1953 if (!_dbus_transport_queue_messages (transport))
1956 _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
1960 /* Try reading more data until we get EAGAIN and return, or
1961 * exceed max bytes per iteration. If in blocking mode of
1962 * course we'll block instead of returning.
1974 unix_error_with_read_to_come (DBusTransport *itransport,
1978 DBusTransportSocket *transport = (DBusTransportSocket *) itransport;
1980 if (!((flags & DBUS_WATCH_HANGUP) || (flags & DBUS_WATCH_ERROR)))
1983 /* If we have a read watch enabled ...
1984 we -might have data incoming ... => handle the HANGUP there */
1985 if (watch != transport->read_watch && _dbus_watch_get_enabled (transport->read_watch))
1992 socket_handle_watch (DBusTransport *transport,
1996 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1998 _dbus_assert (watch == socket_transport->read_watch ||
1999 watch == socket_transport->write_watch);
2000 _dbus_assert (watch != NULL);
2002 /* If we hit an error here on a write watch, don't disconnect the transport yet because data can
2003 * still be in the buffer and do_reading may need several iteration to read
2004 * it all (because of its max_bytes_read_per_iteration limit).
2006 if (!(flags & DBUS_WATCH_READABLE) && unix_error_with_read_to_come (transport, watch, flags))
2008 _dbus_verbose ("Hang up or error on watch\n");
2009 _dbus_transport_disconnect (transport);
2013 if (watch == socket_transport->read_watch &&
2014 (flags & DBUS_WATCH_READABLE))
2016 #ifdef DBUS_AUTHENTICATION
2017 dbus_bool_t auth_finished;
2020 _dbus_verbose ("handling read watch %p flags = %x\n",
2023 #ifdef DBUS_AUTHENTICATION
2024 if (!do_authentication (transport, TRUE, FALSE, &auth_finished))
2027 /* We don't want to do a read immediately following
2028 * a successful authentication. This is so we
2029 * have a chance to propagate the authentication
2030 * state further up. Specifically, we need to
2031 * process any pending data from the auth object.
2036 if (!do_reading (transport))
2038 _dbus_verbose ("no memory to read\n");
2041 #ifdef DBUS_AUTHENTICATION
2045 _dbus_verbose ("Not reading anything since we just completed the authentication\n");
2049 else if (watch == socket_transport->write_watch &&
2050 (flags & DBUS_WATCH_WRITABLE))
2053 _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n",
2054 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
2056 #ifdef DBUS_AUTHENTICATION
2057 if (!do_authentication (transport, FALSE, TRUE, NULL))
2060 if (!do_writing (transport))
2062 _dbus_verbose ("no memory to write\n");
2066 /* See if we still need the write watch */
2067 check_write_watch (transport);
2069 #ifdef DBUS_ENABLE_VERBOSE_MODE
2072 if (watch == socket_transport->read_watch)
2073 _dbus_verbose ("asked to handle read watch with non-read condition 0x%x\n",
2075 else if (watch == socket_transport->write_watch)
2076 _dbus_verbose ("asked to handle write watch with non-write condition 0x%x\n",
2079 _dbus_verbose ("asked to handle watch %p on fd %d that we don't recognize\n",
2080 watch, dbus_watch_get_socket (watch));
2082 #endif /* DBUS_ENABLE_VERBOSE_MODE */
2088 socket_disconnect (DBusTransport *transport)
2090 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2092 _dbus_verbose ("\n");
2094 free_watches (transport);
2096 _dbus_close_socket (socket_transport->fd, NULL);
2097 socket_transport->fd = -1;
2101 socket_connection_set (DBusTransport *transport)
2103 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2105 _dbus_watch_set_handler (socket_transport->write_watch,
2106 _dbus_connection_handle_watch,
2107 transport->connection, NULL);
2109 _dbus_watch_set_handler (socket_transport->read_watch,
2110 _dbus_connection_handle_watch,
2111 transport->connection, NULL);
2113 if (!_dbus_connection_add_watch_unlocked (transport->connection,
2114 socket_transport->write_watch))
2117 if (!_dbus_connection_add_watch_unlocked (transport->connection,
2118 socket_transport->read_watch))
2120 _dbus_connection_remove_watch_unlocked (transport->connection,
2121 socket_transport->write_watch);
2125 check_read_watch (transport);
2126 check_write_watch (transport);
2132 * @todo We need to have a way to wake up the select sleep if
2133 * a new iteration request comes in with a flag (read/write) that
2134 * we're not currently serving. Otherwise a call that just reads
2135 * could block a write call forever (if there are no incoming
2139 kdbus_do_iteration (DBusTransport *transport,
2141 int timeout_milliseconds)
2143 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2148 _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p fd = %d\n",
2149 flags & DBUS_ITERATION_DO_READING ? "read" : "",
2150 flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
2151 timeout_milliseconds,
2152 socket_transport->read_watch,
2153 socket_transport->write_watch,
2154 socket_transport->fd);
2156 /* the passed in DO_READING/DO_WRITING flags indicate whether to
2157 * read/write messages, but regardless of those we may need to block
2158 * for reading/writing to do auth. But if we do reading for auth,
2159 * we don't want to read any messages yet if not given DO_READING.
2162 poll_fd.fd = socket_transport->fd;
2165 if (_dbus_transport_get_is_authenticated (transport))
2167 /* This is kind of a hack; if we have stuff to write, then try
2168 * to avoid the poll. This is probably about a 5% speedup on an
2169 * echo client/server.
2171 * If both reading and writing were requested, we want to avoid this
2172 * since it could have funky effects:
2173 * - both ends spinning waiting for the other one to read
2174 * data so they can finish writing
2175 * - prioritizing all writing ahead of reading
2177 if ((flags & DBUS_ITERATION_DO_WRITING) &&
2178 !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) &&
2179 !transport->disconnected &&
2180 _dbus_connection_has_messages_to_send_unlocked (transport->connection))
2182 do_writing (transport);
2184 if (transport->disconnected ||
2185 !_dbus_connection_has_messages_to_send_unlocked (transport->connection))
2189 /* If we get here, we decided to do the poll() after all */
2190 _dbus_assert (socket_transport->read_watch);
2191 if (flags & DBUS_ITERATION_DO_READING)
2192 poll_fd.events |= _DBUS_POLLIN;
2194 _dbus_assert (socket_transport->write_watch);
2195 if (flags & DBUS_ITERATION_DO_WRITING)
2196 poll_fd.events |= _DBUS_POLLOUT;
2200 DBusAuthState auth_state;
2202 auth_state = _dbus_auth_do_work (transport->auth);
2204 if (transport->receive_credentials_pending || auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT)
2205 poll_fd.events |= _DBUS_POLLIN;
2207 if (transport->send_credentials_pending || auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND)
2208 poll_fd.events |= _DBUS_POLLOUT;
2213 if (flags & DBUS_ITERATION_BLOCK)
2214 poll_timeout = timeout_milliseconds;
2218 /* For blocking selects we drop the connection lock here
2219 * to avoid blocking out connection access during a potentially
2220 * indefinite blocking call. The io path is still protected
2221 * by the io_path_cond condvar, so we won't reenter this.
2223 if (flags & DBUS_ITERATION_BLOCK)
2225 _dbus_verbose ("unlock pre poll\n");
2226 _dbus_connection_unlock (transport->connection);
2230 poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
2232 if (poll_res < 0 && _dbus_get_is_errno_eintr ())
2234 _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
2238 if (flags & DBUS_ITERATION_BLOCK)
2240 _dbus_verbose ("lock post poll\n");
2241 _dbus_connection_lock (transport->connection);
2247 poll_fd.revents = 0; /* some concern that posix does not guarantee this;
2248 * valgrind flags it as an error. though it probably
2249 * is guaranteed on linux at least.
2252 if (poll_fd.revents & _DBUS_POLLERR)
2253 do_io_error (transport);
2256 dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
2257 dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0;
2258 #ifdef DBUS_AUTHENTICATION
2259 dbus_bool_t authentication_completed;
2262 _dbus_verbose ("in iteration, need_read=%d need_write=%d\n",
2263 need_read, need_write);
2264 #ifdef DBUS_AUTHENTICATION
2265 do_authentication (transport, need_read, need_write,
2266 &authentication_completed);
2268 /* See comment in socket_handle_watch. */
2269 if (authentication_completed)
2272 if (need_read && (flags & DBUS_ITERATION_DO_READING))
2273 do_reading (transport);
2274 if (need_write && (flags & DBUS_ITERATION_DO_WRITING))
2275 do_writing (transport);
2279 _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
2283 /* We need to install the write watch only if we did not
2284 * successfully write everything. Note we need to be careful that we
2285 * don't call check_write_watch *before* do_writing, since it's
2286 * inefficient to add the write watch, and we can avoid it most of
2287 * the time since we can write immediately.
2289 * However, we MUST always call check_write_watch(); DBusConnection code
2290 * relies on the fact that running an iteration will notice that
2291 * messages are pending.
2293 check_write_watch (transport);
2295 _dbus_verbose (" ... leaving do_iteration()\n");
2299 socket_live_messages_changed (DBusTransport *transport)
2301 /* See if we should look for incoming messages again */
2302 check_read_watch (transport);
2305 static const DBusTransportVTable kdbus_vtable = {
2307 socket_handle_watch,
2309 socket_connection_set,
2311 socket_live_messages_changed,
2312 socket_get_socket_fd
2316 * Creates a new transport for the given kdbus file descriptor. The file
2317 * descriptor must be nonblocking.
2319 * @param fd the file descriptor.
2320 * @param address the transport's address
2321 * @returns the new transport, or #NULL if no memory.
2323 static DBusTransport*
2324 _dbus_transport_new_for_socket_kdbus (int fd,
2325 const DBusString *address)
2327 DBusTransportSocket *socket_transport;
2329 socket_transport = dbus_new0 (DBusTransportSocket, 1);
2330 if (socket_transport == NULL)
2333 if (!_dbus_string_init (&socket_transport->encoded_outgoing))
2336 if (!_dbus_string_init (&socket_transport->encoded_incoming))
2339 socket_transport->write_watch = _dbus_watch_new (fd,
2340 DBUS_WATCH_WRITABLE,
2343 if (socket_transport->write_watch == NULL)
2346 socket_transport->read_watch = _dbus_watch_new (fd,
2347 DBUS_WATCH_READABLE,
2350 if (socket_transport->read_watch == NULL)
2353 if (!_dbus_transport_init_base (&socket_transport->base,
2358 #ifdef DBUS_AUTHENTICATION
2359 #ifdef HAVE_UNIX_FD_PASSING
2360 _dbus_auth_set_unix_fd_possible(socket_transport->base.auth, _dbus_socket_can_pass_unix_fd(fd));
2364 socket_transport->fd = fd;
2365 socket_transport->message_bytes_written = 0;
2367 /* These values should probably be tunable or something. */
2368 socket_transport->max_bytes_read_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2369 socket_transport->max_bytes_written_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2371 socket_transport->kdbus_mmap_ptr = NULL;
2372 socket_transport->memfd = -1;
2374 return (DBusTransport*) socket_transport;
2377 _dbus_watch_invalidate (socket_transport->read_watch);
2378 _dbus_watch_unref (socket_transport->read_watch);
2380 _dbus_watch_invalidate (socket_transport->write_watch);
2381 _dbus_watch_unref (socket_transport->write_watch);
2383 _dbus_string_free (&socket_transport->encoded_incoming);
2385 _dbus_string_free (&socket_transport->encoded_outgoing);
2387 dbus_free (socket_transport);
2393 * Opens a connection to the kdbus bus
2395 * This will set FD_CLOEXEC for the socket returned.
2397 * @param path the path to UNIX domain socket
2398 * @param error return location for error code
2399 * @returns connection file descriptor or -1 on error
2401 static int _dbus_connect_kdbus (const char *path, DBusError *error)
2405 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2406 _dbus_verbose ("connecting to kdbus bus %s\n", path);
2408 fd = open(path, O_RDWR|O_CLOEXEC|O_NONBLOCK);
2410 dbus_set_error(error, _dbus_error_from_errno (errno), "Failed to open file descriptor: %s", _dbus_strerror (errno));
2416 * maps memory pool for messages received by the kdbus transport
2418 * @param transport transport
2419 * @returns #TRUE on success, otherwise FALSE
2421 static dbus_bool_t kdbus_mmap(DBusTransport* transport)
2423 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2425 socket_transport->kdbus_mmap_ptr = mmap(NULL, RECEIVE_POOL_SIZE, PROT_READ, MAP_SHARED, socket_transport->fd, 0);
2426 if (socket_transport->kdbus_mmap_ptr == MAP_FAILED)
2433 * Creates a new transport for kdbus.
2434 * This creates a client-side of a transport.
2436 * @param path the path to the bus.
2437 * @param error address where an error can be returned.
2438 * @returns a new transport, or #NULL on failure.
2440 static DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error)
2443 DBusTransport *transport;
2446 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2448 if (!_dbus_string_init (&address))
2450 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2456 if ((!_dbus_string_append (&address, "kdbus:path=")) || (!_dbus_string_append (&address, path)))
2458 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2462 fd = _dbus_connect_kdbus (path, error);
2465 _DBUS_ASSERT_ERROR_IS_SET (error);
2469 _dbus_verbose ("Successfully connected to kdbus bus %s\n", path);
2471 transport = _dbus_transport_new_for_socket_kdbus (fd, &address);
2472 if (transport == NULL)
2474 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2478 _dbus_string_free (&address);
2483 _dbus_close_socket (fd, NULL);
2485 _dbus_string_free (&address);
2491 * Opens kdbus transport if method from address entry is kdbus
2493 * @param entry the address entry to try opening
2494 * @param transport_p return location for the opened transport
2495 * @param error error to be set
2496 * @returns result of the attempt
2498 DBusTransportOpenResult _dbus_transport_open_kdbus(DBusAddressEntry *entry,
2499 DBusTransport **transport_p,
2504 method = dbus_address_entry_get_method (entry);
2505 _dbus_assert (method != NULL);
2507 if (strcmp (method, "kdbus") == 0)
2509 const char *path = dbus_address_entry_get_value (entry, "path");
2513 _dbus_set_bad_address (error, "kdbus", "path", NULL);
2514 return DBUS_TRANSPORT_OPEN_BAD_ADDRESS;
2517 *transport_p = _dbus_transport_new_for_kdbus (path, error);
2519 if (*transport_p == NULL)
2521 _DBUS_ASSERT_ERROR_IS_SET (error);
2522 return DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT;
2526 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2527 return DBUS_TRANSPORT_OPEN_OK;
2532 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2533 return DBUS_TRANSPORT_OPEN_NOT_HANDLED;
2537 static struct kdbus_policy *make_policy_name(const char *name)
2539 struct kdbus_policy *p;
2542 size = offsetof(struct kdbus_policy, name) + strlen(name) + 1;
2548 p->type = KDBUS_POLICY_NAME;
2549 strcpy(p->name, name);
2554 static struct kdbus_policy *make_policy_access(__u64 type, __u64 bits, __u64 id)
2556 struct kdbus_policy *p;
2557 __u64 size = sizeof(*p);
2565 p->type = KDBUS_POLICY_ACCESS;
2566 p->access.type = type;
2567 p->access.bits = bits;
2573 static void append_policy(struct kdbus_cmd_policy *cmd_policy, struct kdbus_policy *policy, __u64 max_size)
2575 struct kdbus_policy *dst = (struct kdbus_policy *) ((char *) cmd_policy + cmd_policy->size);
2577 if (cmd_policy->size + policy->size > max_size)
2580 memcpy(dst, policy, policy->size);
2581 cmd_policy->size += KDBUS_ALIGN8(policy->size);
2586 * Registers kdbus policy for given connection.
2588 * Policy sets rights of the name (unique or well known) on the bus. Without policy it is
2589 * not possible to send or receive messages. It must be set separately for unique id and
2590 * well known name of the connection. It is set after registering on the bus, but before
2591 * requesting for name. The policy is valid for the given name, not for the connection.
2593 * Name of the policy equals name on the bus.
2595 * @param name name of the policy = name of the connection
2596 * @param connection the connection
2597 * @param error place to store errors
2599 * @returns #TRUE on success
2601 dbus_bool_t bus_register_policy_kdbus(const char* name, DBusConnection *connection, DBusError *error)
2603 struct kdbus_cmd_policy *cmd_policy;
2604 struct kdbus_policy *policy;
2608 if(!dbus_connection_get_socket(connection, &fd))
2610 dbus_set_error (error, "Failed to get fd for registering policy", NULL);
2614 cmd_policy = alloca(size);
2615 memset(cmd_policy, 0, size);
2617 policy = (struct kdbus_policy *) cmd_policy->policies;
2618 cmd_policy->size = offsetof(struct kdbus_cmd_policy, policies);
2620 policy = make_policy_name(name);
2621 append_policy(cmd_policy, policy, size);
2623 policy = make_policy_access(KDBUS_POLICY_ACCESS_USER, KDBUS_POLICY_OWN, getuid());
2624 append_policy(cmd_policy, policy, size);
2626 policy = make_policy_access(KDBUS_POLICY_ACCESS_WORLD, KDBUS_POLICY_RECV, 0);
2627 append_policy(cmd_policy, policy, size);
2629 policy = make_policy_access(KDBUS_POLICY_ACCESS_WORLD, KDBUS_POLICY_SEND, 0);
2630 append_policy(cmd_policy, policy, size);
2632 if (ioctl(fd, KDBUS_CMD_EP_POLICY_SET, cmd_policy) < 0)
2634 dbus_set_error(error,_dbus_error_from_errno (errno), "Error setting EP policy: %s", _dbus_strerror (errno));
2638 _dbus_verbose("Policy %s set correctly\n", name);
2643 * Kdbus part of dbus_bus_register.
2644 * Shouldn't be used separately because it needs to be surrounded
2645 * by other functions as it is done in dbus_bus_register.
2647 * @param name place to store unique name given by bus
2648 * @param connection the connection
2649 * @param error place to store errors
2650 * @returns #TRUE on success
2652 dbus_bool_t bus_register_kdbus(char* name, DBusConnection *connection, DBusError *error)
2654 struct kdbus_cmd_hello __attribute__ ((__aligned__(8))) hello;
2657 hello.conn_flags = KDBUS_HELLO_ACCEPT_FD/* |
2658 KDBUS_HELLO_ATTACH_COMM |
2659 KDBUS_HELLO_ATTACH_EXE |
2660 KDBUS_HELLO_ATTACH_CMDLINE |
2661 KDBUS_HELLO_ATTACH_CAPS |
2662 KDBUS_HELLO_ATTACH_CGROUP |
2663 KDBUS_HELLO_ATTACH_SECLABEL |
2664 KDBUS_HELLO_ATTACH_AUDIT*/;
2665 hello.size = sizeof(struct kdbus_cmd_hello);
2666 hello.pool_size = RECEIVE_POOL_SIZE;
2668 if(!dbus_connection_get_socket(connection, &fd))
2670 dbus_set_error (error, "failed to get fd for bus registration", NULL);
2673 if (ioctl(fd, KDBUS_CMD_HELLO, &hello))
2675 dbus_set_error(error,_dbus_error_from_errno (errno), "Failed to send hello: %s", _dbus_strerror (errno));
2679 sprintf(name, "%llu", (unsigned long long)hello.id);
2680 _dbus_verbose("-- Our peer ID is: %s\n", name);
2681 ((DBusTransportSocket*)dbus_connection_get_transport(connection))->bloom_size = hello.bloom_size;
2683 if(!kdbus_mmap(dbus_connection_get_transport(connection)))
2685 dbus_set_error(error,_dbus_error_from_errno (errno), "Error when mmap: %s", _dbus_strerror (errno));
2693 * kdbus version of dbus_bus_request_name.
2695 * Asks the bus to assign the given name to this connection.
2697 * Use same flags as original dbus version with one exception below.
2698 * Result flag #DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER is currently
2699 * never returned by kdbus, instead DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER
2700 * is returned by kdbus.
2702 * @param connection the connection
2703 * @param name the name to request
2704 * @param flags flags
2705 * @param error location to store the error
2706 * @returns a result code, -1 if error is set
2708 int bus_request_name_kdbus(DBusConnection *connection, const char *name, const uint64_t flags, DBusError *error)
2710 struct kdbus_cmd_name *cmd_name;
2712 uint64_t size = sizeof(*cmd_name) + strlen(name) + 1;
2713 uint64_t flags_kdbus = 0;
2715 cmd_name = alloca(size);
2717 memset(cmd_name, 0, size);
2718 strcpy(cmd_name->name, name);
2719 cmd_name->size = size;
2721 if(flags & DBUS_NAME_FLAG_ALLOW_REPLACEMENT)
2722 flags_kdbus |= KDBUS_NAME_ALLOW_REPLACEMENT;
2723 if(!(flags & DBUS_NAME_FLAG_DO_NOT_QUEUE))
2724 flags_kdbus |= KDBUS_NAME_QUEUE;
2725 if(flags & DBUS_NAME_FLAG_REPLACE_EXISTING)
2726 flags_kdbus |= KDBUS_NAME_REPLACE_EXISTING;
2728 cmd_name->conn_flags = flags_kdbus;
2730 if(!dbus_connection_get_socket(connection, &fd))
2732 dbus_set_error (error, "failed to get fd for name request", NULL);
2736 _dbus_verbose("Request name - flags sent: 0x%llx !!!!!!!!!\n", cmd_name->conn_flags);
2738 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2739 if (ioctl(fd, KDBUS_CMD_NAME_ACQUIRE, cmd_name))
2741 dbus_set_error(error,_dbus_error_from_errno (errno), "error acquiring name: %s", _dbus_strerror (errno));
2743 return DBUS_REQUEST_NAME_REPLY_EXISTS;
2747 _dbus_verbose("Request name - received flag: 0x%llx !!!!!!!!!\n", cmd_name->conn_flags);
2749 if(cmd_name->conn_flags & KDBUS_NAME_IN_QUEUE)
2750 return DBUS_REQUEST_NAME_REPLY_IN_QUEUE;
2752 return DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER;
2753 /*todo now 1 code is never returned - DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER
2754 * because kdbus never returns it now
2759 * Checks if the connection's transport is kdbus on the basis of its address
2761 * @param pointer to the connection
2762 * @returns TRUE if kdbus transport, otherwise FALSE
2764 dbus_bool_t dbus_transport_is_kdbus(DBusConnection *connection)
2766 const char* address = _dbus_connection_get_address(connection);
2769 if(address == strstr(address, "kdbus:path="))
2775 * Seeks key in rule string, and duplicates value of the key into pValue.
2776 * If value is "org.freedesktop.DBus" it is indicated by returning -1, because it
2777 * needs to be handled in different manner.
2778 * Value is duplicated from rule string to newly allocated memory pointe by pValue,
2779 * so it must be freed after use.
2781 * @param rule rule to look through
2782 * @param key key to look for
2783 * @param pValue pointer to value of the key found
2784 * @return length of the value string, 0 means not found, -1 means "org.freedesktop.DBus"
2786 static int parse_match_key(const char *rule, const char* key, char** pValue)
2789 const char* pValueEnd;
2790 int value_length = 0;
2792 pBegin = strstr(rule, key);
2795 pBegin += strlen(key);
2796 pValueEnd = strchr(pBegin, '\'');
2799 value_length = pValueEnd - pBegin;
2800 *pValue = strndup(pBegin, value_length);
2803 if(strcmp(*pValue, "org.freedesktop.DBus") == 0)
2805 _dbus_verbose ("found for key: %s value:'%s'\n", key, *pValue);
2809 return value_length;
2813 * Adds a match rule to match broadcast messages going through the message bus.
2814 * Do no affect messages addressed directly.
2816 * The "rule" argument is the string form of a match rule.
2818 * In kdbus function do not blocks.
2820 * Upper function returns nothing because of blocking issues
2821 * so there is no point to return true or false here.
2823 * Only part of the dbus's matching capabilities is implemented in kdbus now, because of different mechanism.
2825 * interface match key mapped to bloom
2826 * sender match key mapped to src_name
2827 * also handled org.freedesktop.dbus members: NameOwnerChanged, NameLost, NameAcquired
2829 * @param connection connection to the message bus
2830 * @param rule textual form of match rule
2831 * @param error location to store any errors - may be NULL
2833 void dbus_bus_add_match_kdbus (DBusConnection *connection, const char *rule, DBusError *error)
2835 struct kdbus_cmd_match* pCmd_match;
2836 struct kdbus_item *pItem;
2838 __u64 src_id = KDBUS_MATCH_SRC_ID_ANY;
2840 unsigned int kernel_item = 0;
2843 char* pInterface = NULL;
2844 __u64 bloom_size = ((DBusTransportSocket*)dbus_connection_get_transport(connection))->bloom_size;
2846 dbus_connection_get_socket(connection, &fd);
2848 /*parsing rule and calculating size of command*/
2849 size = sizeof(struct kdbus_cmd_match);
2851 if(strstr(rule, "member='NameOwnerChanged'"))
2853 kernel_item = KDBUS_MATCH_NAME_CHANGE;
2854 size += KDBUS_ITEM_SIZE(1);
2856 else if(strstr(rule, "member='NameLost'"))
2858 kernel_item = KDBUS_MATCH_NAME_REMOVE;
2859 size += KDBUS_ITEM_SIZE(1);
2861 else if(strstr(rule, "member='NameAcquired'"))
2863 kernel_item = KDBUS_MATCH_NAME_ADD;
2864 size += KDBUS_ITEM_SIZE(1);
2867 name_size = parse_match_key(rule, "interface='", &pInterface);
2868 if((name_size == -1) && (kernel_item == 0)) //means org.freedesktop.DBus without specified member
2871 size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2; /* 3 above name related items plus 2 id related items*/
2873 else if(name_size > 0) /*actual size is not important for interface because bloom size is defined by bus*/
2874 size += KDBUS_PART_HEADER_SIZE + bloom_size;
2876 name_size = parse_match_key(rule, "sender='", &pName);
2877 if((name_size == -1) && (kernel_item == 0)) //means org.freedesktop.DBus without specified name - same as interface few line above
2880 size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2; /* 3 above name related items plus 2 id related items*/
2882 else if(name_size > 0)
2884 if(!strncmp(pName, ":1.", 3)) /*if name is unique name it must be converted to unique id*/
2886 src_id = strtoull(&pName[3], NULL, 10);
2891 size += KDBUS_ITEM_SIZE(name_size + 1); //well known name
2894 pCmd_match = alloca(size);
2895 if(pCmd_match == NULL)
2899 pCmd_match->size = size;
2900 pCmd_match->cookie = strtoull(dbus_bus_get_unique_name(connection), NULL , 10);
2902 pItem = pCmd_match->items;
2903 if(kernel_item == ~0) //all signals from kernel
2905 pCmd_match->src_id = 0;
2906 pItem->type = KDBUS_MATCH_NAME_CHANGE;
2907 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2908 pItem = KDBUS_PART_NEXT(pItem);
2909 pItem->type = KDBUS_MATCH_NAME_ADD;
2910 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2911 pItem = KDBUS_PART_NEXT(pItem);
2912 pItem->type = KDBUS_MATCH_NAME_REMOVE;
2913 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2914 pItem = KDBUS_PART_NEXT(pItem);
2915 pItem->type = KDBUS_MATCH_ID_ADD;
2916 pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64);
2917 pItem = KDBUS_PART_NEXT(pItem);
2918 pItem->type = KDBUS_MATCH_ID_REMOVE;
2919 pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64);
2921 else if(kernel_item) //only one item
2923 pCmd_match->src_id = 0;
2924 pItem->type = kernel_item;
2925 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2929 pCmd_match->src_id = src_id;
2932 pItem->type = KDBUS_MATCH_SRC_NAME;
2933 pItem->size = KDBUS_PART_HEADER_SIZE + name_size + 1;
2934 strcpy(pItem->str, pName);
2935 pItem = KDBUS_PART_NEXT(pItem);
2940 pItem->type = KDBUS_MATCH_BLOOM;
2941 pItem->size = KDBUS_PART_HEADER_SIZE + bloom_size;
2942 strncpy(pItem->data, pInterface, bloom_size);
2946 if(ioctl(fd, KDBUS_CMD_MATCH_ADD, pCmd_match))
2949 dbus_set_error(error,_dbus_error_from_errno (errno), "error adding match: %s", _dbus_strerror (errno));
2950 _dbus_verbose("Failed adding match bus rule %s,\nerror: %d, %m\n", rule, errno);
2953 _dbus_verbose("Added match bus rule %s\n", rule);
2963 * Opposing to dbus, in kdbus removes all match rules with given
2964 * cookie, which now is equal to uniqe id.
2966 * In kdbus this function will not block
2968 * @param connection connection to the message bus
2969 * @param error location to store any errors - may be NULL
2971 void dbus_bus_remove_match_kdbus (DBusConnection *connection, DBusError *error)
2973 struct kdbus_cmd_match __attribute__ ((__aligned__(8))) cmd;
2976 dbus_connection_get_socket(connection, &fd);
2977 cmd.cookie = strtoull(dbus_bus_get_unique_name(connection), NULL , 10);
2978 cmd.id = cmd.cookie;
2979 cmd.size = sizeof(struct kdbus_cmd_match);
2981 if(ioctl(fd, KDBUS_CMD_MATCH_ADD, &cmd))
2984 dbus_set_error(error,_dbus_error_from_errno (errno), "error removing match: %s", _dbus_strerror (errno));
2985 _dbus_verbose("Failed removing match rule; error: %d, %m\n", errno);
2988 _dbus_verbose("Match rule removed correctly.\n");