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 #define KDBUS_ALIGN8(l) (((l) + 7) & ~7)
33 #define KDBUS_PART_HEADER_SIZE offsetof(struct kdbus_item, data)
34 #define KDBUS_ITEM_SIZE(s) KDBUS_ALIGN8((s) + KDBUS_PART_HEADER_SIZE)
36 #define KDBUS_PART_NEXT(part) \
37 (typeof(part))(((uint8_t *)part) + KDBUS_ALIGN8((part)->size))
38 #define KDBUS_PART_FOREACH(part, head, first) \
39 for (part = (head)->first; \
40 (uint8_t *)(part) < (uint8_t *)(head) + (head)->size; \
41 part = KDBUS_PART_NEXT(part))
42 #define RECEIVE_POOL_SIZE (10 * 1024LU * 1024LU)
43 #define MEMFD_SIZE_THRESHOLD (2 * 1024 * 1024LU) // over this memfd is used
45 #define KDBUS_MSG_DECODE_DEBUG 0
49 * Opaque object representing a socket file descriptor transport.
51 typedef struct DBusTransportSocket DBusTransportSocket;
54 * Implementation details of DBusTransportSocket. All members are private.
56 struct DBusTransportSocket
58 DBusTransport base; /**< Parent instance */
59 int fd; /**< File descriptor. */
60 DBusWatch *read_watch; /**< Watch for readability. */
61 DBusWatch *write_watch; /**< Watch for writability. */
63 int max_bytes_read_per_iteration; /**< To avoid blocking too long. */
64 int max_bytes_written_per_iteration; /**< To avoid blocking too long. */
66 int message_bytes_written; /**< Number of bytes of current
67 * outgoing message that have
70 DBusString encoded_outgoing; /**< Encoded version of current
73 DBusString encoded_incoming; /**< Encoded version of current
77 int memfd; /* File descriptor to memory
78 * pool from Kdbus kernel module */
84 socket_get_socket_fd (DBusTransport *transport,
87 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
89 *fd_p = socket_transport->fd;
94 //static void check_read_watch (DBusTransport *transport);
97 * Adds locally generated message to received messages queue
100 static dbus_bool_t add_message_to_received(DBusMessage *message, DBusTransport *transport)
102 DBusList *message_link;
104 message_link = _dbus_list_alloc_link (message);
105 if (message_link == NULL)
107 /* it's OK to unref this, nothing that could have attached a callback
108 * has ever seen it */
109 dbus_message_unref (message);
113 _dbus_connection_queue_synthesized_message_link(transport->connection, message_link);
114 // check_read_watch(transport);
119 /*static void kdbus_debug_print_bytes(struct DBusString *data, int size)
123 fprintf (stderr, "\ndata:\n");
124 for(i=0; i < size; i++)
126 fprintf (stderr, "%02x", _dbus_string_get_byte(data,i));
128 fprintf (stderr, "\nsize: %d, i: %lu\n", size, i);
132 static int kdbus_init_memfd(DBusTransportSocket* socket_transport)
137 if(socket_transport->memfd == -1)
139 ret = ioctl(socket_transport->fd, KDBUS_CMD_MEMFD_NEW, &memfd);
141 _dbus_verbose("KDBUS_CMD_MEMFD_NEW failed: \n");
145 socket_transport->memfd = memfd;
146 _dbus_verbose("kdbus_init_memfd: %d!!\n", socket_transport->memfd);
152 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)
154 struct kdbus_msg* msg;
157 msg_size = sizeof(struct kdbus_msg);
159 if(use_memfd == TRUE) // bulk data - memfd - encoded and plain
160 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_memfd));
162 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
164 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
168 msg_size += KDBUS_ITEM_SIZE(sizeof(int)*fds_count);
171 msg_size += KDBUS_ITEM_SIZE(strlen(name) + 1);
172 else if (dst_id == KDBUS_DST_ID_BROADCAST)
173 msg_size += KDBUS_PART_HEADER_SIZE + KDBUS_BLOOM_SIZE_BYTES;
175 msg = malloc(msg_size);
178 _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
182 memset(msg, 0, msg_size);
183 msg->size = msg_size;
184 msg->payload_type = KDBUS_PAYLOAD_DBUS1;
185 msg->dst_id = name ? 0 : dst_id;
190 static int kdbus_write_msg(DBusTransportSocket *transport, DBusMessage *message, dbus_bool_t encoded)
192 struct kdbus_msg *msg;
193 struct kdbus_item *item;
195 uint64_t dst_id = KDBUS_DST_ID_BROADCAST;
196 const DBusString *header;
197 const DBusString *body;
198 uint64_t ret_size = 0;
199 uint64_t body_size = 0;
200 uint64_t header_size = 0;
202 dbus_bool_t use_memfd;
207 // determine name and destination id
208 if((name = dbus_message_get_destination(message)))
210 dst_id = KDBUS_DST_ID_WELL_KNOWN_NAME;
212 if((name[0] == ':') && (name[1] == '1') && (name[2] == '.')) /* if name starts with ":1." it is a unique name and should be send as number */
214 dst_id = strtoull(&name[3], NULL, 10);
221 ret_size = _dbus_string_get_length (&transport->encoded_outgoing);
224 _dbus_message_get_network_data (message, &header, &body);
225 header_size = _dbus_string_get_length(header);
226 body_size = _dbus_string_get_length(body);
227 ret_size = header_size + body_size;
230 // check if message size is big enough to use memfd kdbus transport
231 use_memfd = ret_size > MEMFD_SIZE_THRESHOLD ? TRUE : FALSE;
232 if(use_memfd) kdbus_init_memfd(transport);
234 _dbus_message_get_unix_fds(message, &unix_fds, &fds_count);
236 // init basic message fields
237 msg = kdbus_init_msg(name, dst_id, body_size, use_memfd, fds_count);
238 msg->cookie = dbus_message_get_serial(message);
239 msg->src_id = strtoull(dbus_bus_get_unique_name(transport->base.connection), NULL , 10);
241 // build message contents
244 // case 1 - bulk data transfer - memfd - encoded and plain
247 ret = ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 0);
250 _dbus_verbose("memfd sealing failed: \n");
254 buf = mmap(NULL, ret_size, PROT_WRITE, MAP_SHARED, transport->memfd, 0);
255 if (buf == MAP_FAILED)
257 _dbus_verbose("mmap() fd=%i failed:%m", transport->memfd);
262 memcpy(buf, &transport->encoded_outgoing, ret_size);
265 memcpy(buf, _dbus_string_get_const_data(header), header_size);
268 memcpy(buf, _dbus_string_get_const_data(body), body_size);
273 munmap(buf, ret_size);
275 // seal data - kdbus module needs it
276 ret = ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 1);
278 _dbus_verbose("memfd sealing failed: %d (%m)\n", errno);
283 item->type = KDBUS_MSG_PAYLOAD_MEMFD;
284 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_memfd);
285 item->memfd.size = ret_size;
286 item->memfd.fd = transport->memfd;
287 // case 2 - small encoded - don't use memfd
289 _dbus_verbose("sending encoded data\n");
291 item->type = KDBUS_MSG_PAYLOAD_VEC;
292 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec);
293 item->vec.address = (unsigned long) &transport->encoded_outgoing;
294 item->vec.size = _dbus_string_get_length (&transport->encoded_outgoing);
296 // case 3 - small not encoded - don't use memfd
298 _dbus_verbose("sending normal vector data\n");
300 item->type = KDBUS_MSG_PAYLOAD_VEC;
301 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec);
302 item->vec.address = (unsigned long) _dbus_string_get_const_data(header);
303 item->vec.size = header_size;
307 _dbus_verbose("body attaching\n");
308 item = KDBUS_PART_NEXT(item);
309 item->type = KDBUS_MSG_PAYLOAD_VEC;
310 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec);
311 item->vec.address = (unsigned long) _dbus_string_get_const_data(body);
312 item->vec.size = body_size;
318 item = KDBUS_PART_NEXT(item);
319 item->type = KDBUS_MSG_FDS;
320 item->size = KDBUS_PART_HEADER_SIZE + (sizeof(int) * fds_count);
321 memcpy(item->fds, unix_fds, sizeof(int) * fds_count);
326 item = KDBUS_PART_NEXT(item);
327 item->type = KDBUS_MSG_DST_NAME;
328 item->size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1;
329 strcpy(item->str, name);
331 else if (dst_id == KDBUS_DST_ID_BROADCAST)
333 item = KDBUS_PART_NEXT(item);
334 item->type = KDBUS_MSG_BLOOM;
335 item->size = KDBUS_PART_HEADER_SIZE + KDBUS_BLOOM_SIZE_BYTES;
336 strncpy(item->data, dbus_message_get_interface(message), KDBUS_BLOOM_SIZE_BYTES);
340 if (ioctl(transport->fd, KDBUS_CMD_MSG_SEND, msg))
344 if((errno == ESRCH) || (errno == ENXIO)) //when recipient is not available on the bus
346 DBusMessage *errMessage = NULL;
347 dbus_uint32_t replySerial;
349 errMessage = generate_local_error_message(msg->cookie, DBUS_ERROR_SERVICE_UNKNOWN, (char*)dbus_message_get_destination(message));
350 if(errMessage == NULL)
355 replySerial = dbus_message_get_reply_serial(message);
357 dbus_message_set_reply_serial(errMessage, replySerial);
358 if (!add_message_to_received(errMessage, (DBusTransport*)transport))
362 _dbus_verbose("kdbus error sending message: err %d (%m)\n", errno);
371 static int64_t kdbus_NameQuery(DBusTransport *transport, char* name, int fd)
373 struct kdbus_cmd_name_info *msg;
374 struct kdbus_item *item;
379 item_size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1;
380 item_size = (item_size < 56) ? 56 : item_size;
381 size = sizeof(struct kdbus_cmd_name_info) + item_size;
386 _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
390 memset(msg, 0, size);
394 item->type = KDBUS_NAME_INFO_ITEM_NAME;
395 item->size = item_size;
396 strcpy(item->str, name);
399 if ((ret = ioctl(fd, KDBUS_CMD_NAME_QUERY, msg)))
412 static dbus_bool_t emulateOrgFreedesktopDBus(DBusTransport *transport, DBusMessage *message, int fd)
416 if(!strcmp(dbus_message_get_member(message), "GetNameOwner"))
420 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
421 _dbus_verbose ("Name to discover: %s !!!! !!!!\n", name);
422 ret = kdbus_NameQuery(transport, name, fd);
423 if(ret > 0) //unique id of the name
426 DBusMessageIter args;
427 char unique_name[(unsigned int)(snprintf(name, 0, "%llu", ULLONG_MAX) + 4)]; //+3 prefix ":1." and +1 closing NULL
428 const char* pString = unique_name;
430 sprintf(unique_name, ":1.%lld", (long long int)ret);
431 _dbus_verbose("Unique name discovered:%s!!! !!!!\n", unique_name);
432 reply = dbus_message_new_method_return(message);
435 dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
436 dbus_message_iter_init_append(reply, &args);
437 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pString))
439 if(add_message_to_received(reply, transport))
442 else if(ret == -ENOENT) //name has no owner
444 DBusMessage *errMessage;
445 dbus_uint32_t replySerial;
447 errMessage = generate_local_error_message(1, DBUS_ERROR_NAME_HAS_NO_OWNER, name);
448 if(errMessage == NULL)
450 replySerial = dbus_message_get_reply_serial(message);
452 dbus_message_set_reply_serial(errMessage, replySerial);
453 if (add_message_to_received(errMessage, transport))
457 _dbus_verbose("kdbus error sending name query: err %d (%m)\n", errno);
459 else if(!strcmp(dbus_message_get_member(message), "NameHasOwner"))
463 DBusMessageIter args;
466 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
467 _dbus_verbose ("Name to discover: %s !!!! !!!!\n", name);
468 ret = kdbus_NameQuery(transport, name, fd);
470 result = (ret > 0) ? TRUE : FALSE;
471 _dbus_verbose("Discovery: %d !!! !!!!\n", (int)result);
472 reply = dbus_message_new_method_return(message);
475 dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
476 dbus_message_iter_init_append(reply, &args);
477 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_BOOLEAN, &result))
479 if(add_message_to_received(reply, transport))
482 else if(!strcmp(dbus_message_get_member(message), "ListNames"))
484 struct kdbus_cmd_names* pCmd;
487 cmd_size = sizeof(struct kdbus_cmd_names) + KDBUS_ITEM_SIZE(1);
488 pCmd = malloc(cmd_size);
491 pCmd->size = cmd_size;
495 if(ioctl(fd, KDBUS_CMD_NAME_LIST, pCmd))
500 cmd_size = pCmd->size;
503 _dbus_verbose("kdbus error asking for name list: err %d (%m)\n",errno);
509 pCmd = realloc(pCmd, cmd_size);
517 DBusMessageIter args;
518 struct kdbus_cmd_name* pCmd_name;
521 reply = dbus_message_new_method_return(message);
524 dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
525 dbus_message_iter_init_append(reply, &args);
527 for (pCmd_name = pCmd->names; (uint8_t *)(pCmd_name) < (uint8_t *)(pCmd) + pCmd->size; pCmd_name = KDBUS_PART_NEXT(pCmd_name))
529 pName = pCmd_name->name;
530 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pName))
534 if(add_message_to_received(reply, transport))
545 else //temporarily we send that info but methods below should be implemented
548 dbus_uint32_t replySerial;
550 reply = generate_local_error_message(1, DBUS_ERROR_UNKNOWN_METHOD, NULL);
553 replySerial = dbus_message_get_reply_serial(message);
555 dbus_message_set_reply_serial(reply, replySerial);
556 if(add_message_to_received(reply, transport))
559 /* else if(!strcmp(dbus_message_get_member(message), "ListActivatableNames"))
563 else if(!strcmp(dbus_message_get_member(message), "StartServiceByName"))
567 else if(!strcmp(dbus_message_get_member(message), "UpdateActivationEnvironment"))
571 else if(!strcmp(dbus_message_get_member(message), "GetConnectionUnixUser"))
575 else if(!strcmp(dbus_message_get_member(message), "GetId"))
583 #if KDBUS_MSG_DECODE_DEBUG == 1
584 static char *msg_id(uint64_t id, char *buf)
590 sprintf(buf, "%llu", (unsigned long long)id);
594 struct kdbus_enum_table {
598 #define _STRINGIFY(x) #x
599 #define STRINGIFY(x) _STRINGIFY(x)
600 #define ELEMENTSOF(x) (sizeof(x)/sizeof((x)[0]))
601 #define TABLE(what) static struct kdbus_enum_table kdbus_table_##what[]
602 #define ENUM(_id) { .id=_id, .name=STRINGIFY(_id) }
603 #define LOOKUP(what) \
604 const char *enum_##what(long long id) { \
606 for (i = 0; i < ELEMENTSOF(kdbus_table_##what); i++) \
607 if (id == kdbus_table_##what[i].id) \
608 return kdbus_table_##what[i].name; \
611 const char *enum_MSG(long long id);
613 ENUM(_KDBUS_MSG_NULL),
614 ENUM(KDBUS_MSG_PAYLOAD_VEC),
615 ENUM(KDBUS_MSG_PAYLOAD_OFF),
616 ENUM(KDBUS_MSG_PAYLOAD_MEMFD),
618 ENUM(KDBUS_MSG_BLOOM),
619 ENUM(KDBUS_MSG_DST_NAME),
620 ENUM(KDBUS_MSG_SRC_CREDS),
621 ENUM(KDBUS_MSG_SRC_PID_COMM),
622 ENUM(KDBUS_MSG_SRC_TID_COMM),
623 ENUM(KDBUS_MSG_SRC_EXE),
624 ENUM(KDBUS_MSG_SRC_CMDLINE),
625 ENUM(KDBUS_MSG_SRC_CGROUP),
626 ENUM(KDBUS_MSG_SRC_CAPS),
627 ENUM(KDBUS_MSG_SRC_SECLABEL),
628 ENUM(KDBUS_MSG_SRC_AUDIT),
629 ENUM(KDBUS_MSG_SRC_NAMES),
630 ENUM(KDBUS_MSG_TIMESTAMP),
631 ENUM(KDBUS_MSG_NAME_ADD),
632 ENUM(KDBUS_MSG_NAME_REMOVE),
633 ENUM(KDBUS_MSG_NAME_CHANGE),
634 ENUM(KDBUS_MSG_ID_ADD),
635 ENUM(KDBUS_MSG_ID_REMOVE),
636 ENUM(KDBUS_MSG_REPLY_TIMEOUT),
637 ENUM(KDBUS_MSG_REPLY_DEAD),
640 const char *enum_PAYLOAD(long long id);
642 ENUM(KDBUS_PAYLOAD_KERNEL),
643 ENUM(KDBUS_PAYLOAD_DBUS1),
644 ENUM(KDBUS_PAYLOAD_GVARIANT),
648 static int put_message_into_data(DBusMessage *message, char* data)
651 const DBusString *header;
652 const DBusString *body;
655 dbus_message_lock (message);
656 _dbus_message_get_network_data (message, &header, &body);
657 ret_size = _dbus_string_get_length(header);
658 memcpy(data, _dbus_string_get_const_data(header), ret_size);
660 size = _dbus_string_get_length(body);
661 memcpy(data, _dbus_string_get_const_data(body), size);
667 * Decodes kdbus message
669 static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTransportSocket* socket_transport, int* fds, int* n_fds)
671 const struct kdbus_item *item = msg->items;
673 DBusMessage *message = NULL;
674 DBusMessageIter args;
675 const char* emptyString = "";
676 const char* pString = NULL;
677 char dbus_name[(unsigned int)(snprintf((char*)pString, 0, "%llu", ULLONG_MAX) + 4)]; //+3 prefix ":1." and +1 closing NULL
678 const char* pDBusName = dbus_name;
680 #if KDBUS_MSG_DECODE_DEBUG == 1
684 #if KDBUS_MSG_DECODE_DEBUG == 1
685 _dbus_verbose("MESSAGE: %s (%llu bytes) flags=0x%llx, %s → %s, cookie=%llu, timeout=%llu\n",
686 enum_PAYLOAD(msg->payload_type), (unsigned long long) msg->size,
687 (unsigned long long) msg->flags,
688 msg_id(msg->src_id, buf), msg_id(msg->dst_id, buf),
689 (unsigned long long) msg->cookie, (unsigned long long) msg->timeout_ns);
693 mmap_ptr = socket_transport->kdbus_mmap_ptr;
695 KDBUS_PART_FOREACH(item, msg, items)
697 if (item->size <= KDBUS_PART_HEADER_SIZE)
699 _dbus_verbose(" +%s (%llu bytes) invalid data record\n", enum_MSG(item->type), item->size);
700 break; //??? continue (because dbus will find error) or break
705 case KDBUS_MSG_PAYLOAD_OFF:
707 uint64_t size = item->vec.size;
709 memcpy(data, (char *)mmap_ptr + item->vec.offset, item->vec.size);
710 data += item->vec.size;
711 ret_size += item->vec.size;
713 _dbus_verbose(" +%s (%llu bytes) off=%llu size=%llu\n",
714 enum_MSG(item->type), item->size,
715 (unsigned long long)item->vec.offset,
716 (unsigned long long)size);
720 case KDBUS_MSG_PAYLOAD_MEMFD:
725 size = item->memfd.size;
727 _dbus_verbose("memfd.size : %llu\n", (unsigned long long)size);
729 buf = mmap(NULL, size, PROT_READ , MAP_SHARED, item->memfd.fd, 0);
731 if (buf == MAP_FAILED)
733 _dbus_verbose("mmap() fd=%i failed:%m", item->memfd.fd);
737 memcpy(data, buf, size);
743 _dbus_verbose(" +%s (%llu bytes) off=%llu size=%llu\n",
744 enum_MSG(item->type), item->size,
745 (unsigned long long)item->vec.offset,
746 (unsigned long long)item->vec.size);
754 *n_fds = (item->size - KDBUS_PART_HEADER_SIZE) / sizeof(int);
755 memcpy(fds, item->fds, *n_fds * sizeof(int));
756 for (i = 0; i < *n_fds; i++)
757 _dbus_fd_set_close_on_exec(fds[i]);
761 #if KDBUS_MSG_DECODE_DEBUG == 1
762 case KDBUS_MSG_SRC_CREDS:
763 _dbus_verbose(" +%s (%llu bytes) uid=%lld, gid=%lld, pid=%lld, tid=%lld, starttime=%lld\n",
764 enum_MSG(item->type), item->size,
765 item->creds.uid, item->creds.gid,
766 item->creds.pid, item->creds.tid,
767 item->creds.starttime);
770 case KDBUS_MSG_SRC_PID_COMM:
771 case KDBUS_MSG_SRC_TID_COMM:
772 case KDBUS_MSG_SRC_EXE:
773 case KDBUS_MSG_SRC_CGROUP:
774 case KDBUS_MSG_SRC_SECLABEL:
775 case KDBUS_MSG_DST_NAME:
776 _dbus_verbose(" +%s (%llu bytes) '%s' (%zu)\n",
777 enum_MSG(item->type), item->size, item->str, strlen(item->str));
780 case KDBUS_MSG_SRC_CMDLINE:
781 case KDBUS_MSG_SRC_NAMES: {
782 __u64 size = item->size - KDBUS_PART_HEADER_SIZE;
783 const char *str = item->str;
786 _dbus_verbose(" +%s (%llu bytes) ", enum_MSG(item->type), item->size);
788 _dbus_verbose("'%s' ", str);
789 size -= strlen(str) + 1;
790 str += strlen(str) + 1;
794 _dbus_verbose("(%d string%s)\n", count, (count == 1) ? "" : "s");
798 case KDBUS_MSG_SRC_AUDIT:
799 _dbus_verbose(" +%s (%llu bytes) loginuid=%llu sessionid=%llu\n",
800 enum_MSG(item->type), item->size,
801 (unsigned long long)item->data64[0],
802 (unsigned long long)item->data64[1]);
805 case KDBUS_MSG_SRC_CAPS: {
810 _dbus_verbose(" +%s (%llu bytes) len=%llu bytes)\n",
811 enum_MSG(item->type), item->size,
812 (unsigned long long)item->size - KDBUS_PART_HEADER_SIZE);
815 n = (item->size - KDBUS_PART_HEADER_SIZE) / 4 / sizeof(uint32_t);
817 _dbus_verbose(" CapInh=");
818 for (i = 0; i < n; i++)
819 _dbus_verbose("%08x", cap[(0 * n) + (n - i - 1)]);
821 _dbus_verbose(" CapPrm=");
822 for (i = 0; i < n; i++)
823 _dbus_verbose("%08x", cap[(1 * n) + (n - i - 1)]);
825 _dbus_verbose(" CapEff=");
826 for (i = 0; i < n; i++)
827 _dbus_verbose("%08x", cap[(2 * n) + (n - i - 1)]);
829 _dbus_verbose(" CapInh=");
830 for (i = 0; i < n; i++)
831 _dbus_verbose("%08x", cap[(3 * n) + (n - i - 1)]);
836 case KDBUS_MSG_TIMESTAMP:
837 _dbus_verbose(" +%s (%llu bytes) realtime=%lluns monotonic=%lluns\n",
838 enum_MSG(item->type), item->size,
839 (unsigned long long)item->timestamp.realtime_ns,
840 (unsigned long long)item->timestamp.monotonic_ns);
844 case KDBUS_MSG_REPLY_TIMEOUT:
845 case KDBUS_MSG_REPLY_DEAD:
846 _dbus_verbose(" +%s (%llu bytes) cookie=%llu\n",
847 enum_MSG(item->type), item->size, msg->cookie_reply);
849 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NO_REPLY, NULL);
856 ret_size = put_message_into_data(message, data);
859 case KDBUS_MSG_NAME_ADD:
860 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
861 enum_MSG(item->type), (unsigned long long) item->size,
862 item->name_change.name, item->name_change.old_id,
863 item->name_change.new_id, item->name_change.flags);
865 message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal
866 DBUS_INTERFACE_DBUS, // interface name of the signal
867 "NameOwnerChanged"); // name of the signal
874 sprintf(dbus_name,":1.%llu",item->name_change.new_id);
875 pString = item->name_change.name;
876 _dbus_verbose ("Name added: %s\n", pString);
877 dbus_message_iter_init_append(message, &args);
878 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING,&pString))
883 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &emptyString))
888 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
894 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
895 dbus_message_set_serial(message, 1);
897 ret_size = put_message_into_data(message, data);
900 case KDBUS_MSG_NAME_REMOVE:
901 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
902 enum_MSG(item->type), (unsigned long long) item->size,
903 item->name_change.name, item->name_change.old_id,
904 item->name_change.new_id, item->name_change.flags);
906 message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal
907 DBUS_INTERFACE_DBUS, // interface name of the signal
908 "NameOwnerChanged"); // name of the signal
915 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
916 pString = item->name_change.name;
917 _dbus_verbose ("Name removed: %s\n", pString);
918 dbus_message_iter_init_append(message, &args);
919 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING,&pString))
924 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
929 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &emptyString))
935 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
936 dbus_message_set_serial(message, 1);
938 ret_size = put_message_into_data(message, data);
941 case KDBUS_MSG_NAME_CHANGE:
942 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
943 enum_MSG(item->type), (unsigned long long) item->size,
944 item->name_change.name, item->name_change.old_id,
945 item->name_change.new_id, item->name_change.flags);
947 message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal
948 DBUS_INTERFACE_DBUS, // interface name of the signal
949 "NameOwnerChanged"); // name of the signal
956 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
957 pString = item->name_change.name;
958 _dbus_verbose ("Name changed: %s\n", pString);
959 dbus_message_iter_init_append(message, &args);
960 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING,&pString))
965 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
970 sprintf(&dbus_name[3],"%llu",item->name_change.new_id);
971 _dbus_verbose ("New id: %s\n", pDBusName);
972 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
978 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
979 dbus_message_set_serial(message, 1);
981 ret_size = put_message_into_data(message, data);
984 case KDBUS_MSG_ID_ADD:
985 _dbus_verbose(" +%s (%llu bytes) id=%llu flags=%llu\n",
986 enum_MSG(item->type), (unsigned long long) item->size,
987 (unsigned long long) item->id_change.id,
988 (unsigned long long) item->id_change.flags);
990 message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal
991 DBUS_INTERFACE_DBUS, // interface name of the signal
992 "NameOwnerChanged"); // name of the signal
999 sprintf(dbus_name,":1.%llu",item->id_change.id);
1000 dbus_message_iter_init_append(message, &args);
1001 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
1006 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &emptyString))
1011 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
1017 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1018 dbus_message_set_serial(message, 1);
1020 ret_size = put_message_into_data(message, data);
1023 case KDBUS_MSG_ID_REMOVE:
1024 _dbus_verbose(" +%s (%llu bytes) id=%llu flags=%llu\n",
1025 enum_MSG(item->type), (unsigned long long) item->size,
1026 (unsigned long long) item->id_change.id,
1027 (unsigned long long) item->id_change.flags);
1029 message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal
1030 DBUS_INTERFACE_DBUS, // interface name of the signal
1031 "NameOwnerChanged"); // name of the signal
1038 sprintf(dbus_name,":1.%llu",item->id_change.id);
1039 dbus_message_iter_init_append(message, &args);
1040 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
1045 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
1050 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &emptyString))
1056 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
1057 dbus_message_set_serial(message, 1);
1059 ret_size = put_message_into_data(message, data);
1061 #if KDBUS_MSG_DECODE_DEBUG == 1
1063 _dbus_verbose(" +%s (%llu bytes)\n", enum_MSG(item->type), item->size);
1069 #if KDBUS_MSG_DECODE_DEBUG == 1
1071 if ((char *)item - ((char *)msg + msg->size) >= 8)
1072 _dbus_verbose("invalid padding at end of message\n");
1077 dbus_message_unref(message);
1082 * Reads message from kdbus to buffer and fds
1084 * @param transport transport
1085 * @param buffer place to copy received message to
1086 * @param fds place to store file descriptors sent in the message
1087 * @param n_fds place to store number of file descriptors
1088 * @return size of received message on success, -1 on error
1090 static int kdbus_read_message(DBusTransportSocket *socket_transport, DBusString *buffer, int* fds, int* n_fds)
1093 uint64_t __attribute__ ((__aligned__(8))) offset;
1094 struct kdbus_msg *msg;
1097 _dbus_assert (socket_transport->max_bytes_read_per_iteration >= 0);
1098 if (!_dbus_string_lengthen (buffer, socket_transport->max_bytes_read_per_iteration))
1103 data = _dbus_string_get_data_len (buffer, 0, socket_transport->max_bytes_read_per_iteration);
1106 if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RECV, &offset) < 0)
1110 _dbus_verbose("kdbus error receiving message: %d (%m)\n", errno);
1111 _dbus_string_set_length (buffer, 0);
1115 msg = (struct kdbus_msg *)((char*)socket_transport->kdbus_mmap_ptr + offset);
1117 ret_size = kdbus_decode_msg(msg, data, socket_transport, fds, n_fds);
1118 _dbus_string_set_length (buffer, ret_size);
1121 if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RELEASE, &offset) < 0)
1125 _dbus_verbose("kdbus error freeing message: %d (%m)\n", errno);
1133 free_watches (DBusTransport *transport)
1135 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1137 _dbus_verbose ("start\n");
1139 if (socket_transport->read_watch)
1141 if (transport->connection)
1142 _dbus_connection_remove_watch_unlocked (transport->connection,
1143 socket_transport->read_watch);
1144 _dbus_watch_invalidate (socket_transport->read_watch);
1145 _dbus_watch_unref (socket_transport->read_watch);
1146 socket_transport->read_watch = NULL;
1149 if (socket_transport->write_watch)
1151 if (transport->connection)
1152 _dbus_connection_remove_watch_unlocked (transport->connection,
1153 socket_transport->write_watch);
1154 _dbus_watch_invalidate (socket_transport->write_watch);
1155 _dbus_watch_unref (socket_transport->write_watch);
1156 socket_transport->write_watch = NULL;
1159 _dbus_verbose ("end\n");
1163 socket_finalize (DBusTransport *transport)
1165 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1167 _dbus_verbose ("\n");
1169 free_watches (transport);
1171 _dbus_string_free (&socket_transport->encoded_outgoing);
1172 _dbus_string_free (&socket_transport->encoded_incoming);
1174 _dbus_transport_finalize_base (transport);
1176 _dbus_assert (socket_transport->read_watch == NULL);
1177 _dbus_assert (socket_transport->write_watch == NULL);
1179 dbus_free (transport);
1183 check_write_watch (DBusTransport *transport)
1185 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1188 if (transport->connection == NULL)
1191 if (transport->disconnected)
1193 _dbus_assert (socket_transport->write_watch == NULL);
1197 _dbus_transport_ref (transport);
1199 #ifdef DBUS_AUTHENTICATION
1200 if (_dbus_transport_get_is_authenticated (transport))
1202 needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection);
1203 #ifdef DBUS_AUTHENTICATION
1206 if (transport->send_credentials_pending)
1210 DBusAuthState auth_state;
1212 auth_state = _dbus_auth_do_work (transport->auth);
1214 /* If we need memory we install the write watch just in case,
1215 * if there's no need for it, it will get de-installed
1216 * next time we try reading.
1218 if (auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND ||
1219 auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY)
1226 _dbus_verbose ("check_write_watch(): needed = %d on connection %p watch %p fd = %d outgoing messages exist %d\n",
1227 needed, transport->connection, socket_transport->write_watch,
1228 socket_transport->fd,
1229 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1231 _dbus_connection_toggle_watch_unlocked (transport->connection,
1232 socket_transport->write_watch,
1235 _dbus_transport_unref (transport);
1239 check_read_watch (DBusTransport *transport)
1241 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1242 dbus_bool_t need_read_watch;
1244 _dbus_verbose ("fd = %d\n",socket_transport->fd);
1246 if (transport->connection == NULL)
1249 if (transport->disconnected)
1251 _dbus_assert (socket_transport->read_watch == NULL);
1255 _dbus_transport_ref (transport);
1257 #ifdef DBUS_AUTHENTICATION
1258 if (_dbus_transport_get_is_authenticated (transport))
1261 (_dbus_counter_get_size_value (transport->live_messages) < transport->max_live_messages_size) &&
1262 (_dbus_counter_get_unix_fd_value (transport->live_messages) < transport->max_live_messages_unix_fds);
1263 #ifdef DBUS_AUTHENTICATION
1266 if (transport->receive_credentials_pending)
1267 need_read_watch = TRUE;
1270 /* The reason to disable need_read_watch when not WAITING_FOR_INPUT
1271 * is to avoid spinning on the file descriptor when we're waiting
1272 * to write or for some other part of the auth process
1274 DBusAuthState auth_state;
1276 auth_state = _dbus_auth_do_work (transport->auth);
1278 /* If we need memory we install the read watch just in case,
1279 * if there's no need for it, it will get de-installed
1280 * next time we try reading. If we're authenticated we
1281 * install it since we normally have it installed while
1284 if (auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT ||
1285 auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY ||
1286 auth_state == DBUS_AUTH_STATE_AUTHENTICATED)
1287 need_read_watch = TRUE;
1289 need_read_watch = FALSE;
1294 _dbus_verbose (" setting read watch enabled = %d\n", need_read_watch);
1295 _dbus_connection_toggle_watch_unlocked (transport->connection,
1296 socket_transport->read_watch,
1299 _dbus_transport_unref (transport);
1303 do_io_error (DBusTransport *transport)
1305 _dbus_transport_ref (transport);
1306 _dbus_transport_disconnect (transport);
1307 _dbus_transport_unref (transport);
1310 #ifdef DBUS_AUTHENTICATION
1311 /* return value is whether we successfully read any new data. */
1313 read_data_into_auth (DBusTransport *transport,
1316 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1322 _dbus_auth_get_buffer (transport->auth, &buffer);
1324 bytes_read = kdbus_read_message(socket_transport, buffer);
1326 _dbus_auth_return_buffer (transport->auth, buffer,
1327 bytes_read > 0 ? bytes_read : 0);
1331 _dbus_verbose (" read %d bytes in auth phase\n", bytes_read);
1334 else if (bytes_read < 0)
1336 /* EINTR already handled for us */
1338 if (_dbus_get_is_errno_enomem ())
1342 else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1343 ; /* do nothing, just return FALSE below */
1346 _dbus_verbose ("Error reading from remote app: %s\n",
1347 _dbus_strerror_from_errno ());
1348 do_io_error (transport);
1355 _dbus_assert (bytes_read == 0);
1357 _dbus_verbose ("Disconnected from remote app\n");
1358 do_io_error (transport);
1364 /* Return value is whether we successfully wrote any bytes */
1366 write_data_from_auth (DBusTransport *transport)
1368 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1370 const DBusString *buffer;
1372 if (!_dbus_auth_get_bytes_to_send (transport->auth,
1376 bytes_written = _dbus_write_socket (socket_transport->fd,
1378 0, _dbus_string_get_length (buffer));
1380 if (bytes_written > 0)
1382 _dbus_auth_bytes_sent (transport->auth, bytes_written);
1385 else if (bytes_written < 0)
1387 /* EINTR already handled for us */
1389 if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1393 _dbus_verbose ("Error writing to remote app: %s\n",
1394 _dbus_strerror_from_errno ());
1395 do_io_error (transport);
1404 exchange_credentials (DBusTransport *transport,
1405 dbus_bool_t do_reading,
1406 dbus_bool_t do_writing)
1408 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1409 DBusError error = DBUS_ERROR_INIT;
1411 _dbus_verbose ("exchange_credentials: do_reading = %d, do_writing = %d\n",
1412 do_reading, do_writing);
1414 if (do_writing && transport->send_credentials_pending)
1416 if (_dbus_send_credentials_socket (socket_transport->fd,
1419 transport->send_credentials_pending = FALSE;
1423 _dbus_verbose ("Failed to write credentials: %s\n", error.message);
1424 dbus_error_free (&error);
1425 do_io_error (transport);
1429 if (do_reading && transport->receive_credentials_pending)
1431 /* FIXME this can fail due to IO error _or_ OOM, broken
1432 * (somewhat tricky to fix since the OOM error can be set after
1433 * we already read the credentials byte, so basically we need to
1434 * separate reading the byte and storing it in the
1435 * transport->credentials). Does not really matter for now
1436 * because storing in credentials never actually fails on unix.
1438 if (_dbus_read_credentials_socket (socket_transport->fd,
1439 transport->credentials,
1442 transport->receive_credentials_pending = FALSE;
1446 _dbus_verbose ("Failed to read credentials %s\n", error.message);
1447 dbus_error_free (&error);
1448 do_io_error (transport);
1452 if (!(transport->send_credentials_pending ||
1453 transport->receive_credentials_pending))
1455 if (!_dbus_auth_set_credentials (transport->auth,
1456 transport->credentials))
1464 do_authentication (DBusTransport *transport,
1465 dbus_bool_t do_reading,
1466 dbus_bool_t do_writing,
1467 dbus_bool_t *auth_completed)
1470 dbus_bool_t orig_auth_state;
1474 orig_auth_state = _dbus_transport_get_is_authenticated (transport);
1476 /* This is essential to avoid the check_write_watch() at the end,
1477 * we don't want to add a write watch in do_iteration before
1478 * we try writing and get EAGAIN
1480 if (orig_auth_state)
1483 *auth_completed = FALSE;
1487 _dbus_transport_ref (transport);
1489 while (!_dbus_transport_get_is_authenticated (transport) &&
1490 _dbus_transport_get_is_connected (transport))
1492 if (!exchange_credentials (transport, do_reading, do_writing))
1498 if (transport->send_credentials_pending ||
1499 transport->receive_credentials_pending)
1501 _dbus_verbose ("send_credentials_pending = %d receive_credentials_pending = %d\n",
1502 transport->send_credentials_pending,
1503 transport->receive_credentials_pending);
1507 #define TRANSPORT_SIDE(t) ((t)->is_server ? "server" : "client")
1508 switch (_dbus_auth_do_work (transport->auth))
1510 case DBUS_AUTH_STATE_WAITING_FOR_INPUT:
1511 _dbus_verbose (" %s auth state: waiting for input\n",
1512 TRANSPORT_SIDE (transport));
1513 if (!do_reading || !read_data_into_auth (transport, &oom))
1517 case DBUS_AUTH_STATE_WAITING_FOR_MEMORY:
1518 _dbus_verbose (" %s auth state: waiting for memory\n",
1519 TRANSPORT_SIDE (transport));
1524 case DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND:
1525 _dbus_verbose (" %s auth state: bytes to send\n",
1526 TRANSPORT_SIDE (transport));
1527 if (!do_writing || !write_data_from_auth (transport))
1531 case DBUS_AUTH_STATE_NEED_DISCONNECT:
1532 _dbus_verbose (" %s auth state: need to disconnect\n",
1533 TRANSPORT_SIDE (transport));
1534 do_io_error (transport);
1537 case DBUS_AUTH_STATE_AUTHENTICATED:
1538 _dbus_verbose (" %s auth state: authenticated\n",
1539 TRANSPORT_SIDE (transport));
1546 *auth_completed = (orig_auth_state != _dbus_transport_get_is_authenticated (transport));
1548 check_read_watch (transport);
1549 check_write_watch (transport);
1550 _dbus_transport_unref (transport);
1559 /* returns false on oom */
1561 do_writing (DBusTransport *transport)
1563 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1566 #ifdef DBUS_AUTHENTICATION
1567 /* No messages without authentication! */
1568 if (!_dbus_transport_get_is_authenticated (transport))
1570 _dbus_verbose ("Not authenticated, not writing anything\n");
1575 if (transport->disconnected)
1577 _dbus_verbose ("Not connected, not writing anything\n");
1582 _dbus_verbose ("do_writing(), have_messages = %d, fd = %d\n",
1583 _dbus_connection_has_messages_to_send_unlocked (transport->connection),
1584 socket_transport->fd);
1589 while (!transport->disconnected && _dbus_connection_has_messages_to_send_unlocked (transport->connection))
1592 DBusMessage *message;
1593 const DBusString *header;
1594 const DBusString *body;
1595 int total_bytes_to_write;
1596 const char* pDestination;
1598 message = _dbus_connection_get_message_to_send (transport->connection);
1599 _dbus_assert (message != NULL);
1600 dbus_message_lock (message);
1601 _dbus_message_get_network_data (message, &header, &body);
1602 total_bytes_to_write = _dbus_string_get_length(header) + _dbus_string_get_length(body);
1603 pDestination = dbus_message_get_destination(message);
1607 if(!strcmp(pDestination, "org.freedesktop.DBus"))
1609 if(emulateOrgFreedesktopDBus(transport, message, socket_transport->fd))
1610 bytes_written = total_bytes_to_write;
1616 if (_dbus_auth_needs_encoding (transport->auth))
1618 if (_dbus_string_get_length (&socket_transport->encoded_outgoing) == 0)
1620 if (!_dbus_auth_encode_data (transport->auth,
1621 header, &socket_transport->encoded_outgoing))
1627 if (!_dbus_auth_encode_data (transport->auth,
1628 body, &socket_transport->encoded_outgoing))
1630 _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
1636 total_bytes_to_write = _dbus_string_get_length (&socket_transport->encoded_outgoing);
1637 if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration)
1640 bytes_written = kdbus_write_msg(socket_transport, message, TRUE);
1644 if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration)
1647 bytes_written = kdbus_write_msg(socket_transport, message, FALSE);
1651 if (bytes_written < 0)
1653 /* EINTR already handled for us */
1655 /* For some discussion of why we also ignore EPIPE here, see
1656 * http://lists.freedesktop.org/archives/dbus/2008-March/009526.html
1659 if (_dbus_get_is_errno_eagain_or_ewouldblock () || _dbus_get_is_errno_epipe ())
1663 _dbus_verbose ("Error writing to remote app: %s\n", _dbus_strerror_from_errno ());
1664 do_io_error (transport);
1670 _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
1671 total_bytes_to_write);
1673 socket_transport->message_bytes_written += bytes_written;
1675 _dbus_assert (socket_transport->message_bytes_written <=
1676 total_bytes_to_write);
1678 if (socket_transport->message_bytes_written == total_bytes_to_write)
1680 socket_transport->message_bytes_written = 0;
1681 _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
1682 _dbus_string_compact (&socket_transport->encoded_outgoing, 2048);
1684 _dbus_connection_message_sent_unlocked (transport->connection,
1697 /* returns false on out-of-memory */
1699 do_reading (DBusTransport *transport)
1701 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1704 dbus_bool_t oom = FALSE;
1707 _dbus_verbose ("fd = %d\n",socket_transport->fd);
1709 #ifdef DBUS_AUTHENTICATION
1710 /* No messages without authentication! */
1711 if (!_dbus_transport_get_is_authenticated (transport))
1717 /* See if we've exceeded max messages and need to disable reading */
1718 check_read_watch (transport);
1720 _dbus_assert (socket_transport->read_watch != NULL ||
1721 transport->disconnected);
1723 if (transport->disconnected)
1726 if (!dbus_watch_get_enabled (socket_transport->read_watch))
1729 if (!_dbus_message_loader_get_unix_fds(transport->loader, &fds, &n_fds))
1731 _dbus_verbose ("Out of memory reading file descriptors\n");
1735 _dbus_message_loader_get_buffer (transport->loader, &buffer);
1737 if (_dbus_auth_needs_decoding (transport->auth))
1739 bytes_read = kdbus_read_message(socket_transport, &socket_transport->encoded_incoming, fds, &n_fds);
1741 _dbus_assert (_dbus_string_get_length (&socket_transport->encoded_incoming) == bytes_read);
1745 if (!_dbus_auth_decode_data (transport->auth,
1746 &socket_transport->encoded_incoming,
1749 _dbus_verbose ("Out of memory decoding incoming data\n");
1750 _dbus_message_loader_return_buffer (transport->loader,
1752 _dbus_string_get_length (buffer));
1757 _dbus_string_set_length (&socket_transport->encoded_incoming, 0);
1758 _dbus_string_compact (&socket_transport->encoded_incoming, 2048);
1762 bytes_read = kdbus_read_message(socket_transport, buffer, fds, &n_fds);
1764 if (bytes_read >= 0 && n_fds > 0)
1765 _dbus_verbose("Read %i unix fds\n", n_fds);
1767 _dbus_message_loader_return_buffer (transport->loader,
1769 bytes_read < 0 ? 0 : _dbus_string_get_length (buffer));
1770 _dbus_message_loader_return_unix_fds(transport->loader, fds, bytes_read < 0 ? 0 : n_fds);
1774 /* EINTR already handled for us */
1776 if (_dbus_get_is_errno_enomem ())
1778 _dbus_verbose ("Out of memory in read()/do_reading()\n");
1782 else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1786 _dbus_verbose ("Error reading from remote app: %s\n",
1787 _dbus_strerror_from_errno ());
1788 do_io_error (transport);
1792 else if (bytes_read == 0)
1794 _dbus_verbose ("Disconnected from remote app\n");
1795 do_io_error (transport);
1800 _dbus_verbose (" read %d bytes\n", bytes_read);
1802 if (!_dbus_transport_queue_messages (transport))
1805 _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
1809 /* Try reading more data until we get EAGAIN and return, or
1810 * exceed max bytes per iteration. If in blocking mode of
1811 * course we'll block instead of returning.
1824 unix_error_with_read_to_come (DBusTransport *itransport,
1828 DBusTransportSocket *transport = (DBusTransportSocket *) itransport;
1830 if (!(flags & DBUS_WATCH_HANGUP || flags & DBUS_WATCH_ERROR))
1833 /* If we have a read watch enabled ...
1834 we -might have data incoming ... => handle the HANGUP there */
1835 if (watch != transport->read_watch &&
1836 _dbus_watch_get_enabled (transport->read_watch))
1843 socket_handle_watch (DBusTransport *transport,
1847 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1849 _dbus_assert (watch == socket_transport->read_watch ||
1850 watch == socket_transport->write_watch);
1851 _dbus_assert (watch != NULL);
1853 /* If we hit an error here on a write watch, don't disconnect the transport yet because data can
1854 * still be in the buffer and do_reading may need several iteration to read
1855 * it all (because of its max_bytes_read_per_iteration limit).
1857 if (!(flags & DBUS_WATCH_READABLE) && unix_error_with_read_to_come (transport, watch, flags))
1859 _dbus_verbose ("Hang up or error on watch\n");
1860 _dbus_transport_disconnect (transport);
1864 if (watch == socket_transport->read_watch &&
1865 (flags & DBUS_WATCH_READABLE))
1867 #ifdef DBUS_AUTHENTICATION
1868 dbus_bool_t auth_finished;
1871 _dbus_verbose ("handling read watch %p flags = %x\n",
1874 #ifdef DBUS_AUTHENTICATION
1875 if (!do_authentication (transport, TRUE, FALSE, &auth_finished))
1878 /* We don't want to do a read immediately following
1879 * a successful authentication. This is so we
1880 * have a chance to propagate the authentication
1881 * state further up. Specifically, we need to
1882 * process any pending data from the auth object.
1887 if (!do_reading (transport))
1889 _dbus_verbose ("no memory to read\n");
1892 #ifdef DBUS_AUTHENTICATION
1896 _dbus_verbose ("Not reading anything since we just completed the authentication\n");
1900 else if (watch == socket_transport->write_watch &&
1901 (flags & DBUS_WATCH_WRITABLE))
1904 _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n",
1905 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1907 #ifdef DBUS_AUTHENTICATION
1908 if (!do_authentication (transport, FALSE, TRUE, NULL))
1911 if (!do_writing (transport))
1913 _dbus_verbose ("no memory to write\n");
1917 /* See if we still need the write watch */
1918 check_write_watch (transport);
1920 #ifdef DBUS_ENABLE_VERBOSE_MODE
1923 if (watch == socket_transport->read_watch)
1924 _dbus_verbose ("asked to handle read watch with non-read condition 0x%x\n",
1926 else if (watch == socket_transport->write_watch)
1927 _dbus_verbose ("asked to handle write watch with non-write condition 0x%x\n",
1930 _dbus_verbose ("asked to handle watch %p on fd %d that we don't recognize\n",
1931 watch, dbus_watch_get_socket (watch));
1933 #endif /* DBUS_ENABLE_VERBOSE_MODE */
1939 socket_disconnect (DBusTransport *transport)
1941 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1943 _dbus_verbose ("\n");
1945 free_watches (transport);
1947 _dbus_close_socket (socket_transport->fd, NULL);
1948 socket_transport->fd = -1;
1952 socket_connection_set (DBusTransport *transport)
1954 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1956 _dbus_watch_set_handler (socket_transport->write_watch,
1957 _dbus_connection_handle_watch,
1958 transport->connection, NULL);
1960 _dbus_watch_set_handler (socket_transport->read_watch,
1961 _dbus_connection_handle_watch,
1962 transport->connection, NULL);
1964 if (!_dbus_connection_add_watch_unlocked (transport->connection,
1965 socket_transport->write_watch))
1968 if (!_dbus_connection_add_watch_unlocked (transport->connection,
1969 socket_transport->read_watch))
1971 _dbus_connection_remove_watch_unlocked (transport->connection,
1972 socket_transport->write_watch);
1976 check_read_watch (transport);
1977 check_write_watch (transport);
1983 * @todo We need to have a way to wake up the select sleep if
1984 * a new iteration request comes in with a flag (read/write) that
1985 * we're not currently serving. Otherwise a call that just reads
1986 * could block a write call forever (if there are no incoming
1990 kdbus_do_iteration (DBusTransport *transport,
1992 int timeout_milliseconds)
1994 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1999 _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p fd = %d\n",
2000 flags & DBUS_ITERATION_DO_READING ? "read" : "",
2001 flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
2002 timeout_milliseconds,
2003 socket_transport->read_watch,
2004 socket_transport->write_watch,
2005 socket_transport->fd);
2007 /* the passed in DO_READING/DO_WRITING flags indicate whether to
2008 * read/write messages, but regardless of those we may need to block
2009 * for reading/writing to do auth. But if we do reading for auth,
2010 * we don't want to read any messages yet if not given DO_READING.
2013 poll_fd.fd = socket_transport->fd;
2016 if (_dbus_transport_get_is_authenticated (transport))
2018 /* This is kind of a hack; if we have stuff to write, then try
2019 * to avoid the poll. This is probably about a 5% speedup on an
2020 * echo client/server.
2022 * If both reading and writing were requested, we want to avoid this
2023 * since it could have funky effects:
2024 * - both ends spinning waiting for the other one to read
2025 * data so they can finish writing
2026 * - prioritizing all writing ahead of reading
2028 if ((flags & DBUS_ITERATION_DO_WRITING) &&
2029 !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) &&
2030 !transport->disconnected &&
2031 _dbus_connection_has_messages_to_send_unlocked (transport->connection))
2033 do_writing (transport);
2035 if (transport->disconnected ||
2036 !_dbus_connection_has_messages_to_send_unlocked (transport->connection))
2040 /* If we get here, we decided to do the poll() after all */
2041 _dbus_assert (socket_transport->read_watch);
2042 if (flags & DBUS_ITERATION_DO_READING)
2043 poll_fd.events |= _DBUS_POLLIN;
2045 _dbus_assert (socket_transport->write_watch);
2046 if (flags & DBUS_ITERATION_DO_WRITING)
2047 poll_fd.events |= _DBUS_POLLOUT;
2051 DBusAuthState auth_state;
2053 auth_state = _dbus_auth_do_work (transport->auth);
2055 if (transport->receive_credentials_pending ||
2056 auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT)
2057 poll_fd.events |= _DBUS_POLLIN;
2059 if (transport->send_credentials_pending ||
2060 auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND)
2061 poll_fd.events |= _DBUS_POLLOUT;
2066 if (flags & DBUS_ITERATION_BLOCK)
2067 poll_timeout = timeout_milliseconds;
2071 /* For blocking selects we drop the connection lock here
2072 * to avoid blocking out connection access during a potentially
2073 * indefinite blocking call. The io path is still protected
2074 * by the io_path_cond condvar, so we won't reenter this.
2076 if (flags & DBUS_ITERATION_BLOCK)
2078 _dbus_verbose ("unlock pre poll\n");
2079 _dbus_connection_unlock (transport->connection);
2083 poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
2085 if (poll_res < 0 && _dbus_get_is_errno_eintr ())
2087 _dbus_verbose ("Error from _dbus_poll(): %s\n",
2088 _dbus_strerror_from_errno ());
2092 if (flags & DBUS_ITERATION_BLOCK)
2094 _dbus_verbose ("lock post poll\n");
2095 _dbus_connection_lock (transport->connection);
2101 poll_fd.revents = 0; /* some concern that posix does not guarantee this;
2102 * valgrind flags it as an error. though it probably
2103 * is guaranteed on linux at least.
2106 if (poll_fd.revents & _DBUS_POLLERR)
2107 do_io_error (transport);
2110 dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
2111 dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0;
2112 #ifdef DBUS_AUTHENTICATION
2113 dbus_bool_t authentication_completed;
2116 _dbus_verbose ("in iteration, need_read=%d need_write=%d\n",
2117 need_read, need_write);
2118 #ifdef DBUS_AUTHENTICATION
2119 do_authentication (transport, need_read, need_write,
2120 &authentication_completed);
2122 /* See comment in socket_handle_watch. */
2123 if (authentication_completed)
2126 if (need_read && (flags & DBUS_ITERATION_DO_READING))
2127 do_reading (transport);
2128 if (need_write && (flags & DBUS_ITERATION_DO_WRITING))
2129 do_writing (transport);
2133 _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
2137 /* We need to install the write watch only if we did not
2138 * successfully write everything. Note we need to be careful that we
2139 * don't call check_write_watch *before* do_writing, since it's
2140 * inefficient to add the write watch, and we can avoid it most of
2141 * the time since we can write immediately.
2143 * However, we MUST always call check_write_watch(); DBusConnection code
2144 * relies on the fact that running an iteration will notice that
2145 * messages are pending.
2147 check_write_watch (transport);
2149 _dbus_verbose (" ... leaving do_iteration()\n");
2153 socket_live_messages_changed (DBusTransport *transport)
2155 /* See if we should look for incoming messages again */
2156 check_read_watch (transport);
2159 static const DBusTransportVTable kdbus_vtable = {
2161 socket_handle_watch,
2163 socket_connection_set,
2165 socket_live_messages_changed,
2166 socket_get_socket_fd
2170 * Creates a new transport for the given kdbus file descriptor. The file
2171 * descriptor must be nonblocking.
2173 * @param fd the file descriptor.
2174 * @param address the transport's address
2175 * @returns the new transport, or #NULL if no memory.
2177 static DBusTransport*
2178 _dbus_transport_new_for_socket_kdbus (int fd,
2179 const DBusString *address)
2181 DBusTransportSocket *socket_transport;
2183 socket_transport = dbus_new0 (DBusTransportSocket, 1);
2184 if (socket_transport == NULL)
2187 if (!_dbus_string_init (&socket_transport->encoded_outgoing))
2190 if (!_dbus_string_init (&socket_transport->encoded_incoming))
2193 socket_transport->write_watch = _dbus_watch_new (fd,
2194 DBUS_WATCH_WRITABLE,
2197 if (socket_transport->write_watch == NULL)
2200 socket_transport->read_watch = _dbus_watch_new (fd,
2201 DBUS_WATCH_READABLE,
2204 if (socket_transport->read_watch == NULL)
2207 if (!_dbus_transport_init_base (&socket_transport->base,
2212 #ifdef DBUS_AUTHENTICATION
2213 #ifdef HAVE_UNIX_FD_PASSING
2214 _dbus_auth_set_unix_fd_possible(socket_transport->base.auth, _dbus_socket_can_pass_unix_fd(fd));
2218 socket_transport->fd = fd;
2219 socket_transport->message_bytes_written = 0;
2221 /* These values should probably be tunable or something. */
2222 socket_transport->max_bytes_read_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2223 socket_transport->max_bytes_written_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2225 socket_transport->kdbus_mmap_ptr = NULL;
2226 socket_transport->memfd = -1;
2228 return (DBusTransport*) socket_transport;
2231 _dbus_watch_invalidate (socket_transport->read_watch);
2232 _dbus_watch_unref (socket_transport->read_watch);
2234 _dbus_watch_invalidate (socket_transport->write_watch);
2235 _dbus_watch_unref (socket_transport->write_watch);
2237 _dbus_string_free (&socket_transport->encoded_incoming);
2239 _dbus_string_free (&socket_transport->encoded_outgoing);
2241 dbus_free (socket_transport);
2247 * Opens a connection to the kdbus bus
2249 * This will set FD_CLOEXEC for the socket returned.
2251 * @param path the path to UNIX domain socket
2252 * @param error return location for error code
2253 * @returns connection file descriptor or -1 on error
2255 static int _dbus_connect_kdbus (const char *path, DBusError *error)
2259 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2260 _dbus_verbose ("connecting to kdbus bus %s\n", path);
2262 fd = open(path, O_RDWR|O_CLOEXEC|O_NONBLOCK);
2264 dbus_set_error(error, _dbus_error_from_errno (errno), "Failed to open file descriptor: %s", _dbus_strerror (errno));
2270 * maps memory pool for messages received by the kdbus transport
2272 * @param transport transport
2273 * @returns #TRUE on success
2275 static dbus_bool_t kdbus_mmap(DBusTransport* transport)
2277 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2279 socket_transport->kdbus_mmap_ptr = mmap(NULL, RECEIVE_POOL_SIZE, PROT_READ, MAP_SHARED, socket_transport->fd, 0);
2280 if (socket_transport->kdbus_mmap_ptr == MAP_FAILED)
2287 * Creates a new transport for kdbus.
2288 * This creates a client-side of a transport.
2290 * @param path the path to the bus.
2291 * @param error address where an error can be returned.
2292 * @returns a new transport, or #NULL on failure.
2294 static DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error)
2297 DBusTransport *transport;
2300 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2302 if (!_dbus_string_init (&address))
2304 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2310 if ((!_dbus_string_append (&address, "kdbus:path=")) || (!_dbus_string_append (&address, path)))
2312 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2316 fd = _dbus_connect_kdbus (path, error);
2319 _DBUS_ASSERT_ERROR_IS_SET (error);
2323 _dbus_verbose ("Successfully connected to kdbus bus %s\n", path);
2325 transport = _dbus_transport_new_for_socket_kdbus (fd, &address);
2326 if (transport == NULL)
2328 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2332 _dbus_string_free (&address);
2337 _dbus_close_socket (fd, NULL);
2339 _dbus_string_free (&address);
2345 * Opens kdbus transport if method from address entry is kdbus
2347 * @param entry the address entry to try opening
2348 * @param transport_p return location for the opened transport
2349 * @param error error to be set
2350 * @returns result of the attempt
2352 DBusTransportOpenResult _dbus_transport_open_kdbus(DBusAddressEntry *entry,
2353 DBusTransport **transport_p,
2358 method = dbus_address_entry_get_method (entry);
2359 _dbus_assert (method != NULL);
2361 if (strcmp (method, "kdbus") == 0)
2363 const char *path = dbus_address_entry_get_value (entry, "path");
2367 _dbus_set_bad_address (error, "kdbus", "path", NULL);
2368 return DBUS_TRANSPORT_OPEN_BAD_ADDRESS;
2371 *transport_p = _dbus_transport_new_for_kdbus (path, error);
2373 if (*transport_p == NULL)
2375 _DBUS_ASSERT_ERROR_IS_SET (error);
2376 return DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT;
2380 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2381 return DBUS_TRANSPORT_OPEN_OK;
2386 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2387 return DBUS_TRANSPORT_OPEN_NOT_HANDLED;
2391 static struct kdbus_policy *make_policy_name(const char *name)
2393 struct kdbus_policy *p;
2396 size = offsetof(struct kdbus_policy, name) + strlen(name) + 1;
2402 p->type = KDBUS_POLICY_NAME;
2403 strcpy(p->name, name);
2408 static struct kdbus_policy *make_policy_access(__u64 type, __u64 bits, __u64 id)
2410 struct kdbus_policy *p;
2411 __u64 size = sizeof(*p);
2419 p->type = KDBUS_POLICY_ACCESS;
2420 p->access.type = type;
2421 p->access.bits = bits;
2427 static void append_policy(struct kdbus_cmd_policy *cmd_policy, struct kdbus_policy *policy, __u64 max_size)
2429 struct kdbus_policy *dst = (struct kdbus_policy *) ((char *) cmd_policy + cmd_policy->size);
2431 if (cmd_policy->size + policy->size > max_size)
2434 memcpy(dst, policy, policy->size);
2435 cmd_policy->size += KDBUS_ALIGN8(policy->size);
2440 * Registers kdbus policy for given connection.
2442 * Policy sets rights of the name (unique or well known) on the bus. Without policy it is
2443 * not possible to send or receive messages. It must be set separately for unique id and
2444 * well known name of the connection. It is set after registering on the bus, but before
2445 * requesting for name. The policy is valid for the given name, not for the connection.
2447 * Name of the policy equals name on the bus.
2449 * @param name name of the policy = name of the connection
2450 * @param connection the connection
2451 * @param error place to store errors
2453 * @returns #TRUE on success
2455 dbus_bool_t bus_register_policy_kdbus(const char* name, DBusConnection *connection, DBusError *error)
2457 struct kdbus_cmd_policy *cmd_policy;
2458 struct kdbus_policy *policy;
2462 if(!dbus_connection_get_socket(connection, &fd))
2464 dbus_set_error (error, "Failed to get fd for registering policy", NULL);
2468 cmd_policy = alloca(size);
2469 memset(cmd_policy, 0, size);
2471 policy = (struct kdbus_policy *) cmd_policy->policies;
2472 cmd_policy->size = offsetof(struct kdbus_cmd_policy, policies);
2474 policy = make_policy_name(name);
2475 append_policy(cmd_policy, policy, size);
2477 policy = make_policy_access(KDBUS_POLICY_ACCESS_USER, KDBUS_POLICY_OWN, getuid());
2478 append_policy(cmd_policy, policy, size);
2480 policy = make_policy_access(KDBUS_POLICY_ACCESS_WORLD, KDBUS_POLICY_RECV, 0);
2481 append_policy(cmd_policy, policy, size);
2483 policy = make_policy_access(KDBUS_POLICY_ACCESS_WORLD, KDBUS_POLICY_SEND, 0);
2484 append_policy(cmd_policy, policy, size);
2486 if (ioctl(fd, KDBUS_CMD_EP_POLICY_SET, cmd_policy) < 0)
2488 dbus_set_error(error,_dbus_error_from_errno (errno), "Error setting EP policy: %s", _dbus_strerror (errno));
2492 _dbus_verbose("Policy %s set correctly\n", name);
2497 * Kdbus part of dbus_bus_register.
2498 * Shouldn't be used separately because it needs to be surrounded
2499 * by other functions as it is done in dbus_bus_register.
2501 * @param name place to store unique name given by bus
2502 * @param connection the connection
2503 * @param error place to store errors
2504 * @returns #TRUE on success
2506 dbus_bool_t bus_register_kdbus(char* name, DBusConnection *connection, DBusError *error)
2508 struct kdbus_cmd_hello __attribute__ ((__aligned__(8))) hello;
2511 memset(&hello, 0, sizeof(hello));
2512 hello.conn_flags = KDBUS_HELLO_ACCEPT_FD/* |
2513 KDBUS_HELLO_ATTACH_COMM |
2514 KDBUS_HELLO_ATTACH_EXE |
2515 KDBUS_HELLO_ATTACH_CMDLINE |
2516 KDBUS_HELLO_ATTACH_CAPS |
2517 KDBUS_HELLO_ATTACH_CGROUP |
2518 KDBUS_HELLO_ATTACH_SECLABEL |
2519 KDBUS_HELLO_ATTACH_AUDIT*/;
2520 hello.size = sizeof(struct kdbus_cmd_hello);
2521 hello.pool_size = RECEIVE_POOL_SIZE;
2523 if(!dbus_connection_get_socket(connection, &fd))
2525 dbus_set_error (error, "failed to get fd for bus registration", NULL);
2528 if (ioctl(fd, KDBUS_CMD_HELLO, &hello))
2530 dbus_set_error(error,_dbus_error_from_errno (errno), "Failed to send hello: %s", _dbus_strerror (errno));
2534 _dbus_verbose("-- Our peer ID is: %llu\n", (unsigned long long)hello.id);
2535 sprintf(name, "%llu", (unsigned long long)hello.id);
2537 if(!kdbus_mmap(dbus_connection_get_transport(connection)))
2539 dbus_set_error(error,_dbus_error_from_errno (errno), "Error when mmap: %s", _dbus_strerror (errno));
2547 * kdbus version of dbus_bus_request_name.
2549 * Asks the bus to assign the given name to this connection.
2551 * Use same flags as original dbus version with one exception below.
2552 * Result flag #DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER is currently
2553 * never returned by kdbus, instead DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER
2554 * is returned by kdbus.
2556 * @param connection the connection
2557 * @param name the name to request
2558 * @param flags flags
2559 * @param error location to store the error
2560 * @returns a result code, -1 if error is set
2562 int bus_request_name_kdbus(DBusConnection *connection, const char *name, const uint64_t flags, DBusError *error)
2564 struct kdbus_cmd_name *cmd_name;
2566 uint64_t size = sizeof(*cmd_name) + strlen(name) + 1;
2567 uint64_t flags_kdbus = 0;
2569 cmd_name = alloca(size);
2571 memset(cmd_name, 0, size);
2572 strcpy(cmd_name->name, name);
2573 cmd_name->size = size;
2575 if(flags & DBUS_NAME_FLAG_ALLOW_REPLACEMENT)
2576 flags_kdbus |= KDBUS_NAME_ALLOW_REPLACEMENT;
2577 if(!(flags & DBUS_NAME_FLAG_DO_NOT_QUEUE))
2578 flags_kdbus |= KDBUS_NAME_QUEUE;
2579 if(flags & DBUS_NAME_FLAG_REPLACE_EXISTING)
2580 flags_kdbus |= KDBUS_NAME_REPLACE_EXISTING;
2582 cmd_name->conn_flags = flags_kdbus;
2584 if(!dbus_connection_get_socket(connection, &fd))
2586 dbus_set_error (error, "failed to get fd for name request", NULL);
2590 _dbus_verbose("Request name - flags sent: 0x%llx !!!!!!!!!\n", cmd_name->conn_flags);
2592 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2593 if (ioctl(fd, KDBUS_CMD_NAME_ACQUIRE, cmd_name))
2595 dbus_set_error(error,_dbus_error_from_errno (errno), "error acquiring name: %s", _dbus_strerror (errno));
2597 return DBUS_REQUEST_NAME_REPLY_EXISTS;
2601 _dbus_verbose("Request name - received flag: 0x%llx !!!!!!!!!\n", cmd_name->conn_flags);
2603 if(cmd_name->conn_flags & KDBUS_NAME_IN_QUEUE)
2604 return DBUS_REQUEST_NAME_REPLY_IN_QUEUE;
2606 return DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER;
2607 //todo now 1 code is never returned - DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER
2611 * Checks if the connection's transport is kdbus on the basis of its address
2613 * @param pointer to the connection
2614 * @returns TRUE if kdbus transport, otherwise FALSE
2616 dbus_bool_t dbus_transport_is_kdbus(DBusConnection *connection)
2618 const char* address = _dbus_connection_get_address(connection);
2620 if(address == strstr(address, "kdbus:path="))
2626 static int parse_match_key(const char *rule, const char* key, char** pValue)
2629 const char* pValueEnd;
2630 int value_length = 0;
2632 pBegin = strstr(rule, key);
2635 pBegin += strlen(key);
2636 pValueEnd = strchr(pBegin, '\'');
2639 value_length = pValueEnd - pBegin;
2640 *pValue = strndup(pBegin, value_length);
2643 if(strcmp(*pValue, "org.freedesktop.DBus") == 0)
2645 _dbus_verbose ("found for key: %s value:'%s'\n", key, *pValue);
2649 return value_length;
2653 * Adds a match rule to match broadcast messages going through the message bus.
2654 * Do no affect messages addressed directly.
2656 * The "rule" argument is the string form of a match rule.
2658 * In kdbus function do not blocks.
2660 * Upper function returns nothing because of blocking issues
2661 * so there is no point to return true or false here.
2663 * Only part of the dbus's matching capabilities is implemented in kdbus now, because of different mechanism.
2665 * interface match key mapped to bloom
2666 * sender match key mapped to src_name
2667 * also handled org.freedesktop.dbus members: NameOwnerChanged, NameLost, NameAcquired
2669 * @param connection connection to the message bus
2670 * @param rule textual form of match rule
2671 * @param error location to store any errors - may be NULL
2673 void dbus_bus_add_match_kdbus (DBusConnection *connection, const char *rule, DBusError *error)
2675 struct kdbus_cmd_match* pCmd_match;
2676 struct kdbus_item *pItem;
2678 __u64 src_id = KDBUS_MATCH_SRC_ID_ANY;
2680 unsigned int kernel_item = 0;
2683 char* pInterface = NULL;
2685 dbus_connection_get_socket(connection, &fd);
2687 /*parsing rule and calculating size of command*/
2688 size = sizeof(struct kdbus_cmd_match);
2690 if(strstr(rule, "member='NameOwnerChanged'"))
2692 kernel_item = KDBUS_MATCH_NAME_CHANGE;
2693 size += KDBUS_ITEM_SIZE(1);
2695 else if(strstr(rule, "member='NameLost'"))
2697 kernel_item = KDBUS_MATCH_NAME_REMOVE;
2698 size += KDBUS_ITEM_SIZE(1);
2700 else if(strstr(rule, "member='NameAcquired'"))
2702 kernel_item = KDBUS_MATCH_NAME_ADD;
2703 size += KDBUS_ITEM_SIZE(1);
2706 name_size = parse_match_key(rule, "interface='", &pInterface);
2707 if((name_size == -1) && (kernel_item == 0)) //means org.freedesktop.DBus
2710 size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2; /* 3 above
2711 name related items plus 2 id related items*/
2713 else if(name_size > 0) /*actual size is not important for interface because bloom size is defined by bus*/
2714 size += KDBUS_PART_HEADER_SIZE + KDBUS_BLOOM_SIZE_BYTES;
2716 name_size = parse_match_key(rule, "sender='", &pName);
2717 if((name_size == -1) && (kernel_item == 0)) //means org.freedesktop.DBus - same as interface few line above
2720 size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2; /* 3 above
2721 name related items plus 2 id related items*/
2725 if(!strncmp(pName, ":1.", 3)) /*if name is unique name it must be converted to unique id*/
2727 src_id = strtoull(&pName[3], NULL, 10);
2732 size += KDBUS_ITEM_SIZE(name_size + 1); //well known name
2735 pCmd_match = alloca(size);
2736 if(pCmd_match == NULL)
2738 memset(pCmd_match, 0, size);
2740 pCmd_match->size = size;
2741 pCmd_match->cookie = strtoull(dbus_bus_get_unique_name(connection), NULL , 10);
2743 pItem = pCmd_match->items;
2744 if(kernel_item == ~0) //all signals from kernel
2746 pCmd_match->src_id = 0;
2747 pItem->type = KDBUS_MATCH_NAME_CHANGE;
2748 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2749 pItem = KDBUS_PART_NEXT(pItem);
2750 pItem->type = KDBUS_MATCH_NAME_ADD;
2751 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2752 pItem = KDBUS_PART_NEXT(pItem);
2753 pItem->type = KDBUS_MATCH_NAME_REMOVE;
2754 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2755 pItem = KDBUS_PART_NEXT(pItem);
2756 pItem->type = KDBUS_MATCH_ID_ADD;
2757 pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64);
2758 pItem = KDBUS_PART_NEXT(pItem);
2759 pItem->type = KDBUS_MATCH_ID_REMOVE;
2760 pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64);
2762 else if(kernel_item)
2764 pCmd_match->src_id = 0;
2765 pItem->type = kernel_item;
2766 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2770 pCmd_match->src_id = src_id;
2773 pItem->type = KDBUS_MATCH_SRC_NAME;
2774 pItem->size = KDBUS_PART_HEADER_SIZE + name_size + 1;
2775 strcpy(pItem->str, pName);
2776 pItem = KDBUS_PART_NEXT(pItem);
2781 pItem->type = KDBUS_MATCH_BLOOM;
2782 pItem->size = KDBUS_PART_HEADER_SIZE + KDBUS_BLOOM_SIZE_BYTES;
2783 strncpy(pItem->data, pInterface, KDBUS_BLOOM_SIZE_BYTES);
2787 if(ioctl(fd, KDBUS_CMD_MATCH_ADD, pCmd_match))
2790 dbus_set_error(error,_dbus_error_from_errno (errno), "error adding match: %s", _dbus_strerror (errno));
2791 _dbus_verbose("Failed adding match bus rule %s,\nerror: %d, %m\n", rule, errno);
2794 _dbus_verbose("Added match bus rule %s\n", rule);
2804 * Opposing to dbus, in kdbus removes all match rules with given
2805 * cookie, which now is equal to uniqe id.
2807 * In kdbus this function will not block
2809 * @param connection connection to the message bus
2810 * @param error location to store any errors - may be NULL
2812 void dbus_bus_remove_match_kdbus (DBusConnection *connection, DBusError *error)
2814 struct kdbus_cmd_match __attribute__ ((__aligned__(8))) cmd;
2817 dbus_connection_get_socket(connection, &fd);
2818 cmd.cookie = strtoull(dbus_bus_get_unique_name(connection), NULL , 10);
2819 cmd.id = cmd.cookie;
2820 cmd.size = sizeof(struct kdbus_cmd_match);
2822 if(ioctl(fd, KDBUS_CMD_MATCH_ADD, &cmd))
2825 dbus_set_error(error,_dbus_error_from_errno (errno), "error removing match: %s", _dbus_strerror (errno));
2826 _dbus_verbose("Failed removing match rule; error: %d, %m\n", errno);
2829 _dbus_verbose("Match rule removed correctly.\n");