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>
31 #define KDBUS_ALIGN8(l) (((l) + 7) & ~7)
32 #define KDBUS_PART_HEADER_SIZE offsetof(struct kdbus_item, data)
33 #define KDBUS_ITEM_SIZE(s) KDBUS_ALIGN8((s) + KDBUS_PART_HEADER_SIZE)
35 #define KDBUS_PART_NEXT(part) \
36 (typeof(part))(((uint8_t *)part) + KDBUS_ALIGN8((part)->size))
37 #define KDBUS_PART_FOREACH(part, head, first) \
38 for (part = (head)->first; \
39 (uint8_t *)(part) < (uint8_t *)(head) + (head)->size; \
40 part = KDBUS_PART_NEXT(part))
41 #define RECEIVE_POOL_SIZE (10 * 1024LU * 1024LU)
42 #define MEMFD_SIZE_THRESHOLD (2 * 1024 * 1024LU) // over this memfd is used
44 #define KDBUS_DECODE_DEBUG 1
48 * Opaque object representing a socket file descriptor transport.
50 typedef struct DBusTransportSocket DBusTransportSocket;
53 * Implementation details of DBusTransportSocket. All members are private.
55 struct DBusTransportSocket
57 DBusTransport base; /**< Parent instance */
58 int fd; /**< File descriptor. */
59 DBusWatch *read_watch; /**< Watch for readability. */
60 DBusWatch *write_watch; /**< Watch for writability. */
62 int max_bytes_read_per_iteration; /**< To avoid blocking too long. */
63 int max_bytes_written_per_iteration; /**< To avoid blocking too long. */
65 int message_bytes_written; /**< Number of bytes of current
66 * outgoing message that have
69 DBusString encoded_outgoing; /**< Encoded version of current
72 DBusString encoded_incoming; /**< Encoded version of current
76 int memfd; /* File descriptor to memory
77 * pool from Kdbus kernel module */
83 socket_get_socket_fd (DBusTransport *transport,
86 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
88 *fd_p = socket_transport->fd;
93 //static void check_read_watch (DBusTransport *transport);
96 * Adds locally generated message to received messages queue
99 static dbus_bool_t add_message_to_received(DBusMessage *message, DBusTransport *transport)
101 DBusList *message_link;
103 message_link = _dbus_list_alloc_link (message);
104 if (message_link == NULL)
106 /* it's OK to unref this, nothing that could have attached a callback
107 * has ever seen it */
108 dbus_message_unref (message);
112 _dbus_connection_queue_synthesized_message_link(transport->connection, message_link);
113 // check_read_watch(transport);
118 /*static void kdbus_debug_print_bytes(struct DBusString *data, int size)
122 fprintf (stderr, "\ndata:\n");
123 for(i=0; i < size; i++)
125 fprintf (stderr, "%02x", _dbus_string_get_byte(data,i));
127 fprintf (stderr, "\nsize: %d, i: %lu\n", size, i);
131 static int kdbus_init_memfd(DBusTransportSocket* socket_transport)
136 if(socket_transport->memfd == -1)
138 ret = ioctl(socket_transport->fd, KDBUS_CMD_MEMFD_NEW, &memfd);
140 _dbus_verbose("KDBUS_CMD_MEMFD_NEW failed: \n");
144 socket_transport->memfd = memfd;
145 _dbus_verbose("kdbus_init_memfd: %d!!\n", socket_transport->memfd);
151 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)
153 struct kdbus_msg* msg;
156 msg_size = sizeof(struct kdbus_msg);
158 if(use_memfd == TRUE) // bulk data - memfd - encoded and plain
159 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_memfd));
161 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
163 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
167 msg_size += KDBUS_ITEM_SIZE(sizeof(int)*fds_count);
170 msg_size += KDBUS_ITEM_SIZE(strlen(name) + 1);
171 else if (dst_id == KDBUS_DST_ID_BROADCAST)
172 msg_size += KDBUS_PART_HEADER_SIZE + KDBUS_BLOOM_SIZE_BYTES;
174 msg = malloc(msg_size);
177 _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
181 memset(msg, 0, msg_size);
182 msg->size = msg_size;
183 msg->payload_type = KDBUS_PAYLOAD_DBUS1;
184 msg->dst_id = name ? 0 : dst_id;
189 static int kdbus_write_msg(DBusTransportSocket *transport, DBusMessage *message, dbus_bool_t encoded)
191 struct kdbus_msg *msg;
192 struct kdbus_item *item;
194 uint64_t dst_id = KDBUS_DST_ID_BROADCAST;
195 const DBusString *header;
196 const DBusString *body;
197 uint64_t ret_size = 0;
198 uint64_t body_size = 0;
199 uint64_t header_size = 0;
201 dbus_bool_t use_memfd;
206 // determine name and destination id
207 if((name = dbus_message_get_destination(message)))
209 dst_id = KDBUS_DST_ID_WELL_KNOWN_NAME;
211 if((name[0] == ':') && (name[1] == '1') && (name[2] == '.')) /* if name starts with ":1." it is a unique name and should be send as number */
213 dst_id = strtoll(&name[3], NULL, 10);
220 ret_size = _dbus_string_get_length (&transport->encoded_outgoing);
223 _dbus_message_get_network_data (message, &header, &body);
224 header_size = _dbus_string_get_length(header);
225 body_size = _dbus_string_get_length(body);
226 ret_size = header_size + body_size;
229 // check if message size is big enough to use memfd kdbus transport
230 use_memfd = ret_size > MEMFD_SIZE_THRESHOLD ? TRUE : FALSE;
231 if(use_memfd) kdbus_init_memfd(transport);
233 _dbus_message_get_unix_fds(message, &unix_fds, &fds_count);
235 // init basic message fields
236 msg = kdbus_init_msg(name, dst_id, body_size, use_memfd, fds_count);
237 msg->cookie = dbus_message_get_serial(message);
238 msg->src_id = strtoll(dbus_bus_get_unique_name(transport->base.connection), NULL , 10);
240 // build message contents
243 // case 1 - bulk data transfer - memfd - encoded and plain
246 ret = ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 0);
249 _dbus_verbose("memfd sealing failed: \n");
253 buf = mmap(NULL, ret_size, PROT_WRITE, MAP_SHARED, transport->memfd, 0);
254 if (buf == MAP_FAILED)
256 _dbus_verbose("mmap() fd=%i failed:%m", transport->memfd);
261 memcpy(buf, &transport->encoded_outgoing, ret_size);
264 memcpy(buf, _dbus_string_get_const_data(header), header_size);
267 memcpy(buf, _dbus_string_get_const_data(body), body_size);
272 munmap(buf, ret_size);
274 // seal data - kdbus module needs it
275 ret = ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 1);
277 _dbus_verbose("memfd sealing failed: %d (%m)\n", errno);
282 item->type = KDBUS_MSG_PAYLOAD_MEMFD;
283 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_memfd);
284 item->memfd.size = ret_size;
285 item->memfd.fd = transport->memfd;
286 // case 2 - small encoded - don't use memfd
288 _dbus_verbose("sending encoded data\n");
290 item->type = KDBUS_MSG_PAYLOAD_VEC;
291 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec);
292 item->vec.address = (unsigned long) &transport->encoded_outgoing;
293 item->vec.size = _dbus_string_get_length (&transport->encoded_outgoing);
295 // case 3 - small not encoded - don't use memfd
297 _dbus_verbose("sending normal vector data\n");
299 item->type = KDBUS_MSG_PAYLOAD_VEC;
300 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec);
301 item->vec.address = (unsigned long) _dbus_string_get_const_data(header);
302 item->vec.size = header_size;
306 _dbus_verbose("body attaching\n");
307 item = KDBUS_PART_NEXT(item);
308 item->type = KDBUS_MSG_PAYLOAD_VEC;
309 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec);
310 item->vec.address = (unsigned long) _dbus_string_get_const_data(body);
311 item->vec.size = body_size;
317 item = KDBUS_PART_NEXT(item);
318 item->type = KDBUS_MSG_FDS;
319 item->size = KDBUS_PART_HEADER_SIZE + (sizeof(int) * fds_count);
320 memcpy(item->fds, unix_fds, sizeof(int) * fds_count);
325 item = KDBUS_PART_NEXT(item);
326 item->type = KDBUS_MSG_DST_NAME;
327 item->size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1;
328 strcpy(item->str, name);
330 else if (dst_id == KDBUS_DST_ID_BROADCAST)
332 item = KDBUS_PART_NEXT(item);
333 item->type = KDBUS_MSG_BLOOM;
334 item->size = KDBUS_PART_HEADER_SIZE + KDBUS_BLOOM_SIZE_BYTES;
335 strncpy(item->data, dbus_message_get_interface(message), KDBUS_BLOOM_SIZE_BYTES);
339 if (ioctl(transport->fd, KDBUS_CMD_MSG_SEND, msg))
343 if((errno == ESRCH) || (errno == ENXIO)) //when recipient is not available on the bus
345 DBusMessage *errMessage = NULL;
346 dbus_uint32_t replySerial;
348 errMessage = generate_local_error_message(msg->cookie, DBUS_ERROR_SERVICE_UNKNOWN, NULL);
349 if(errMessage == NULL)
354 replySerial = dbus_message_get_reply_serial(message);
356 dbus_message_set_reply_serial(errMessage, replySerial);
357 if (!add_message_to_received(errMessage, (DBusTransport*)transport))
361 _dbus_verbose("kdbus error sending message: err %d (%m)\n", errno);
370 static int64_t kdbus_NameQuery(DBusTransport *transport, char* name, int fd)
372 struct kdbus_cmd_name_info *msg;
373 struct kdbus_item *item;
378 item_size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1;
379 item_size = (item_size < 56) ? 56 : item_size;
380 size = sizeof(struct kdbus_cmd_name_info) + item_size;
385 _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
389 memset(msg, 0, size);
393 item->type = KDBUS_NAME_INFO_ITEM_NAME;
394 item->size = item_size;
395 strcpy(item->str, name);
398 if ((ret = ioctl(fd, KDBUS_CMD_NAME_QUERY, msg)))
411 static dbus_bool_t emulateOrgFreedesktopDBus(DBusTransport *transport, DBusMessage *message, int fd)
415 if(!strcmp(dbus_message_get_member(message), "GetNameOwner"))
419 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
420 _dbus_verbose ("Name to discover: %s !!!! !!!!\n", name);
421 ret = kdbus_NameQuery(transport, name, fd);
422 if(ret > 0) //unique id of the name
425 DBusMessageIter args;
426 char unique_name[(unsigned int)(sizeof(ret)*2.5 + 4)];
427 const char* pString = unique_name;
429 sprintf(unique_name, ":1.%lld", (long long int)ret);
430 _dbus_verbose("Unique name discovered:%s!!! !!!!\n", unique_name);
431 reply = dbus_message_new_method_return(message);
434 dbus_message_iter_init_append(reply, &args);
435 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pString))
437 if(add_message_to_received(reply, transport))
440 else if(ret == -ENOENT) //name has no owner
442 DBusMessage *errMessage;
443 dbus_uint32_t replySerial;
445 errMessage = generate_local_error_message(1, DBUS_ERROR_NAME_HAS_NO_OWNER, NULL);
446 if(errMessage == NULL)
448 replySerial = dbus_message_get_reply_serial(message);
450 dbus_message_set_reply_serial(errMessage, replySerial);
451 if (add_message_to_received(errMessage, transport))
455 _dbus_verbose("kdbus error sending name query: err %d (%m)\n", errno);
457 else if(!strcmp(dbus_message_get_member(message), "NameHasOwner"))
461 DBusMessageIter args;
464 dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
465 _dbus_verbose ("Name to discover: %s !!!! !!!!\n", name);
466 ret = kdbus_NameQuery(transport, name, fd);
468 result = (ret > 0) ? TRUE : FALSE;
469 _dbus_verbose("Discovery: %d !!! !!!!\n", (int)result);
470 reply = dbus_message_new_method_return(message);
473 dbus_message_iter_init_append(reply, &args);
474 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_BOOLEAN, &result))
476 if(add_message_to_received(reply, transport))
479 else //temporarily we send that info but methods below should be implemented
482 dbus_uint32_t replySerial;
484 reply = generate_local_error_message(1, DBUS_ERROR_UNKNOWN_METHOD, NULL);
487 replySerial = dbus_message_get_reply_serial(message);
489 dbus_message_set_reply_serial(reply, replySerial);
490 if(add_message_to_received(reply, transport))
493 /*else if(!strcmp(dbus_message_get_member(message), "ListNames"))
497 else if(!strcmp(dbus_message_get_member(message), "ListActivatableNames"))
501 else if(!strcmp(dbus_message_get_member(message), "StartServiceByName"))
505 else if(!strcmp(dbus_message_get_member(message), "UpdateActivationEnvironment"))
509 else if(!strcmp(dbus_message_get_member(message), "GetConnectionUnixUser"))
513 else if(!strcmp(dbus_message_get_member(message), "GetId"))
521 #if KDBUS_DECODE_DEBUG == 1
522 static char *msg_id(uint64_t id, char *buf)
528 sprintf(buf, "%llu", (unsigned long long)id);
532 struct kdbus_enum_table {
536 #define _STRINGIFY(x) #x
537 #define STRINGIFY(x) _STRINGIFY(x)
538 #define ELEMENTSOF(x) (sizeof(x)/sizeof((x)[0]))
539 #define TABLE(what) static struct kdbus_enum_table kdbus_table_##what[]
540 #define ENUM(_id) { .id=_id, .name=STRINGIFY(_id) }
541 #define LOOKUP(what) \
542 const char *enum_##what(long long id) { \
544 for (i = 0; i < ELEMENTSOF(kdbus_table_##what); i++) \
545 if (id == kdbus_table_##what[i].id) \
546 return kdbus_table_##what[i].name; \
549 const char *enum_MSG(long long id);
551 ENUM(_KDBUS_MSG_NULL),
552 ENUM(KDBUS_MSG_PAYLOAD_VEC),
553 ENUM(KDBUS_MSG_PAYLOAD_OFF),
554 ENUM(KDBUS_MSG_PAYLOAD_MEMFD),
556 ENUM(KDBUS_MSG_BLOOM),
557 ENUM(KDBUS_MSG_DST_NAME),
558 ENUM(KDBUS_MSG_SRC_CREDS),
559 ENUM(KDBUS_MSG_SRC_PID_COMM),
560 ENUM(KDBUS_MSG_SRC_TID_COMM),
561 ENUM(KDBUS_MSG_SRC_EXE),
562 ENUM(KDBUS_MSG_SRC_CMDLINE),
563 ENUM(KDBUS_MSG_SRC_CGROUP),
564 ENUM(KDBUS_MSG_SRC_CAPS),
565 ENUM(KDBUS_MSG_SRC_SECLABEL),
566 ENUM(KDBUS_MSG_SRC_AUDIT),
567 ENUM(KDBUS_MSG_SRC_NAMES),
568 ENUM(KDBUS_MSG_TIMESTAMP),
569 ENUM(KDBUS_MSG_NAME_ADD),
570 ENUM(KDBUS_MSG_NAME_REMOVE),
571 ENUM(KDBUS_MSG_NAME_CHANGE),
572 ENUM(KDBUS_MSG_ID_ADD),
573 ENUM(KDBUS_MSG_ID_REMOVE),
574 ENUM(KDBUS_MSG_REPLY_TIMEOUT),
575 ENUM(KDBUS_MSG_REPLY_DEAD),
578 const char *enum_PAYLOAD(long long id);
580 ENUM(KDBUS_PAYLOAD_KERNEL),
581 ENUM(KDBUS_PAYLOAD_DBUS1),
582 ENUM(KDBUS_PAYLOAD_GVARIANT),
586 static int put_message_into_data(DBusMessage *message, char* data)
589 const DBusString *header;
590 const DBusString *body;
593 dbus_message_lock (message);
594 _dbus_message_get_network_data (message, &header, &body);
595 ret_size = _dbus_string_get_length(header);
596 memcpy(data, _dbus_string_get_const_data(header), ret_size);
598 size = _dbus_string_get_length(body);
599 memcpy(data, _dbus_string_get_const_data(body), size);
605 static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTransportSocket* socket_transport, int* fds, int* n_fds)
607 const struct kdbus_item *item = msg->items;
609 DBusMessage *message = NULL;
610 DBusMessageIter args;
611 char dbus_name[(unsigned int)(sizeof(item->name_change.new_id)*2.5 + 4)];
612 const char* pDBusName = dbus_name;
613 const char* dbus = "org.freedesktop.DBus";
614 const char* emptyString = "";
615 const char* pString = NULL;
617 #if KDBUS_DECODE_DEBUG == 1
621 #if KDBUS_DECODE_DEBUG == 1
622 _dbus_verbose("MESSAGE: %s (%llu bytes) flags=0x%llx, %s → %s, cookie=%llu, timeout=%llu\n",
623 enum_PAYLOAD(msg->payload_type), (unsigned long long) msg->size,
624 (unsigned long long) msg->flags,
625 msg_id(msg->src_id, buf), msg_id(msg->dst_id, buf),
626 (unsigned long long) msg->cookie, (unsigned long long) msg->timeout_ns);
630 mmap_ptr = socket_transport->kdbus_mmap_ptr;
632 KDBUS_PART_FOREACH(item, msg, items)
634 if (item->size <= KDBUS_PART_HEADER_SIZE)
636 _dbus_verbose(" +%s (%llu bytes) invalid data record\n", enum_MSG(item->type), item->size);
637 continue; //todo ??? continue (because dbus will find error if it is in important part) or break
642 case KDBUS_MSG_PAYLOAD_OFF:
644 uint64_t size = item->vec.size;
646 memcpy(data, (char *)mmap_ptr + item->vec.offset, item->vec.size);
647 data += item->vec.size;
648 ret_size += item->vec.size;
650 _dbus_verbose(" +%s (%llu bytes) off=%llu size=%llu\n",
651 enum_MSG(item->type), item->size,
652 (unsigned long long)item->vec.offset,
653 (unsigned long long)size);
657 case KDBUS_MSG_PAYLOAD_MEMFD:
662 size = item->memfd.size;
664 _dbus_verbose("memfd.size : %llu\n", (unsigned long long)size);
666 buf = mmap(NULL, size, PROT_READ , MAP_SHARED, item->memfd.fd, 0);
668 if (buf == MAP_FAILED)
670 _dbus_verbose("mmap() fd=%i failed:%m", item->memfd.fd);
674 memcpy(data, buf, size);
680 _dbus_verbose(" +%s (%llu bytes) off=%llu size=%llu\n",
681 enum_MSG(item->type), item->size,
682 (unsigned long long)item->vec.offset,
683 (unsigned long long)item->vec.size);
691 *n_fds = (item->size - KDBUS_PART_HEADER_SIZE) / sizeof(int);
692 memcpy(fds, item->fds, *n_fds * sizeof(int));
693 for (i = 0; i < *n_fds; i++)
694 _dbus_fd_set_close_on_exec(fds[i]);
698 #if KDBUS_DECODE_DEBUG == 1
699 case KDBUS_MSG_SRC_CREDS:
700 _dbus_verbose(" +%s (%llu bytes) uid=%lld, gid=%lld, pid=%lld, tid=%lld, starttime=%lld\n",
701 enum_MSG(item->type), item->size,
702 item->creds.uid, item->creds.gid,
703 item->creds.pid, item->creds.tid,
704 item->creds.starttime);
707 case KDBUS_MSG_SRC_PID_COMM:
708 case KDBUS_MSG_SRC_TID_COMM:
709 case KDBUS_MSG_SRC_EXE:
710 case KDBUS_MSG_SRC_CGROUP:
711 case KDBUS_MSG_SRC_SECLABEL:
712 case KDBUS_MSG_DST_NAME:
713 _dbus_verbose(" +%s (%llu bytes) '%s' (%zu)\n",
714 enum_MSG(item->type), item->size, item->str, strlen(item->str));
717 case KDBUS_MSG_SRC_CMDLINE:
718 case KDBUS_MSG_SRC_NAMES: {
719 size_t size = item->size - KDBUS_PART_HEADER_SIZE;
720 const char *str = item->str;
723 _dbus_verbose(" +%s (%llu bytes) ", enum_MSG(item->type), item->size);
725 _dbus_verbose("'%s' ", str);
726 size -= strlen(str) + 1;
727 str += strlen(str) + 1;
731 _dbus_verbose("(%d string%s)\n", count, (count == 1) ? "" : "s");
735 case KDBUS_MSG_SRC_AUDIT:
736 _dbus_verbose(" +%s (%llu bytes) loginuid=%llu sessionid=%llu\n",
737 enum_MSG(item->type), item->size,
738 (unsigned long long)item->data64[0],
739 (unsigned long long)item->data64[1]);
742 case KDBUS_MSG_SRC_CAPS: {
747 _dbus_verbose(" +%s (%llu bytes) len=%llu bytes)\n",
748 enum_MSG(item->type), item->size,
749 (unsigned long long)item->size - KDBUS_PART_HEADER_SIZE);
752 n = (item->size - KDBUS_PART_HEADER_SIZE) / 4 / sizeof(uint32_t);
754 _dbus_verbose(" CapInh=");
755 for (i = 0; i < n; i++)
756 _dbus_verbose("%08x", cap[(0 * n) + (n - i - 1)]);
758 _dbus_verbose(" CapPrm=");
759 for (i = 0; i < n; i++)
760 _dbus_verbose("%08x", cap[(1 * n) + (n - i - 1)]);
762 _dbus_verbose(" CapEff=");
763 for (i = 0; i < n; i++)
764 _dbus_verbose("%08x", cap[(2 * n) + (n - i - 1)]);
766 _dbus_verbose(" CapInh=");
767 for (i = 0; i < n; i++)
768 _dbus_verbose("%08x", cap[(3 * n) + (n - i - 1)]);
773 case KDBUS_MSG_TIMESTAMP:
774 _dbus_verbose(" +%s (%llu bytes) realtime=%lluns monotonic=%lluns\n",
775 enum_MSG(item->type), item->size,
776 (unsigned long long)item->timestamp.realtime_ns,
777 (unsigned long long)item->timestamp.monotonic_ns);
781 case KDBUS_MSG_REPLY_TIMEOUT:
782 _dbus_verbose(" +%s (%llu bytes) cookie=%llu\n",
783 enum_MSG(item->type), item->size, msg->cookie_reply);
785 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NO_REPLY, NULL);
792 ret_size = put_message_into_data(message, data);
795 case KDBUS_MSG_NAME_ADD:
796 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
797 enum_MSG(item->type), (unsigned long long) item->size,
798 item->name_change.name, item->name_change.old_id,
799 item->name_change.new_id, item->name_change.flags);
801 message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal
802 dbus, // interface name of the signal
803 "NameOwnerChanged"); // name of the signal
810 sprintf(dbus_name,":1.%llu",item->name_change.new_id);
811 pString = item->name_change.name;
812 _dbus_verbose ("Name added: %s\n", pString);
813 dbus_message_iter_init_append(message, &args);
814 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING,&pString))
819 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &emptyString))
824 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
830 dbus_message_set_sender(message, dbus);
831 dbus_message_set_serial(message, 1);
833 ret_size = put_message_into_data(message, data);
836 case KDBUS_MSG_NAME_REMOVE:
837 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
838 enum_MSG(item->type), (unsigned long long) item->size,
839 item->name_change.name, item->name_change.old_id,
840 item->name_change.new_id, item->name_change.flags);
842 message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal
843 dbus, // interface name of the signal
844 "NameOwnerChanged"); // name of the signal
851 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
852 pString = item->name_change.name;
853 _dbus_verbose ("Name removed: %s\n", pString);
854 dbus_message_iter_init_append(message, &args);
855 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING,&pString))
860 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
865 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &emptyString))
871 dbus_message_set_sender(message, dbus);
872 dbus_message_set_serial(message, 1);
874 ret_size = put_message_into_data(message, data);
877 case KDBUS_MSG_NAME_CHANGE:
878 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
879 enum_MSG(item->type), (unsigned long long) item->size,
880 item->name_change.name, item->name_change.old_id,
881 item->name_change.new_id, item->name_change.flags);
883 message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal
884 dbus, // interface name of the signal
885 "NameOwnerChanged"); // name of the signal
892 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
893 pString = item->name_change.name;
894 _dbus_verbose ("Name changed: %s\n", pString);
895 dbus_message_iter_init_append(message, &args);
896 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING,&pString))
901 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
906 sprintf(&dbus_name[3],"%llu",item->name_change.new_id);
907 _dbus_verbose ("New id: %s\n", pDBusName);
908 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
914 dbus_message_set_sender(message, dbus);
915 dbus_message_set_serial(message, 1);
917 ret_size = put_message_into_data(message, data);
920 case KDBUS_MSG_ID_ADD:
921 _dbus_verbose(" +%s (%llu bytes) id=%llu flags=%llu\n",
922 enum_MSG(item->type), (unsigned long long) item->size,
923 (unsigned long long) item->id_change.id,
924 (unsigned long long) item->id_change.flags);
926 message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal
927 dbus, // interface name of the signal
928 "NameOwnerChanged"); // name of the signal
935 sprintf(dbus_name,":1.%llu",item->id_change.id);
936 dbus_message_iter_init_append(message, &args);
937 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
942 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &emptyString))
947 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
953 dbus_message_set_sender(message, dbus);
954 dbus_message_set_serial(message, 1);
956 ret_size = put_message_into_data(message, data);
959 case KDBUS_MSG_ID_REMOVE:
960 _dbus_verbose(" +%s (%llu bytes) id=%llu flags=%llu\n",
961 enum_MSG(item->type), (unsigned long long) item->size,
962 (unsigned long long) item->id_change.id,
963 (unsigned long long) item->id_change.flags);
965 message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal
966 dbus, // interface name of the signal
967 "NameOwnerChanged"); // name of the signal
974 sprintf(dbus_name,":1.%llu",item->id_change.id);
975 dbus_message_iter_init_append(message, &args);
976 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
981 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
986 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &emptyString))
992 dbus_message_set_sender(message, dbus);
993 dbus_message_set_serial(message, 1);
995 ret_size = put_message_into_data(message, data);
997 #if KDBUS_DECODE_DEBUG == 1
999 _dbus_verbose(" +%s (%llu bytes)\n", enum_MSG(item->type), item->size);
1005 #if KDBUS_DECODE_DEBUG == 1
1007 if ((char *)item - ((char *)msg + msg->size) >= 8)
1008 _dbus_verbose("invalid padding at end of message\n");
1013 dbus_message_unref(message);
1017 static int kdbus_read_message(DBusTransportSocket *socket_transport, DBusString *buffer, int* fds, int* n_fds)
1020 uint64_t __attribute__ ((__aligned__(8))) offset;
1021 struct kdbus_msg *msg;
1024 _dbus_assert (socket_transport->max_bytes_read_per_iteration >= 0);
1025 if (!_dbus_string_lengthen (buffer, socket_transport->max_bytes_read_per_iteration))
1030 data = _dbus_string_get_data_len (buffer, 0, socket_transport->max_bytes_read_per_iteration);
1033 if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RECV, &offset) < 0)
1037 _dbus_verbose("kdbus error receiving message: %d (%m)\n", errno);
1038 _dbus_string_set_length (buffer, 0);
1042 msg = (struct kdbus_msg *)((char*)socket_transport->kdbus_mmap_ptr + offset);
1044 ret_size = kdbus_decode_msg(msg, data, socket_transport, fds, n_fds);
1045 _dbus_string_set_length (buffer, ret_size);
1048 if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RELEASE, &offset) < 0)
1052 _dbus_verbose("kdbus error freeing message: %d (%m)\n", errno);
1060 free_watches (DBusTransport *transport)
1062 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1064 _dbus_verbose ("start\n");
1066 if (socket_transport->read_watch)
1068 if (transport->connection)
1069 _dbus_connection_remove_watch_unlocked (transport->connection,
1070 socket_transport->read_watch);
1071 _dbus_watch_invalidate (socket_transport->read_watch);
1072 _dbus_watch_unref (socket_transport->read_watch);
1073 socket_transport->read_watch = NULL;
1076 if (socket_transport->write_watch)
1078 if (transport->connection)
1079 _dbus_connection_remove_watch_unlocked (transport->connection,
1080 socket_transport->write_watch);
1081 _dbus_watch_invalidate (socket_transport->write_watch);
1082 _dbus_watch_unref (socket_transport->write_watch);
1083 socket_transport->write_watch = NULL;
1086 _dbus_verbose ("end\n");
1090 socket_finalize (DBusTransport *transport)
1092 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1094 _dbus_verbose ("\n");
1096 free_watches (transport);
1098 _dbus_string_free (&socket_transport->encoded_outgoing);
1099 _dbus_string_free (&socket_transport->encoded_incoming);
1101 _dbus_transport_finalize_base (transport);
1103 _dbus_assert (socket_transport->read_watch == NULL);
1104 _dbus_assert (socket_transport->write_watch == NULL);
1106 dbus_free (transport);
1110 check_write_watch (DBusTransport *transport)
1112 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1115 if (transport->connection == NULL)
1118 if (transport->disconnected)
1120 _dbus_assert (socket_transport->write_watch == NULL);
1124 _dbus_transport_ref (transport);
1126 if (_dbus_transport_get_is_authenticated (transport))
1127 needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection);
1130 if (transport->send_credentials_pending)
1134 DBusAuthState auth_state;
1136 auth_state = _dbus_auth_do_work (transport->auth);
1138 /* If we need memory we install the write watch just in case,
1139 * if there's no need for it, it will get de-installed
1140 * next time we try reading.
1142 if (auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND ||
1143 auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY)
1150 _dbus_verbose ("check_write_watch(): needed = %d on connection %p watch %p fd = %d outgoing messages exist %d\n",
1151 needed, transport->connection, socket_transport->write_watch,
1152 socket_transport->fd,
1153 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1155 _dbus_connection_toggle_watch_unlocked (transport->connection,
1156 socket_transport->write_watch,
1159 _dbus_transport_unref (transport);
1163 check_read_watch (DBusTransport *transport)
1165 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1166 dbus_bool_t need_read_watch;
1168 _dbus_verbose ("fd = %d\n",socket_transport->fd);
1170 if (transport->connection == NULL)
1173 if (transport->disconnected)
1175 _dbus_assert (socket_transport->read_watch == NULL);
1179 _dbus_transport_ref (transport);
1181 if (_dbus_transport_get_is_authenticated (transport))
1183 (_dbus_counter_get_size_value (transport->live_messages) < transport->max_live_messages_size) &&
1184 (_dbus_counter_get_unix_fd_value (transport->live_messages) < transport->max_live_messages_unix_fds);
1187 if (transport->receive_credentials_pending)
1188 need_read_watch = TRUE;
1191 /* The reason to disable need_read_watch when not WAITING_FOR_INPUT
1192 * is to avoid spinning on the file descriptor when we're waiting
1193 * to write or for some other part of the auth process
1195 DBusAuthState auth_state;
1197 auth_state = _dbus_auth_do_work (transport->auth);
1199 /* If we need memory we install the read watch just in case,
1200 * if there's no need for it, it will get de-installed
1201 * next time we try reading. If we're authenticated we
1202 * install it since we normally have it installed while
1205 if (auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT ||
1206 auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY ||
1207 auth_state == DBUS_AUTH_STATE_AUTHENTICATED)
1208 need_read_watch = TRUE;
1210 need_read_watch = FALSE;
1214 _dbus_verbose (" setting read watch enabled = %d\n", need_read_watch);
1215 _dbus_connection_toggle_watch_unlocked (transport->connection,
1216 socket_transport->read_watch,
1219 _dbus_transport_unref (transport);
1223 do_io_error (DBusTransport *transport)
1225 _dbus_transport_ref (transport);
1226 _dbus_transport_disconnect (transport);
1227 _dbus_transport_unref (transport);
1230 #ifdef DBUS_AUTHENTICATION
1231 /* return value is whether we successfully read any new data. */
1233 read_data_into_auth (DBusTransport *transport,
1236 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1242 _dbus_auth_get_buffer (transport->auth, &buffer);
1244 bytes_read = kdbus_read_message(socket_transport, buffer);
1246 _dbus_auth_return_buffer (transport->auth, buffer,
1247 bytes_read > 0 ? bytes_read : 0);
1251 _dbus_verbose (" read %d bytes in auth phase\n", bytes_read);
1254 else if (bytes_read < 0)
1256 /* EINTR already handled for us */
1258 if (_dbus_get_is_errno_enomem ())
1262 else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1263 ; /* do nothing, just return FALSE below */
1266 _dbus_verbose ("Error reading from remote app: %s\n",
1267 _dbus_strerror_from_errno ());
1268 do_io_error (transport);
1275 _dbus_assert (bytes_read == 0);
1277 _dbus_verbose ("Disconnected from remote app\n");
1278 do_io_error (transport);
1284 /* Return value is whether we successfully wrote any bytes */
1286 write_data_from_auth (DBusTransport *transport)
1288 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1290 const DBusString *buffer;
1292 if (!_dbus_auth_get_bytes_to_send (transport->auth,
1296 bytes_written = _dbus_write_socket (socket_transport->fd,
1298 0, _dbus_string_get_length (buffer));
1300 if (bytes_written > 0)
1302 _dbus_auth_bytes_sent (transport->auth, bytes_written);
1305 else if (bytes_written < 0)
1307 /* EINTR already handled for us */
1309 if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1313 _dbus_verbose ("Error writing to remote app: %s\n",
1314 _dbus_strerror_from_errno ());
1315 do_io_error (transport);
1324 exchange_credentials (DBusTransport *transport,
1325 dbus_bool_t do_reading,
1326 dbus_bool_t do_writing)
1328 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1329 DBusError error = DBUS_ERROR_INIT;
1331 _dbus_verbose ("exchange_credentials: do_reading = %d, do_writing = %d\n",
1332 do_reading, do_writing);
1334 if (do_writing && transport->send_credentials_pending)
1336 if (_dbus_send_credentials_socket (socket_transport->fd,
1339 transport->send_credentials_pending = FALSE;
1343 _dbus_verbose ("Failed to write credentials: %s\n", error.message);
1344 dbus_error_free (&error);
1345 do_io_error (transport);
1349 if (do_reading && transport->receive_credentials_pending)
1351 /* FIXME this can fail due to IO error _or_ OOM, broken
1352 * (somewhat tricky to fix since the OOM error can be set after
1353 * we already read the credentials byte, so basically we need to
1354 * separate reading the byte and storing it in the
1355 * transport->credentials). Does not really matter for now
1356 * because storing in credentials never actually fails on unix.
1358 if (_dbus_read_credentials_socket (socket_transport->fd,
1359 transport->credentials,
1362 transport->receive_credentials_pending = FALSE;
1366 _dbus_verbose ("Failed to read credentials %s\n", error.message);
1367 dbus_error_free (&error);
1368 do_io_error (transport);
1372 if (!(transport->send_credentials_pending ||
1373 transport->receive_credentials_pending))
1375 if (!_dbus_auth_set_credentials (transport->auth,
1376 transport->credentials))
1384 do_authentication (DBusTransport *transport,
1385 dbus_bool_t do_reading,
1386 dbus_bool_t do_writing,
1387 dbus_bool_t *auth_completed)
1390 dbus_bool_t orig_auth_state;
1394 orig_auth_state = _dbus_transport_get_is_authenticated (transport);
1396 /* This is essential to avoid the check_write_watch() at the end,
1397 * we don't want to add a write watch in do_iteration before
1398 * we try writing and get EAGAIN
1400 if (orig_auth_state)
1403 *auth_completed = FALSE;
1407 _dbus_transport_ref (transport);
1409 while (!_dbus_transport_get_is_authenticated (transport) &&
1410 _dbus_transport_get_is_connected (transport))
1412 if (!exchange_credentials (transport, do_reading, do_writing))
1418 if (transport->send_credentials_pending ||
1419 transport->receive_credentials_pending)
1421 _dbus_verbose ("send_credentials_pending = %d receive_credentials_pending = %d\n",
1422 transport->send_credentials_pending,
1423 transport->receive_credentials_pending);
1427 #define TRANSPORT_SIDE(t) ((t)->is_server ? "server" : "client")
1428 switch (_dbus_auth_do_work (transport->auth))
1430 case DBUS_AUTH_STATE_WAITING_FOR_INPUT:
1431 _dbus_verbose (" %s auth state: waiting for input\n",
1432 TRANSPORT_SIDE (transport));
1433 if (!do_reading || !read_data_into_auth (transport, &oom))
1437 case DBUS_AUTH_STATE_WAITING_FOR_MEMORY:
1438 _dbus_verbose (" %s auth state: waiting for memory\n",
1439 TRANSPORT_SIDE (transport));
1444 case DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND:
1445 _dbus_verbose (" %s auth state: bytes to send\n",
1446 TRANSPORT_SIDE (transport));
1447 if (!do_writing || !write_data_from_auth (transport))
1451 case DBUS_AUTH_STATE_NEED_DISCONNECT:
1452 _dbus_verbose (" %s auth state: need to disconnect\n",
1453 TRANSPORT_SIDE (transport));
1454 do_io_error (transport);
1457 case DBUS_AUTH_STATE_AUTHENTICATED:
1458 _dbus_verbose (" %s auth state: authenticated\n",
1459 TRANSPORT_SIDE (transport));
1466 *auth_completed = (orig_auth_state != _dbus_transport_get_is_authenticated (transport));
1468 check_read_watch (transport);
1469 check_write_watch (transport);
1470 _dbus_transport_unref (transport);
1479 /* returns false on oom */
1481 do_writing (DBusTransport *transport)
1484 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1487 /* No messages without authentication! */
1488 if (!_dbus_transport_get_is_authenticated (transport))
1490 _dbus_verbose ("Not authenticated, not writing anything\n");
1494 if (transport->disconnected)
1496 _dbus_verbose ("Not connected, not writing anything\n");
1501 _dbus_verbose ("do_writing(), have_messages = %d, fd = %d\n",
1502 _dbus_connection_has_messages_to_send_unlocked (transport->connection),
1503 socket_transport->fd);
1509 while (!transport->disconnected && _dbus_connection_has_messages_to_send_unlocked (transport->connection))
1512 DBusMessage *message;
1513 const DBusString *header;
1514 const DBusString *body;
1515 int total_bytes_to_write;
1516 const char* pDestination;
1518 /* if (total > socket_transport->max_bytes_written_per_iteration)
1520 _dbus_verbose ("%d bytes exceeds %d bytes written per iteration, returning\n",
1521 total, socket_transport->max_bytes_written_per_iteration);
1525 message = _dbus_connection_get_message_to_send (transport->connection);
1526 _dbus_assert (message != NULL);
1527 dbus_message_lock (message);
1528 _dbus_message_get_network_data (message, &header, &body);
1529 total_bytes_to_write = _dbus_string_get_length(header) + _dbus_string_get_length(body);
1530 pDestination = dbus_message_get_destination(message);
1534 if(!strcmp(pDestination, "org.freedesktop.DBus"))
1536 if(emulateOrgFreedesktopDBus(transport, message, socket_transport->fd))
1537 bytes_written = total_bytes_to_write;
1543 if (_dbus_auth_needs_encoding (transport->auth))
1545 if (_dbus_string_get_length (&socket_transport->encoded_outgoing) == 0)
1547 if (!_dbus_auth_encode_data (transport->auth,
1548 header, &socket_transport->encoded_outgoing))
1554 if (!_dbus_auth_encode_data (transport->auth,
1555 body, &socket_transport->encoded_outgoing))
1557 _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
1563 total_bytes_to_write = _dbus_string_get_length (&socket_transport->encoded_outgoing);
1564 if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration)
1567 bytes_written = kdbus_write_msg(socket_transport, message, TRUE);
1571 if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration)
1574 bytes_written = kdbus_write_msg(socket_transport, message, FALSE);
1578 if (bytes_written < 0)
1580 /* EINTR already handled for us */
1582 /* For some discussion of why we also ignore EPIPE here, see
1583 * http://lists.freedesktop.org/archives/dbus/2008-March/009526.html
1586 if (_dbus_get_is_errno_eagain_or_ewouldblock () || _dbus_get_is_errno_epipe ())
1590 _dbus_verbose ("Error writing to remote app: %s\n", _dbus_strerror_from_errno ());
1591 do_io_error (transport);
1597 _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
1598 total_bytes_to_write);
1600 // total += bytes_written;
1601 socket_transport->message_bytes_written += bytes_written;
1603 _dbus_assert (socket_transport->message_bytes_written <=
1604 total_bytes_to_write);
1606 if (socket_transport->message_bytes_written == total_bytes_to_write)
1608 socket_transport->message_bytes_written = 0;
1609 _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
1610 _dbus_string_compact (&socket_transport->encoded_outgoing, 2048);
1612 _dbus_connection_message_sent_unlocked (transport->connection,
1625 /* returns false on out-of-memory */
1627 do_reading (DBusTransport *transport)
1629 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1635 _dbus_verbose ("fd = %d\n",socket_transport->fd);
1637 /* No messages without authentication! */
1638 if (!_dbus_transport_get_is_authenticated (transport))
1645 /* See if we've exceeded max messages and need to disable reading */
1646 check_read_watch (transport);
1648 _dbus_assert (socket_transport->read_watch != NULL ||
1649 transport->disconnected);
1651 if (transport->disconnected)
1654 if (!dbus_watch_get_enabled (socket_transport->read_watch))
1657 if (!_dbus_message_loader_get_unix_fds(transport->loader, &fds, &n_fds))
1659 _dbus_verbose ("Out of memory reading file descriptors\n");
1663 _dbus_message_loader_get_buffer (transport->loader, &buffer);
1665 if (_dbus_auth_needs_decoding (transport->auth))
1667 bytes_read = kdbus_read_message(socket_transport, &socket_transport->encoded_incoming, fds, &n_fds);
1669 _dbus_assert (_dbus_string_get_length (&socket_transport->encoded_incoming) == bytes_read);
1673 if (!_dbus_auth_decode_data (transport->auth,
1674 &socket_transport->encoded_incoming,
1677 _dbus_verbose ("Out of memory decoding incoming data\n");
1678 _dbus_message_loader_return_buffer (transport->loader,
1680 _dbus_string_get_length (buffer));
1685 _dbus_string_set_length (&socket_transport->encoded_incoming, 0);
1686 _dbus_string_compact (&socket_transport->encoded_incoming, 2048);
1690 bytes_read = kdbus_read_message(socket_transport, buffer, fds, &n_fds);
1692 if (bytes_read >= 0 && n_fds > 0)
1693 _dbus_verbose("Read %i unix fds\n", n_fds);
1695 _dbus_message_loader_return_buffer (transport->loader,
1697 bytes_read < 0 ? 0 : _dbus_string_get_length (buffer));
1698 _dbus_message_loader_return_unix_fds(transport->loader, fds, bytes_read < 0 ? 0 : n_fds);
1700 /* if (_dbus_auth_needs_decoding (transport->auth))
1702 bytes_read = kdbus_read_message(socket_transport, &socket_transport->encoded_incoming);
1704 _dbus_assert (_dbus_string_get_length (&socket_transport->encoded_incoming) ==
1711 _dbus_message_loader_get_buffer (transport->loader, &buffer);
1712 orig_len = _dbus_string_get_length (buffer);
1713 if (!_dbus_auth_decode_data (transport->auth,
1714 &socket_transport->encoded_incoming,
1717 _dbus_verbose ("Out of memory decoding incoming data\n");
1718 _dbus_message_loader_return_buffer (transport->loader,
1720 _dbus_string_get_length (buffer) - orig_len);
1725 _dbus_message_loader_return_buffer (transport->loader,
1727 _dbus_string_get_length (buffer) - orig_len);
1728 _dbus_string_set_length (&socket_transport->encoded_incoming, 0);
1729 _dbus_string_compact (&socket_transport->encoded_incoming, 2048);
1736 if (!_dbus_message_loader_get_unix_fds(transport->loader, &fds, &n_fds))
1738 _dbus_verbose ("Out of memory reading file descriptors\n");
1739 _dbus_message_loader_return_buffer (transport->loader, buffer, 0);
1743 _dbus_message_loader_get_buffer (transport->loader, &buffer);
1745 bytes_read = kdbus_read_message(socket_transport, buffer, fds, &n_fds);
1747 if (bytes_read >= 0 && n_fds > 0)
1748 _dbus_verbose("Read %i unix fds\n", n_fds);
1750 _dbus_message_loader_return_unix_fds(transport->loader, fds, bytes_read < 0 ? 0 : n_fds);
1751 _dbus_message_loader_return_buffer (transport->loader,
1753 bytes_read < 0 ? 0 : bytes_read);
1758 /* EINTR already handled for us */
1760 if (_dbus_get_is_errno_enomem ())
1762 _dbus_verbose ("Out of memory in read()/do_reading()\n");
1766 else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1770 _dbus_verbose ("Error reading from remote app: %s\n",
1771 _dbus_strerror_from_errno ());
1772 do_io_error (transport);
1776 else if (bytes_read == 0)
1778 _dbus_verbose ("Disconnected from remote app\n");
1779 do_io_error (transport);
1784 _dbus_verbose (" read %d bytes\n", bytes_read);
1786 // total += bytes_read;
1788 if (!_dbus_transport_queue_messages (transport))
1791 _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
1795 /* Try reading more data until we get EAGAIN and return, or
1796 * exceed max bytes per iteration. If in blocking mode of
1797 * course we'll block instead of returning.
1810 unix_error_with_read_to_come (DBusTransport *itransport,
1814 DBusTransportSocket *transport = (DBusTransportSocket *) itransport;
1816 if (!(flags & DBUS_WATCH_HANGUP || flags & DBUS_WATCH_ERROR))
1819 /* If we have a read watch enabled ...
1820 we -might have data incoming ... => handle the HANGUP there */
1821 if (watch != transport->read_watch &&
1822 _dbus_watch_get_enabled (transport->read_watch))
1829 socket_handle_watch (DBusTransport *transport,
1833 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1835 _dbus_assert (watch == socket_transport->read_watch ||
1836 watch == socket_transport->write_watch);
1837 _dbus_assert (watch != NULL);
1839 /* If we hit an error here on a write watch, don't disconnect the transport yet because data can
1840 * still be in the buffer and do_reading may need several iteration to read
1841 * it all (because of its max_bytes_read_per_iteration limit).
1843 if (!(flags & DBUS_WATCH_READABLE) && unix_error_with_read_to_come (transport, watch, flags))
1845 _dbus_verbose ("Hang up or error on watch\n");
1846 _dbus_transport_disconnect (transport);
1850 if (watch == socket_transport->read_watch &&
1851 (flags & DBUS_WATCH_READABLE))
1853 #ifdef DBUS_AUTHENTICATION
1854 dbus_bool_t auth_finished;
1857 _dbus_verbose ("handling read watch %p flags = %x\n",
1860 #ifdef DBUS_AUTHENTICATION
1861 if (!do_authentication (transport, TRUE, FALSE, &auth_finished))
1864 /* We don't want to do a read immediately following
1865 * a successful authentication. This is so we
1866 * have a chance to propagate the authentication
1867 * state further up. Specifically, we need to
1868 * process any pending data from the auth object.
1873 if (!do_reading (transport))
1875 _dbus_verbose ("no memory to read\n");
1878 #ifdef DBUS_AUTHENTICATION
1882 _dbus_verbose ("Not reading anything since we just completed the authentication\n");
1886 else if (watch == socket_transport->write_watch &&
1887 (flags & DBUS_WATCH_WRITABLE))
1890 _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n",
1891 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1893 #ifdef DBUS_AUTHENTICATION
1894 if (!do_authentication (transport, FALSE, TRUE, NULL))
1897 if (!do_writing (transport))
1899 _dbus_verbose ("no memory to write\n");
1903 /* See if we still need the write watch */
1904 check_write_watch (transport);
1906 #ifdef DBUS_ENABLE_VERBOSE_MODE
1909 if (watch == socket_transport->read_watch)
1910 _dbus_verbose ("asked to handle read watch with non-read condition 0x%x\n",
1912 else if (watch == socket_transport->write_watch)
1913 _dbus_verbose ("asked to handle write watch with non-write condition 0x%x\n",
1916 _dbus_verbose ("asked to handle watch %p on fd %d that we don't recognize\n",
1917 watch, dbus_watch_get_socket (watch));
1919 #endif /* DBUS_ENABLE_VERBOSE_MODE */
1925 socket_disconnect (DBusTransport *transport)
1927 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1929 _dbus_verbose ("\n");
1931 free_watches (transport);
1933 _dbus_close_socket (socket_transport->fd, NULL);
1934 socket_transport->fd = -1;
1938 socket_connection_set (DBusTransport *transport)
1940 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1942 _dbus_watch_set_handler (socket_transport->write_watch,
1943 _dbus_connection_handle_watch,
1944 transport->connection, NULL);
1946 _dbus_watch_set_handler (socket_transport->read_watch,
1947 _dbus_connection_handle_watch,
1948 transport->connection, NULL);
1950 if (!_dbus_connection_add_watch_unlocked (transport->connection,
1951 socket_transport->write_watch))
1954 if (!_dbus_connection_add_watch_unlocked (transport->connection,
1955 socket_transport->read_watch))
1957 _dbus_connection_remove_watch_unlocked (transport->connection,
1958 socket_transport->write_watch);
1962 check_read_watch (transport);
1963 check_write_watch (transport);
1969 * @todo We need to have a way to wake up the select sleep if
1970 * a new iteration request comes in with a flag (read/write) that
1971 * we're not currently serving. Otherwise a call that just reads
1972 * could block a write call forever (if there are no incoming
1976 kdbus_do_iteration (DBusTransport *transport,
1978 int timeout_milliseconds)
1980 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1985 _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p fd = %d\n",
1986 flags & DBUS_ITERATION_DO_READING ? "read" : "",
1987 flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
1988 timeout_milliseconds,
1989 socket_transport->read_watch,
1990 socket_transport->write_watch,
1991 socket_transport->fd);
1993 /* the passed in DO_READING/DO_WRITING flags indicate whether to
1994 * read/write messages, but regardless of those we may need to block
1995 * for reading/writing to do auth. But if we do reading for auth,
1996 * we don't want to read any messages yet if not given DO_READING.
1999 poll_fd.fd = socket_transport->fd;
2002 if (_dbus_transport_get_is_authenticated (transport))
2004 /* This is kind of a hack; if we have stuff to write, then try
2005 * to avoid the poll. This is probably about a 5% speedup on an
2006 * echo client/server.
2008 * If both reading and writing were requested, we want to avoid this
2009 * since it could have funky effects:
2010 * - both ends spinning waiting for the other one to read
2011 * data so they can finish writing
2012 * - prioritizing all writing ahead of reading
2014 if ((flags & DBUS_ITERATION_DO_WRITING) &&
2015 !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) &&
2016 !transport->disconnected &&
2017 _dbus_connection_has_messages_to_send_unlocked (transport->connection))
2019 do_writing (transport);
2021 if (transport->disconnected ||
2022 !_dbus_connection_has_messages_to_send_unlocked (transport->connection))
2026 /* If we get here, we decided to do the poll() after all */
2027 _dbus_assert (socket_transport->read_watch);
2028 if (flags & DBUS_ITERATION_DO_READING)
2029 poll_fd.events |= _DBUS_POLLIN;
2031 _dbus_assert (socket_transport->write_watch);
2032 if (flags & DBUS_ITERATION_DO_WRITING)
2033 poll_fd.events |= _DBUS_POLLOUT;
2037 DBusAuthState auth_state;
2039 auth_state = _dbus_auth_do_work (transport->auth);
2041 if (transport->receive_credentials_pending ||
2042 auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT)
2043 poll_fd.events |= _DBUS_POLLIN;
2045 if (transport->send_credentials_pending ||
2046 auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND)
2047 poll_fd.events |= _DBUS_POLLOUT;
2052 if (flags & DBUS_ITERATION_BLOCK)
2053 poll_timeout = timeout_milliseconds;
2057 /* For blocking selects we drop the connection lock here
2058 * to avoid blocking out connection access during a potentially
2059 * indefinite blocking call. The io path is still protected
2060 * by the io_path_cond condvar, so we won't reenter this.
2062 if (flags & DBUS_ITERATION_BLOCK)
2064 _dbus_verbose ("unlock pre poll\n");
2065 _dbus_connection_unlock (transport->connection);
2069 poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
2071 if (poll_res < 0 && _dbus_get_is_errno_eintr ())
2073 _dbus_verbose ("Error from _dbus_poll(): %s\n",
2074 _dbus_strerror_from_errno ());
2078 if (flags & DBUS_ITERATION_BLOCK)
2080 _dbus_verbose ("lock post poll\n");
2081 _dbus_connection_lock (transport->connection);
2087 poll_fd.revents = 0; /* some concern that posix does not guarantee this;
2088 * valgrind flags it as an error. though it probably
2089 * is guaranteed on linux at least.
2092 if (poll_fd.revents & _DBUS_POLLERR)
2093 do_io_error (transport);
2096 dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
2097 dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0;
2098 #ifdef DBUS_AUTHENTICATION
2099 dbus_bool_t authentication_completed;
2102 _dbus_verbose ("in iteration, need_read=%d need_write=%d\n",
2103 need_read, need_write);
2104 #ifdef DBUS_AUTHENTICATION
2105 do_authentication (transport, need_read, need_write,
2106 &authentication_completed);
2108 /* See comment in socket_handle_watch. */
2109 if (authentication_completed)
2112 if (need_read && (flags & DBUS_ITERATION_DO_READING))
2113 do_reading (transport);
2114 if (need_write && (flags & DBUS_ITERATION_DO_WRITING))
2115 do_writing (transport);
2120 _dbus_verbose ("Error from _dbus_poll(): %s\n",
2121 _dbus_strerror_from_errno ());
2127 /* We need to install the write watch only if we did not
2128 * successfully write everything. Note we need to be careful that we
2129 * don't call check_write_watch *before* do_writing, since it's
2130 * inefficient to add the write watch, and we can avoid it most of
2131 * the time since we can write immediately.
2133 * However, we MUST always call check_write_watch(); DBusConnection code
2134 * relies on the fact that running an iteration will notice that
2135 * messages are pending.
2137 check_write_watch (transport);
2139 _dbus_verbose (" ... leaving do_iteration()\n");
2143 socket_live_messages_changed (DBusTransport *transport)
2145 /* See if we should look for incoming messages again */
2146 check_read_watch (transport);
2149 static const DBusTransportVTable kdbus_vtable = {
2151 socket_handle_watch,
2153 socket_connection_set,
2155 socket_live_messages_changed,
2156 socket_get_socket_fd
2160 * Creates a new transport for the given kdbus file descriptor. The file
2161 * descriptor must be nonblocking (use _dbus_set_fd_nonblocking() to
2164 * @param fd the file descriptor.
2165 * @param server_guid non-#NULL if this transport is on the server side of a connection
2166 * @param address the transport's address
2167 * @returns the new transport, or #NULL if no memory.
2169 static DBusTransport*
2170 _dbus_transport_new_for_socket_kdbus (int fd,
2171 const DBusString *server_guid,
2172 const DBusString *address)
2174 DBusTransportSocket *socket_transport;
2176 socket_transport = dbus_new0 (DBusTransportSocket, 1);
2177 if (socket_transport == NULL)
2180 if (!_dbus_string_init (&socket_transport->encoded_outgoing))
2183 if (!_dbus_string_init (&socket_transport->encoded_incoming))
2186 socket_transport->write_watch = _dbus_watch_new (fd,
2187 DBUS_WATCH_WRITABLE,
2190 if (socket_transport->write_watch == NULL)
2193 socket_transport->read_watch = _dbus_watch_new (fd,
2194 DBUS_WATCH_READABLE,
2197 if (socket_transport->read_watch == NULL)
2200 if (!_dbus_transport_init_base (&socket_transport->base,
2202 server_guid, address))
2205 #ifdef HAVE_UNIX_FD_PASSING
2206 _dbus_auth_set_unix_fd_possible(socket_transport->base.auth, _dbus_socket_can_pass_unix_fd(fd));
2209 socket_transport->fd = fd;
2210 socket_transport->message_bytes_written = 0;
2212 /* These values should probably be tunable or something. */
2213 socket_transport->max_bytes_read_per_iteration = RECEIVE_POOL_SIZE;
2214 socket_transport->max_bytes_written_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2216 socket_transport->kdbus_mmap_ptr = NULL;
2217 socket_transport->memfd = -1;
2219 return (DBusTransport*) socket_transport;
2222 _dbus_watch_invalidate (socket_transport->read_watch);
2223 _dbus_watch_unref (socket_transport->read_watch);
2225 _dbus_watch_invalidate (socket_transport->write_watch);
2226 _dbus_watch_unref (socket_transport->write_watch);
2228 _dbus_string_free (&socket_transport->encoded_incoming);
2230 _dbus_string_free (&socket_transport->encoded_outgoing);
2232 dbus_free (socket_transport);
2238 * Creates a connection to the kdbus bus
2240 * This will set FD_CLOEXEC for the socket returned.
2242 * @param path the path to UNIX domain socket
2243 * @param error return location for error code
2244 * @returns connection file descriptor or -1 on error
2246 static int _dbus_connect_kdbus (const char *path, DBusError *error)
2250 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2251 _dbus_verbose ("connecting to kdbus bus %s\n", path);
2253 fd = open(path, O_RDWR|O_CLOEXEC|O_NONBLOCK);
2255 dbus_set_error(error, _dbus_error_from_errno (errno), "Failed to open file descriptor: %s", _dbus_strerror (errno));
2260 static dbus_bool_t kdbus_mmap(DBusTransport* transport)
2262 DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
2264 socket_transport->kdbus_mmap_ptr = mmap(NULL, RECEIVE_POOL_SIZE, PROT_READ, MAP_SHARED, socket_transport->fd, 0);
2265 if (socket_transport->kdbus_mmap_ptr == MAP_FAILED)
2272 * Creates a new transport for kdbus.
2273 * This creates a client-side of a transport.
2275 * @param path the path to the domain socket.
2276 * @param error address where an error can be returned.
2277 * @returns a new transport, or #NULL on failure.
2279 static DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error)
2282 DBusTransport *transport;
2285 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2287 if (!_dbus_string_init (&address))
2289 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2295 if ((!_dbus_string_append (&address, "kdbus:path=")) || (!_dbus_string_append (&address, path)))
2297 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2301 fd = _dbus_connect_kdbus (path, error);
2304 _DBUS_ASSERT_ERROR_IS_SET (error);
2308 _dbus_verbose ("Successfully connected to kdbus bus %s\n", path);
2310 transport = _dbus_transport_new_for_socket_kdbus (fd, NULL, &address);
2311 if (transport == NULL)
2313 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2317 _dbus_string_free (&address);
2322 _dbus_close_socket (fd, NULL);
2324 _dbus_string_free (&address);
2330 * Opens kdbus transport.
2332 * @param entry the address entry to try opening
2333 * @param transport_p return location for the opened transport
2334 * @param error error to be set
2335 * @returns result of the attempt
2337 DBusTransportOpenResult _dbus_transport_open_kdbus(DBusAddressEntry *entry,
2338 DBusTransport **transport_p,
2343 method = dbus_address_entry_get_method (entry);
2344 _dbus_assert (method != NULL);
2346 if (strcmp (method, "kdbus") == 0)
2348 const char *path = dbus_address_entry_get_value (entry, "path");
2352 _dbus_set_bad_address (error, "kdbus", "path", NULL);
2353 return DBUS_TRANSPORT_OPEN_BAD_ADDRESS;
2356 *transport_p = _dbus_transport_new_for_kdbus (path, error);
2358 if (*transport_p == NULL)
2360 _DBUS_ASSERT_ERROR_IS_SET (error);
2361 return DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT;
2365 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2366 return DBUS_TRANSPORT_OPEN_OK;
2371 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2372 return DBUS_TRANSPORT_OPEN_NOT_HANDLED;
2376 static struct kdbus_policy *make_policy_name(const char *name)
2378 struct kdbus_policy *p;
2381 size = offsetof(struct kdbus_policy, name) + strlen(name) + 1;
2387 p->type = KDBUS_POLICY_NAME;
2388 strcpy(p->name, name);
2393 static struct kdbus_policy *make_policy_access(__u64 type, __u64 bits, __u64 id)
2395 struct kdbus_policy *p;
2396 __u64 size = sizeof(*p);
2404 p->type = KDBUS_POLICY_ACCESS;
2405 p->access.type = type;
2406 p->access.bits = bits;
2412 static void append_policy(struct kdbus_cmd_policy *cmd_policy, struct kdbus_policy *policy, __u64 max_size)
2414 struct kdbus_policy *dst = (struct kdbus_policy *) ((char *) cmd_policy + cmd_policy->size);
2416 if (cmd_policy->size + policy->size > max_size)
2419 memcpy(dst, policy, policy->size);
2420 cmd_policy->size += KDBUS_ALIGN8(policy->size);
2424 dbus_bool_t bus_register_policy_kdbus(const char* name, DBusConnection *connection, DBusError *error)
2426 struct kdbus_cmd_policy *cmd_policy;
2427 struct kdbus_policy *policy;
2431 if(!dbus_connection_get_socket(connection, &fd))
2433 dbus_set_error (error, "Failed to get fd for registering policy", NULL);
2437 cmd_policy = (struct kdbus_cmd_policy *) alloca(size);
2438 memset(cmd_policy, 0, size);
2440 policy = (struct kdbus_policy *) cmd_policy->policies;
2441 cmd_policy->size = offsetof(struct kdbus_cmd_policy, policies);
2443 policy = make_policy_name(name);
2444 append_policy(cmd_policy, policy, size);
2446 policy = make_policy_access(KDBUS_POLICY_ACCESS_USER, KDBUS_POLICY_OWN, getuid());
2447 append_policy(cmd_policy, policy, size);
2449 policy = make_policy_access(KDBUS_POLICY_ACCESS_WORLD, KDBUS_POLICY_RECV, 0);
2450 append_policy(cmd_policy, policy, size);
2452 policy = make_policy_access(KDBUS_POLICY_ACCESS_WORLD, KDBUS_POLICY_SEND, 0);
2453 append_policy(cmd_policy, policy, size);
2455 if (ioctl(fd, KDBUS_CMD_EP_POLICY_SET, cmd_policy) < 0)
2457 dbus_set_error(error,_dbus_error_from_errno (errno), "Error setting EP policy: %s", _dbus_strerror (errno));
2461 _dbus_verbose("Policy %s set correctly\n", name);
2465 dbus_bool_t bus_register_kdbus(char* name, DBusConnection *connection, DBusError *error)
2467 struct kdbus_cmd_hello __attribute__ ((__aligned__(8))) hello;
2470 memset(&hello, 0, sizeof(hello));
2471 hello.conn_flags = KDBUS_HELLO_ACCEPT_FD |
2472 KDBUS_HELLO_ATTACH_COMM |
2473 KDBUS_HELLO_ATTACH_EXE |
2474 KDBUS_HELLO_ATTACH_CMDLINE |
2475 KDBUS_HELLO_ATTACH_CAPS |
2476 KDBUS_HELLO_ATTACH_CGROUP |
2477 KDBUS_HELLO_ATTACH_SECLABEL |
2478 KDBUS_HELLO_ATTACH_AUDIT;
2479 hello.size = sizeof(struct kdbus_cmd_hello);
2480 hello.pool_size = RECEIVE_POOL_SIZE;
2482 if(!dbus_connection_get_socket(connection, &fd))
2484 dbus_set_error (error, "failed to get fd for bus registration", NULL);
2487 if (ioctl(fd, KDBUS_CMD_HELLO, &hello))
2489 dbus_set_error(error,_dbus_error_from_errno (errno), "Failed to send hello: %s", _dbus_strerror (errno));
2493 _dbus_verbose("-- Our peer ID is: %llu\n", (unsigned long long)hello.id);
2494 sprintf(name, "%llu", (unsigned long long)hello.id);
2496 if(!kdbus_mmap(dbus_connection_get_transport(connection)))
2498 dbus_set_error(error,_dbus_error_from_errno (errno), "Error when mmap: %s", _dbus_strerror (errno));
2505 int bus_request_name_kdbus(DBusConnection *connection, const char *name, const uint64_t flags, DBusError *error)
2507 struct kdbus_cmd_name *cmd_name;
2509 uint64_t size = sizeof(*cmd_name) + strlen(name) + 1;
2510 uint64_t flags_kdbus = 0;
2512 cmd_name = alloca(size);
2514 memset(cmd_name, 0, size);
2515 strcpy(cmd_name->name, name);
2516 cmd_name->size = size;
2518 if(flags & DBUS_NAME_FLAG_ALLOW_REPLACEMENT)
2519 flags_kdbus |= KDBUS_NAME_ALLOW_REPLACEMENT;
2520 if(!(flags & DBUS_NAME_FLAG_DO_NOT_QUEUE))
2521 flags_kdbus |= KDBUS_NAME_QUEUE;
2522 if(flags & DBUS_NAME_FLAG_REPLACE_EXISTING)
2523 flags_kdbus |= KDBUS_NAME_REPLACE_EXISTING;
2525 cmd_name->conn_flags = flags_kdbus;
2527 if(!dbus_connection_get_socket(connection, &fd))
2529 dbus_set_error (error, "failed to get fd for name request", NULL);
2533 _dbus_verbose("Request name - flags sent: 0x%llx !!!!!!!!!\n", cmd_name->conn_flags);
2535 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2536 if (ioctl(fd, KDBUS_CMD_NAME_ACQUIRE, cmd_name))
2538 dbus_set_error(error,_dbus_error_from_errno (errno), "error acquiring name: %s", _dbus_strerror (errno));
2540 return DBUS_REQUEST_NAME_REPLY_EXISTS;
2544 _dbus_verbose("Request name - received flag: 0x%llx !!!!!!!!!\n", cmd_name->conn_flags);
2546 if(cmd_name->conn_flags & KDBUS_NAME_IN_QUEUE)
2547 return DBUS_REQUEST_NAME_REPLY_IN_QUEUE;
2549 return DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER;
2550 //todo now 1 code is never returned - DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER
2554 * Checks if the connection's transport is kdbus on the basis of its address
2556 * @param pointer to the connection
2557 * @returns TRUE if kdbus transport, otherwise FALSE
2559 dbus_bool_t dbus_transport_is_kdbus(DBusConnection *connection)
2561 const char* address = _dbus_connection_get_address(connection);
2563 if(address == strstr(address, "kdbus:path="))
2569 static int parse_match_key(const char *rule, const char* key, char** pValue)
2572 const char* pValueEnd;
2573 int value_length = 0;
2575 pBegin = strstr(rule, key);
2578 pBegin += strlen(key);
2579 pValueEnd = strchr(pBegin, '\'');
2582 value_length = pValueEnd - pBegin;
2583 *pValue = strndup(pBegin, value_length);
2586 if(strcmp(*pValue, "org.freedesktop.DBus") == 0)
2588 _dbus_verbose ("founf for key: %s value:'%s'\n", key, *pValue);
2592 return value_length;
2595 /* only part of the dbus's matching capabilities implemented in kdbus now because of different mechanism
2596 * interface match key mapped to bloom
2597 * sender match key mapped to src_name
2598 * also handled org.freedesktop.dbus members: NameOwnerChanged, NameLost, NameAcquired
2600 void dbus_bus_add_match_kdbus (DBusConnection *connection, const char *rule, DBusError *error)
2602 struct kdbus_cmd_match* pCmd_match;
2603 struct kdbus_item *pItem;
2605 __u64 src_id = KDBUS_MATCH_SRC_ID_ANY;
2607 unsigned int kernel_item = 0;
2610 char* pInterface = NULL;
2612 dbus_connection_get_socket(connection, &fd);
2614 /*parsing rule and calculating size of command*/
2615 size = sizeof(struct kdbus_cmd_match);
2617 if(strstr(rule, "member='NameOwnerChanged'"))
2619 kernel_item = KDBUS_MATCH_NAME_CHANGE;
2620 size += KDBUS_ITEM_SIZE(1);
2622 else if(strstr(rule, "member='NameLost'"))
2624 kernel_item = KDBUS_MATCH_NAME_REMOVE;
2625 size += KDBUS_ITEM_SIZE(1);
2627 else if(strstr(rule, "member='NameAcquired'"))
2629 kernel_item = KDBUS_MATCH_NAME_ADD;
2630 size += KDBUS_ITEM_SIZE(1);
2633 name_size = parse_match_key(rule, "interface='", &pInterface); /*actual size is not important for interface*/
2634 if((name_size == -1) && (kernel_item == 0))
2637 size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2;
2639 else if(name_size > 0)
2640 size += KDBUS_PART_HEADER_SIZE + KDBUS_BLOOM_SIZE_BYTES;
2642 name_size = parse_match_key(rule, "sender='", &pName);
2643 if((name_size == -1) && (kernel_item == 0))
2646 size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2;
2650 if(!strncmp(pName, ":1.", 3)) /*if name is unique name it must be converted to unique id*/
2652 src_id = strtoll(&pName[3], NULL, 10);
2657 size += KDBUS_ITEM_SIZE(name_size + 1);
2660 pCmd_match = malloc(size);
2661 if(pCmd_match == NULL)
2663 memset(pCmd_match, 0, size);
2665 pCmd_match->size = size;
2666 pCmd_match->cookie = strtoll(dbus_bus_get_unique_name(connection), NULL , 10);
2668 pItem = pCmd_match->items;
2669 if(kernel_item == ~0) //all signals from kernel
2671 pCmd_match->src_id = 0;
2672 pItem->type = KDBUS_MATCH_NAME_CHANGE;
2673 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2674 pItem = KDBUS_PART_NEXT(pItem);
2675 pItem->type = KDBUS_MATCH_NAME_ADD;
2676 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2677 pItem = KDBUS_PART_NEXT(pItem);
2678 pItem->type = KDBUS_MATCH_NAME_REMOVE;
2679 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2680 pItem = KDBUS_PART_NEXT(pItem);
2681 pItem->type = KDBUS_MATCH_ID_ADD;
2682 pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64);
2683 pItem = KDBUS_PART_NEXT(pItem);
2684 pItem->type = KDBUS_MATCH_ID_REMOVE;
2685 pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64);
2687 else if(kernel_item)
2689 pCmd_match->src_id = 0;
2690 pItem->type = kernel_item;
2691 pItem->size = KDBUS_PART_HEADER_SIZE + 1;
2695 pCmd_match->src_id = src_id;
2698 pItem->type = KDBUS_MATCH_SRC_NAME;
2699 pItem->size = KDBUS_PART_HEADER_SIZE + name_size + 1;
2700 strcpy(pItem->str, pName);
2701 pItem = KDBUS_PART_NEXT(pItem);
2706 pItem->type = KDBUS_MATCH_BLOOM;
2707 pItem->size = KDBUS_PART_HEADER_SIZE + KDBUS_BLOOM_SIZE_BYTES;
2708 strncpy(pItem->data, pInterface, KDBUS_BLOOM_SIZE_BYTES);
2712 if(ioctl(fd, KDBUS_CMD_MATCH_ADD, pCmd_match))
2715 dbus_set_error(error,_dbus_error_from_errno (errno), "error adding match: %s", _dbus_strerror (errno));
2716 _dbus_verbose("Failed adding match bus rule %s,\nerror: %d, %m\n", rule, errno);
2719 _dbus_verbose("Added match bus rule %s\n", rule);
2729 void dbus_bus_remove_match_kdbus (DBusConnection *connection, const char *rule, DBusError *error)
2731 struct kdbus_cmd_match __attribute__ ((__aligned__(8))) cmd;
2734 dbus_connection_get_socket(connection, &fd);
2735 cmd.cookie = strtoll(dbus_bus_get_unique_name(connection), NULL , 10);
2736 cmd.id = cmd.cookie;
2737 cmd.size = sizeof(struct kdbus_cmd_match);
2739 if(ioctl(fd, KDBUS_CMD_MATCH_ADD, &cmd))
2742 dbus_set_error(error,_dbus_error_from_errno (errno), "error removing match: %s", _dbus_strerror (errno));
2743 _dbus_verbose("Failed removing match rule; error: %d, %m\n", errno);
2746 _dbus_verbose("Match rule removed correctly.\n");