1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-transport-kdbus.c kdbus subclasses of DBusTransport
4 * Copyright (C) 2002, 2003, 2004, 2006 Red Hat Inc
5 * Copyright (C) 2013 Samsung Electronics
7 * Licensed under the Academic Free License version 2.1
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version and under the terms of the GNU
13 * Lesser General Public License as published by the
14 * Free Software Foundation; either version 2.1 of the License, or (at
15 * your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "dbus-transport.h"
28 #include "dbus-transport-kdbus.h"
29 #include "dbus-transport-protected.h"
30 #include "dbus-connection-internal.h"
32 #include "dbus-watch.h"
33 #include "dbus-errors.h"
35 #include "kdbus-common.h"
36 #include <linux/types.h>
40 #include <sys/ioctl.h>
49 #define KDBUS_PART_FOREACH(part, head, first) \
50 for (part = (head)->first; \
51 (uint8_t *)(part) < (uint8_t *)(head) + (head)->size; \
52 part = KDBUS_PART_NEXT(part))
53 #define RECEIVE_POOL_SIZE (10 * 1024LU * 1024LU)
54 #define MEMFD_SIZE_THRESHOLD (2 * 1024 * 1024LU) // over this memfd is used
56 #define KDBUS_MSG_DECODE_DEBUG 0
57 //#define DBUS_AUTHENTICATION
59 #define ITER_APPEND_STR(string) \
60 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &string)) \
66 #define MSG_ITEM_BUILD_VEC(data, datasize) \
67 item->type = KDBUS_MSG_PAYLOAD_VEC; \
68 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec); \
69 item->vec.address = (unsigned long) data; \
70 item->vec.size = datasize;
73 * Opaque object representing a transport. In kdbus transport it has nothing common
74 * with socket, but the name was preserved to comply with upper functions.
76 typedef struct DBusTransportKdbus DBusTransportKdbus;
79 * Implementation details of DBusTransportSocket. All members are private.
81 struct DBusTransportKdbus
83 DBusTransport base; /**< Parent instance */
84 int fd; /**< File descriptor. */
85 DBusWatch *read_watch; /**< Watch for readability. */
86 DBusWatch *write_watch; /**< Watch for writability. */
88 int max_bytes_read_per_iteration; /**< In kdbus only to control overall message size*/
89 int max_bytes_written_per_iteration; /**< In kdbus only to control overall message size*/
91 int message_bytes_written; /**< Number of bytes of current
92 * outgoing message that have
95 DBusString encoded_outgoing; /**< Encoded version of current
98 DBusString encoded_incoming; /**< Encoded version of current
101 void* kdbus_mmap_ptr; /**< Mapped memory where Kdbus (kernel) writes
102 * messages incoming to us.
104 int memfd; /**< File descriptor to special
105 * memory pool for bulk data
106 * transfer. Retrieved from
107 * Kdbus kernel module.
109 __u64 bloom_size; /**< bloom filter field size */
110 char* sender; /**< uniqe name of the sender */
113 __u64 dbus_transport_get_bloom_size(DBusTransport* transport)
115 return ((DBusTransportKdbus*)transport)->bloom_size;
119 * Adds locally generated message to received messages queue
122 static dbus_bool_t add_message_to_received(DBusMessage *message, DBusConnection* connection)
124 DBusList *message_link;
126 message_link = _dbus_list_alloc_link (message);
127 if (message_link == NULL)
129 dbus_message_unref (message);
133 _dbus_connection_queue_synthesized_message_link(connection, message_link);
139 * Generates local error message as a reply to message given as parameter
140 * and adds generated error message to received messages queue.
142 static int reply_with_error(char* error_type, const char* template, const char* object, DBusMessage *message, DBusConnection* connection)
144 DBusMessage *errMessage;
145 char* error_msg = "";
149 error_msg = alloca(strlen(template) + strlen(object));
150 sprintf(error_msg, template, object);
153 error_msg = (char*)object;
155 errMessage = generate_local_error_message(dbus_message_get_serial(message), error_type, error_msg);
156 if(errMessage == NULL)
158 if (add_message_to_received(errMessage, connection))
165 * Generates reply to the message given as a parameter with one item in the reply body
166 * and adds generated reply message to received messages queue.
168 static int reply_1_data(DBusMessage *message, int data_type, void* pData, DBusConnection* connection)
170 DBusMessageIter args;
173 reply = dbus_message_new_method_return(message);
176 dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
177 dbus_message_iter_init_append(reply, &args);
178 if (!dbus_message_iter_append_basic(&args, data_type, pData))
180 dbus_message_unref(reply);
183 if(add_message_to_received(reply, connection))
190 static int reply_ack(DBusMessage *message, DBusConnection* connection)
194 reply = dbus_message_new_method_return(message);
197 if(add_message_to_received(reply, connection))
203 * Retrieves file descriptor to memory pool from kdbus module.
204 * It is then used for bulk data sending.
205 * Triggered when message payload is over MEMFD_SIZE_THRESHOLD
208 static int kdbus_init_memfd(DBusTransportKdbus* socket_transport)
212 if (ioctl(socket_transport->fd, KDBUS_CMD_MEMFD_NEW, &memfd) < 0) {
213 _dbus_verbose("KDBUS_CMD_MEMFD_NEW failed: \n");
217 socket_transport->memfd = memfd;
218 _dbus_verbose("kdbus_init_memfd: %d!!\n", socket_transport->memfd);
223 * Initiates Kdbus message structure.
224 * Calculates it's size, allocates memory and fills some fields.
225 * @param name Well-known name or NULL
226 * @param dst_id Numeric id of recipient
227 * @param body_size size of message body if present
228 * @param use_memfd flag to build memfd message
229 * @param fds_count number of file descriptors used
230 * @param transport transport
231 * @return initialized kdbus message
233 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, DBusTransportKdbus *transport)
235 struct kdbus_msg* msg;
238 msg_size = sizeof(struct kdbus_msg);
240 if(use_memfd == TRUE) // bulk data - memfd - encoded and plain
241 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_memfd));
243 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
245 msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
249 msg_size += KDBUS_ITEM_SIZE(sizeof(int)*fds_count);
252 msg_size += KDBUS_ITEM_SIZE(strlen(name) + 1);
253 else if (dst_id == KDBUS_DST_ID_BROADCAST)
254 msg_size += KDBUS_PART_HEADER_SIZE + transport->bloom_size;
256 msg = malloc(msg_size);
259 _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
263 memset(msg, 0, msg_size);
264 msg->size = msg_size;
265 msg->payload_type = KDBUS_PAYLOAD_DBUS1;
266 msg->dst_id = name ? 0 : dst_id;
267 msg->src_id = strtoull(dbus_bus_get_unique_name(transport->base.connection), NULL , 10);
273 * Builds and sends kdbus message using DBus message.
274 * Decide whether used payload vector or memfd memory pool.
275 * Handles broadcasts and unicast messages, and passing of Unix fds.
276 * Does error handling.
277 * TODO refactor to be more compact
279 * @param transport transport
280 * @param message DBus message to be sent
281 * @param encoded flag if the message is encoded
282 * @return size of data sent
284 static int kdbus_write_msg(DBusTransportKdbus *transport, DBusMessage *message, const char* destination, dbus_bool_t encoded)
286 struct kdbus_msg *msg;
287 struct kdbus_item *item;
288 uint64_t dst_id = KDBUS_DST_ID_BROADCAST;
289 const DBusString *header;
290 const DBusString *body;
291 uint64_t ret_size = 0;
292 uint64_t body_size = 0;
293 uint64_t header_size = 0;
294 dbus_bool_t use_memfd;
297 dbus_bool_t autostart;
299 // determine destination and destination id
302 dst_id = KDBUS_DST_ID_WELL_KNOWN_NAME;
303 if((destination[0] == ':') && (destination[1] == '1') && (destination[2] == '.')) /* if name starts with ":1." it is a unique name and should be send as number */
305 dst_id = strtoull(&destination[3], NULL, 10);
312 ret_size = _dbus_string_get_length (&transport->encoded_outgoing);
315 _dbus_message_get_network_data (message, &header, &body);
316 header_size = _dbus_string_get_length(header);
317 body_size = _dbus_string_get_length(body);
318 ret_size = header_size + body_size;
321 // check if message size is big enough to use memfd kdbus transport
322 use_memfd = ret_size > MEMFD_SIZE_THRESHOLD ? TRUE : FALSE;
323 if(use_memfd) kdbus_init_memfd(transport);
325 _dbus_message_get_unix_fds(message, &unix_fds, &fds_count);
327 // init basic message fields
328 msg = kdbus_init_msg(destination, dst_id, body_size, use_memfd, fds_count, transport);
329 msg->cookie = dbus_message_get_serial(message);
330 autostart = dbus_message_get_auto_start (message);
332 msg->flags |= KDBUS_MSG_FLAGS_NO_AUTO_START;
334 // build message contents
337 // case 1 - bulk data transfer - memfd - encoded and plain
342 if(ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 0) < 0)
344 _dbus_verbose("memfd sealing failed: \n");
348 buf = mmap(NULL, ret_size, PROT_WRITE, MAP_SHARED, transport->memfd, 0);
349 if (buf == MAP_FAILED)
351 _dbus_verbose("mmap() fd=%i failed:%m", transport->memfd);
356 memcpy(buf, &transport->encoded_outgoing, ret_size);
359 memcpy(buf, _dbus_string_get_const_data(header), header_size);
362 memcpy(buf, _dbus_string_get_const_data(body), body_size);
367 munmap(buf, ret_size);
369 // seal data - kdbus module needs it
370 if(ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 1) < 0) {
371 _dbus_verbose("memfd sealing failed: %d (%m)\n", errno);
376 item->type = KDBUS_MSG_PAYLOAD_MEMFD;
377 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_memfd);
378 item->memfd.size = ret_size;
379 item->memfd.fd = transport->memfd;
380 // case 2 - small encoded - don't use memfd
382 _dbus_verbose("sending encoded data\n");
383 MSG_ITEM_BUILD_VEC(&transport->encoded_outgoing, _dbus_string_get_length (&transport->encoded_outgoing));
385 // case 3 - small not encoded - don't use memfd
387 _dbus_verbose("sending normal vector data\n");
388 MSG_ITEM_BUILD_VEC(_dbus_string_get_const_data(header), header_size);
392 _dbus_verbose("body attaching\n");
393 item = KDBUS_PART_NEXT(item);
394 MSG_ITEM_BUILD_VEC(_dbus_string_get_const_data(body), body_size);
400 item = KDBUS_PART_NEXT(item);
401 item->type = KDBUS_MSG_FDS;
402 item->size = KDBUS_PART_HEADER_SIZE + (sizeof(int) * fds_count);
403 memcpy(item->fds, unix_fds, sizeof(int) * fds_count);
408 item = KDBUS_PART_NEXT(item);
409 item->type = KDBUS_MSG_DST_NAME;
410 item->size = KDBUS_PART_HEADER_SIZE + strlen(destination) + 1;
411 memcpy(item->str, destination, item->size - KDBUS_PART_HEADER_SIZE);
413 else if (dst_id == KDBUS_DST_ID_BROADCAST)
415 item = KDBUS_PART_NEXT(item);
416 item->type = KDBUS_MSG_BLOOM;
417 item->size = KDBUS_PART_HEADER_SIZE + transport->bloom_size;
418 strncpy(item->data, dbus_message_get_interface(message), transport->bloom_size);
422 if (ioctl(transport->fd, KDBUS_CMD_MSG_SEND, msg))
426 else if(errno == ENXIO) //no such id on the bus
428 if(!reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Name \"%s\" does not exist", dbus_message_get_destination(message), message, transport->base.connection))
431 else if((errno == ESRCH) || (errno = EADDRNOTAVAIL)) //when well known name is not available on the bus
435 if(!reply_with_error(DBUS_ERROR_SERVICE_UNKNOWN, "The name %s was not provided by any .service files", dbus_message_get_destination(message), message, transport->base.connection))
439 if(!reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Name \"%s\" does not exist", dbus_message_get_destination(message), message, transport->base.connection))
442 _dbus_verbose("kdbus error sending message: err %d (%m)\n", errno);
448 close(transport->memfd);
454 * Performs kdbus hello - registration on the kdbus bus
456 * @param name place to store unique name given by bus
457 * @param transportS transport structure
458 * @returns #TRUE on success
460 static dbus_bool_t bus_register_kdbus(char* name, DBusTransportKdbus* transportS)
462 struct kdbus_cmd_hello __attribute__ ((__aligned__(8))) hello;
464 hello.conn_flags = KDBUS_HELLO_ACCEPT_FD/* |
465 KDBUS_HELLO_ATTACH_COMM |
466 KDBUS_HELLO_ATTACH_EXE |
467 KDBUS_HELLO_ATTACH_CMDLINE |
468 KDBUS_HELLO_ATTACH_CAPS |
469 KDBUS_HELLO_ATTACH_CGROUP |
470 KDBUS_HELLO_ATTACH_SECLABEL |
471 KDBUS_HELLO_ATTACH_AUDIT*/;
472 hello.size = sizeof(struct kdbus_cmd_hello);
473 hello.pool_size = RECEIVE_POOL_SIZE;
475 if (ioctl(transportS->fd, KDBUS_CMD_HELLO, &hello))
477 _dbus_verbose ("Failed to send hello: %m, %d",errno);
481 sprintf(name, "%llu", (unsigned long long)hello.id);
482 _dbus_verbose("-- Our peer ID is: %s\n", name);
483 transportS->bloom_size = hello.bloom_size;
485 transportS->kdbus_mmap_ptr = mmap(NULL, RECEIVE_POOL_SIZE, PROT_READ, MAP_SHARED, transportS->fd, 0);
486 if (transportS->kdbus_mmap_ptr == MAP_FAILED)
488 _dbus_verbose("Error when mmap: %m, %d",errno);
496 * Handles messages sent to bus daemon - "org.freedesktop.DBus" and translates them to appropriate
497 * kdbus ioctl commands. Than translate kdbus reply into dbus message and put it into recived messages queue.
499 * Now it captures only Hello message, which must be handled locally.
500 * All the rest is passed to dbus-daemon.
502 static int emulateOrgFreedesktopDBus(DBusTransport *transport, DBusMessage *message)
504 if(!strcmp(dbus_message_get_member(message), "Hello"))
508 name = malloc(snprintf(name, 0, "%llu", ULLONG_MAX) + sizeof(":1."));
512 if(!bus_register_kdbus(&name[3], (DBusTransportKdbus*)transport))
514 if(!register_kdbus_policy(&name[3], transport, geteuid()))
517 ((DBusTransportKdbus*)transport)->sender = name;
519 if(!reply_1_data(message, DBUS_TYPE_STRING, &name, transport->connection))
526 return 1; //send to daemon
531 #if KDBUS_MSG_DECODE_DEBUG == 1
532 static char *msg_id(uint64_t id, char *buf)
538 sprintf(buf, "%llu", (unsigned long long)id);
542 struct kdbus_enum_table {
546 #define _STRINGIFY(x) #x
547 #define STRINGIFY(x) _STRINGIFY(x)
548 #define ELEMENTSOF(x) (sizeof(x)/sizeof((x)[0]))
549 #define TABLE(what) static struct kdbus_enum_table kdbus_table_##what[]
550 #define ENUM(_id) { .id=_id, .name=STRINGIFY(_id) }
551 #define LOOKUP(what) \
552 const char *enum_##what(long long id) { \
554 for (i = 0; i < ELEMENTSOF(kdbus_table_##what); i++) \
555 if (id == kdbus_table_##what[i].id) \
556 return kdbus_table_##what[i].name; \
559 const char *enum_MSG(long long id);
561 ENUM(_KDBUS_MSG_NULL),
562 ENUM(KDBUS_MSG_PAYLOAD_VEC),
563 ENUM(KDBUS_MSG_PAYLOAD_OFF),
564 ENUM(KDBUS_MSG_PAYLOAD_MEMFD),
566 ENUM(KDBUS_MSG_BLOOM),
567 ENUM(KDBUS_MSG_DST_NAME),
568 ENUM(KDBUS_MSG_SRC_CREDS),
569 ENUM(KDBUS_MSG_SRC_PID_COMM),
570 ENUM(KDBUS_MSG_SRC_TID_COMM),
571 ENUM(KDBUS_MSG_SRC_EXE),
572 ENUM(KDBUS_MSG_SRC_CMDLINE),
573 ENUM(KDBUS_MSG_SRC_CGROUP),
574 ENUM(KDBUS_MSG_SRC_CAPS),
575 ENUM(KDBUS_MSG_SRC_SECLABEL),
576 ENUM(KDBUS_MSG_SRC_AUDIT),
577 ENUM(KDBUS_MSG_SRC_NAMES),
578 ENUM(KDBUS_MSG_TIMESTAMP),
579 ENUM(KDBUS_MSG_NAME_ADD),
580 ENUM(KDBUS_MSG_NAME_REMOVE),
581 ENUM(KDBUS_MSG_NAME_CHANGE),
582 ENUM(KDBUS_MSG_ID_ADD),
583 ENUM(KDBUS_MSG_ID_REMOVE),
584 ENUM(KDBUS_MSG_REPLY_TIMEOUT),
585 ENUM(KDBUS_MSG_REPLY_DEAD),
588 const char *enum_PAYLOAD(long long id);
590 ENUM(KDBUS_PAYLOAD_KERNEL),
591 ENUM(KDBUS_PAYLOAD_DBUS1),
592 ENUM(KDBUS_PAYLOAD_GVARIANT),
597 * Puts locally generated message into received data buffer.
598 * Use only during receiving phase!
600 * @param message message to load
601 * @param data place to load message
602 * @return size of message
604 static int put_message_into_data(DBusMessage *message, char* data)
607 const DBusString *header;
608 const DBusString *body;
611 dbus_message_set_serial(message, 1);
612 dbus_message_lock (message);
613 _dbus_message_get_network_data (message, &header, &body);
614 ret_size = _dbus_string_get_length(header);
615 memcpy(data, _dbus_string_get_const_data(header), ret_size);
617 size = _dbus_string_get_length(body);
618 memcpy(data, _dbus_string_get_const_data(body), size);
625 * Get the length of the kdbus message content.
627 * @param msg kdbus message
628 * @return the length of the kdbus message
630 static int kdbus_message_size(const struct kdbus_msg* msg)
632 const struct kdbus_item *item;
635 KDBUS_PART_FOREACH(item, msg, items)
637 if (item->size <= KDBUS_PART_HEADER_SIZE)
639 _dbus_verbose(" +%s (%llu bytes) invalid data record\n", enum_MSG(item->type), item->size);
644 case KDBUS_MSG_PAYLOAD_OFF:
645 ret_size += item->vec.size;
647 case KDBUS_MSG_PAYLOAD_MEMFD:
648 ret_size += item->memfd.size;
659 * Decodes kdbus message in order to extract dbus message and put it into data and fds.
660 * Also captures and decodes kdbus error messages and kdbus kernel broadcasts and converts
661 * all of them into dbus messages.
663 * @param msg kdbus message
664 * @param data place to copy dbus message to
665 * @param kdbus_transport transport
666 * @param fds place to store file descriptors received
667 * @param n_fds place to store quantity of file descriptor
668 * @return number of dbus message's bytes received or -1 on error
670 static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTransportKdbus* kdbus_transport, int* fds, int* n_fds)
672 const struct kdbus_item *item;
674 DBusMessage *message = NULL;
675 DBusMessageIter args;
676 const char* emptyString = "";
677 const char* pString = NULL;
678 char dbus_name[(unsigned int)(snprintf((char*)pString, 0, "%llu", ULLONG_MAX) + sizeof(":1."))];
679 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);
694 KDBUS_PART_FOREACH(item, msg, items)
696 if (item->size <= KDBUS_PART_HEADER_SIZE)
698 _dbus_verbose(" +%s (%llu bytes) invalid data record\n", enum_MSG(item->type), item->size);
699 break; //??? continue (because dbus will find error) or break
704 case KDBUS_MSG_PAYLOAD_OFF:
705 memcpy(data, (char *)kdbus_transport->kdbus_mmap_ptr + item->vec.offset, item->vec.size);
706 data += item->vec.size;
707 ret_size += item->vec.size;
709 _dbus_verbose(" +%s (%llu bytes) off=%llu size=%llu\n",
710 enum_MSG(item->type), item->size,
711 (unsigned long long)item->vec.offset,
712 (unsigned long long)item->vec.size);
715 case KDBUS_MSG_PAYLOAD_MEMFD:
720 size = item->memfd.size;
721 _dbus_verbose("memfd.size : %llu\n", (unsigned long long)size);
723 buf = mmap(NULL, size, PROT_READ , MAP_SHARED, item->memfd.fd, 0);
724 if (buf == MAP_FAILED)
726 _dbus_verbose("mmap() fd=%i failed:%m", item->memfd.fd);
730 memcpy(data, buf, size);
736 _dbus_verbose(" +%s (%llu bytes) off=%llu size=%llu\n",
737 enum_MSG(item->type), item->size,
738 (unsigned long long)item->vec.offset,
739 (unsigned long long)item->vec.size);
747 *n_fds = (item->size - KDBUS_PART_HEADER_SIZE) / sizeof(int);
748 memcpy(fds, item->fds, *n_fds * sizeof(int));
749 for (i = 0; i < *n_fds; i++)
750 _dbus_fd_set_close_on_exec(fds[i]);
754 #if KDBUS_MSG_DECODE_DEBUG == 1
755 case KDBUS_MSG_SRC_CREDS:
756 _dbus_verbose(" +%s (%llu bytes) uid=%lld, gid=%lld, pid=%lld, tid=%lld, starttime=%lld\n",
757 enum_MSG(item->type), item->size,
758 item->creds.uid, item->creds.gid,
759 item->creds.pid, item->creds.tid,
760 item->creds.starttime);
763 case KDBUS_MSG_SRC_PID_COMM:
764 case KDBUS_MSG_SRC_TID_COMM:
765 case KDBUS_MSG_SRC_EXE:
766 case KDBUS_MSG_SRC_CGROUP:
767 case KDBUS_MSG_SRC_SECLABEL:
768 case KDBUS_MSG_DST_NAME:
769 _dbus_verbose(" +%s (%llu bytes) '%s' (%zu)\n",
770 enum_MSG(item->type), item->size, item->str, strlen(item->str));
773 case KDBUS_MSG_SRC_CMDLINE:
774 case KDBUS_MSG_SRC_NAMES: {
775 __u64 size = item->size - KDBUS_PART_HEADER_SIZE;
776 const char *str = item->str;
779 _dbus_verbose(" +%s (%llu bytes) ", enum_MSG(item->type), item->size);
781 _dbus_verbose("'%s' ", str);
782 size -= strlen(str) + 1;
783 str += strlen(str) + 1;
787 _dbus_verbose("(%d string%s)\n", count, (count == 1) ? "" : "s");
791 case KDBUS_MSG_SRC_AUDIT:
792 _dbus_verbose(" +%s (%llu bytes) loginuid=%llu sessionid=%llu\n",
793 enum_MSG(item->type), item->size,
794 (unsigned long long)item->data64[0],
795 (unsigned long long)item->data64[1]);
798 case KDBUS_MSG_SRC_CAPS: {
803 _dbus_verbose(" +%s (%llu bytes) len=%llu bytes)\n",
804 enum_MSG(item->type), item->size,
805 (unsigned long long)item->size - KDBUS_PART_HEADER_SIZE);
808 n = (item->size - KDBUS_PART_HEADER_SIZE) / 4 / sizeof(uint32_t);
810 _dbus_verbose(" CapInh=");
811 for (i = 0; i < n; i++)
812 _dbus_verbose("%08x", cap[(0 * n) + (n - i - 1)]);
814 _dbus_verbose(" CapPrm=");
815 for (i = 0; i < n; i++)
816 _dbus_verbose("%08x", cap[(1 * n) + (n - i - 1)]);
818 _dbus_verbose(" CapEff=");
819 for (i = 0; i < n; i++)
820 _dbus_verbose("%08x", cap[(2 * n) + (n - i - 1)]);
822 _dbus_verbose(" CapInh=");
823 for (i = 0; i < n; i++)
824 _dbus_verbose("%08x", cap[(3 * n) + (n - i - 1)]);
829 case KDBUS_MSG_TIMESTAMP:
830 _dbus_verbose(" +%s (%llu bytes) realtime=%lluns monotonic=%lluns\n",
831 enum_MSG(item->type), item->size,
832 (unsigned long long)item->timestamp.realtime_ns,
833 (unsigned long long)item->timestamp.monotonic_ns);
837 case KDBUS_MSG_REPLY_TIMEOUT:
838 _dbus_verbose(" +%s (%llu bytes) cookie=%llu\n",
839 enum_MSG(item->type), item->size, msg->cookie_reply);
841 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NO_REPLY, NULL);
848 ret_size = put_message_into_data(message, data);
851 case KDBUS_MSG_REPLY_DEAD:
852 _dbus_verbose(" +%s (%llu bytes) cookie=%llu\n",
853 enum_MSG(item->type), item->size, msg->cookie_reply);
855 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NAME_HAS_NO_OWNER, NULL);
862 ret_size = put_message_into_data(message, data);
865 case KDBUS_MSG_NAME_ADD:
866 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
867 enum_MSG(item->type), (unsigned long long) item->size,
868 item->name_change.name, item->name_change.old_id,
869 item->name_change.new_id, item->name_change.flags);
871 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
878 sprintf(dbus_name,":1.%llu",item->name_change.new_id);
879 pString = item->name_change.name;
880 _dbus_verbose ("Name added: %s\n", pString);
881 dbus_message_iter_init_append(message, &args);
882 ITER_APPEND_STR(pString)
883 ITER_APPEND_STR(emptyString)
884 ITER_APPEND_STR(pDBusName)
885 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
887 ret_size = put_message_into_data(message, data);
890 case KDBUS_MSG_NAME_REMOVE:
891 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
892 enum_MSG(item->type), (unsigned long long) item->size,
893 item->name_change.name, item->name_change.old_id,
894 item->name_change.new_id, item->name_change.flags);
896 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged"); // name of the signal
903 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
904 pString = item->name_change.name;
905 _dbus_verbose ("Name removed: %s\n", pString);
906 dbus_message_iter_init_append(message, &args);
907 ITER_APPEND_STR(pString)
908 ITER_APPEND_STR(pDBusName)
909 ITER_APPEND_STR(emptyString)
910 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
912 ret_size = put_message_into_data(message, data);
915 case KDBUS_MSG_NAME_CHANGE:
916 _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
917 enum_MSG(item->type), (unsigned long long) item->size,
918 item->name_change.name, item->name_change.old_id,
919 item->name_change.new_id, item->name_change.flags);
921 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
928 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
929 pString = item->name_change.name;
930 _dbus_verbose ("Name changed: %s\n", pString);
931 dbus_message_iter_init_append(message, &args);
932 ITER_APPEND_STR(pString)
933 ITER_APPEND_STR(pDBusName)
934 sprintf(&dbus_name[3],"%llu",item->name_change.new_id);
935 _dbus_verbose ("New id: %s\n", pDBusName);
936 ITER_APPEND_STR(pDBusName)
937 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
939 ret_size = put_message_into_data(message, data);
942 case KDBUS_MSG_ID_ADD:
943 _dbus_verbose(" +%s (%llu bytes) id=%llu flags=%llu\n",
944 enum_MSG(item->type), (unsigned long long) item->size,
945 (unsigned long long) item->id_change.id,
946 (unsigned long long) item->id_change.flags);
948 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
955 sprintf(dbus_name,":1.%llu",item->id_change.id);
956 dbus_message_iter_init_append(message, &args);
957 ITER_APPEND_STR(pDBusName)
958 ITER_APPEND_STR(emptyString)
959 ITER_APPEND_STR(pDBusName)
960 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
962 ret_size = put_message_into_data(message, data);
965 case KDBUS_MSG_ID_REMOVE:
966 _dbus_verbose(" +%s (%llu bytes) id=%llu flags=%llu\n",
967 enum_MSG(item->type), (unsigned long long) item->size,
968 (unsigned long long) item->id_change.id,
969 (unsigned long long) item->id_change.flags);
971 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
978 sprintf(dbus_name,":1.%llu",item->id_change.id);
979 dbus_message_iter_init_append(message, &args);
980 ITER_APPEND_STR(pDBusName)
981 ITER_APPEND_STR(pDBusName)
982 ITER_APPEND_STR(emptyString)
983 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
985 ret_size = put_message_into_data(message, data);
987 #if KDBUS_MSG_DECODE_DEBUG == 1
989 _dbus_verbose(" +%s (%llu bytes)\n", enum_MSG(item->type), item->size);
995 #if KDBUS_MSG_DECODE_DEBUG == 1
997 if ((char *)item - ((char *)msg + msg->size) >= 8)
998 _dbus_verbose("invalid padding at end of message\n");
1003 dbus_message_unref(message);
1008 * Reads message from kdbus and puts it into dbus buffer and fds
1010 * @param transport transport
1011 * @param buffer place to copy received message to
1012 * @param fds place to store file descriptors sent in the message
1013 * @param n_fds place to store number of file descriptors
1014 * @return size of received message on success, -1 on error
1016 static int kdbus_read_message(DBusTransportKdbus *socket_transport, DBusString *buffer, int* fds, int* n_fds)
1018 int ret_size, buf_size;
1019 uint64_t __attribute__ ((__aligned__(8))) offset;
1020 struct kdbus_msg *msg;
1024 start = _dbus_string_get_length (buffer);
1027 if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RECV, &offset) < 0)
1031 _dbus_verbose("kdbus error receiving message: %d (%m)\n", errno);
1032 _dbus_string_set_length (buffer, start);
1036 msg = (struct kdbus_msg *)((char*)socket_transport->kdbus_mmap_ptr + offset);
1038 buf_size = kdbus_message_size(msg);
1041 _dbus_verbose("kdbus error - too short message: %d (%m)\n", errno);
1045 /* What is the maximum size of the locally generated message?
1046 I just assume 2048 bytes */
1047 buf_size = MAX(buf_size, 2048);
1049 if (!_dbus_string_lengthen (buffer, buf_size))
1054 data = _dbus_string_get_data_len (buffer, start, buf_size);
1056 ret_size = kdbus_decode_msg(msg, data, socket_transport, fds, n_fds);
1058 if(ret_size == -1) /* error */
1060 _dbus_string_set_length (buffer, start);
1063 else if (buf_size != ret_size) /* case of locally generated message */
1065 _dbus_string_set_length (buffer, start + ret_size);
1069 if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RELEASE, &offset) < 0)
1073 _dbus_verbose("kdbus error freeing message: %d (%m)\n", errno);
1080 * copy-paste from socket transport with needed renames only.
1083 free_watches (DBusTransport *transport)
1085 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1087 _dbus_verbose ("start\n");
1089 if (kdbus_transport->read_watch)
1091 if (transport->connection)
1092 _dbus_connection_remove_watch_unlocked (transport->connection,
1093 kdbus_transport->read_watch);
1094 _dbus_watch_invalidate (kdbus_transport->read_watch);
1095 _dbus_watch_unref (kdbus_transport->read_watch);
1096 kdbus_transport->read_watch = NULL;
1099 if (kdbus_transport->write_watch)
1101 if (transport->connection)
1102 _dbus_connection_remove_watch_unlocked (transport->connection,
1103 kdbus_transport->write_watch);
1104 _dbus_watch_invalidate (kdbus_transport->write_watch);
1105 _dbus_watch_unref (kdbus_transport->write_watch);
1106 kdbus_transport->write_watch = NULL;
1109 _dbus_verbose ("end\n");
1113 * copy-paste from socket transport with needed renames only.
1116 transport_finalize (DBusTransport *transport)
1118 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1120 _dbus_verbose ("\n");
1122 free_watches (transport);
1124 _dbus_string_free (&kdbus_transport->encoded_outgoing);
1125 _dbus_string_free (&kdbus_transport->encoded_incoming);
1127 _dbus_transport_finalize_base (transport);
1129 _dbus_assert (kdbus_transport->read_watch == NULL);
1130 _dbus_assert (kdbus_transport->write_watch == NULL);
1132 dbus_free (transport);
1136 * copy-paste from socket transport with needed renames only.
1139 check_write_watch (DBusTransport *transport)
1141 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1144 if (transport->connection == NULL)
1147 if (transport->disconnected)
1149 _dbus_assert (kdbus_transport->write_watch == NULL);
1153 _dbus_transport_ref (transport);
1155 #ifdef DBUS_AUTHENTICATION
1156 if (_dbus_transport_try_to_authenticate (transport))
1158 needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection);
1159 #ifdef DBUS_AUTHENTICATION
1162 if (transport->send_credentials_pending)
1166 DBusAuthState auth_state;
1168 auth_state = _dbus_auth_do_work (transport->auth);
1170 /* If we need memory we install the write watch just in case,
1171 * if there's no need for it, it will get de-installed
1172 * next time we try reading.
1174 if (auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND ||
1175 auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY)
1182 _dbus_verbose ("check_write_watch(): needed = %d on connection %p watch %p fd = %d outgoing messages exist %d\n",
1183 needed, transport->connection, kdbus_transport->write_watch,
1184 kdbus_transport->fd,
1185 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1187 _dbus_connection_toggle_watch_unlocked (transport->connection,
1188 kdbus_transport->write_watch,
1191 _dbus_transport_unref (transport);
1195 * copy-paste from socket transport with needed renames only.
1198 check_read_watch (DBusTransport *transport)
1200 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1201 dbus_bool_t need_read_watch;
1203 _dbus_verbose ("fd = %d\n",kdbus_transport->fd);
1205 if (transport->connection == NULL)
1208 if (transport->disconnected)
1210 _dbus_assert (kdbus_transport->read_watch == NULL);
1214 _dbus_transport_ref (transport);
1216 #ifdef DBUS_AUTHENTICATION
1217 if (_dbus_transport_try_to_authenticate (transport))
1220 (_dbus_counter_get_size_value (transport->live_messages) < transport->max_live_messages_size) &&
1221 (_dbus_counter_get_unix_fd_value (transport->live_messages) < transport->max_live_messages_unix_fds);
1222 #ifdef DBUS_AUTHENTICATION
1225 if (transport->receive_credentials_pending)
1226 need_read_watch = TRUE;
1229 /* The reason to disable need_read_watch when not WAITING_FOR_INPUT
1230 * is to avoid spinning on the file descriptor when we're waiting
1231 * to write or for some other part of the auth process
1233 DBusAuthState auth_state;
1235 auth_state = _dbus_auth_do_work (transport->auth);
1237 /* If we need memory we install the read watch just in case,
1238 * if there's no need for it, it will get de-installed
1239 * next time we try reading. If we're authenticated we
1240 * install it since we normally have it installed while
1243 if (auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT ||
1244 auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY ||
1245 auth_state == DBUS_AUTH_STATE_AUTHENTICATED)
1246 need_read_watch = TRUE;
1248 need_read_watch = FALSE;
1253 _dbus_verbose (" setting read watch enabled = %d\n", need_read_watch);
1254 _dbus_connection_toggle_watch_unlocked (transport->connection,
1255 kdbus_transport->read_watch,
1258 _dbus_transport_unref (transport);
1262 * copy-paste from socket transport.
1265 do_io_error (DBusTransport *transport)
1267 _dbus_transport_ref (transport);
1268 _dbus_transport_disconnect (transport);
1269 _dbus_transport_unref (transport);
1272 #ifdef DBUS_AUTHENTICATION
1273 /* return value is whether we successfully read any new data. */
1275 read_data_into_auth (DBusTransport *transport,
1278 DBusTransportKdbus *socket_transport = (DBusTransportKdbus*) transport;
1285 _dbus_auth_get_buffer (transport->auth, &buffer);
1287 bytes_read = kdbus_read_message(socket_transport, buffer, fds, &n_fds);
1289 _dbus_auth_return_buffer (transport->auth, buffer,
1290 bytes_read > 0 ? bytes_read : 0);
1294 _dbus_verbose (" read %d bytes in auth phase\n", bytes_read);
1297 else if (bytes_read < 0)
1299 /* EINTR already handled for us */
1301 if (_dbus_get_is_errno_enomem ())
1305 else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1306 ; /* do nothing, just return FALSE below */
1309 _dbus_verbose ("Error reading from remote app: %s\n",
1310 _dbus_strerror_from_errno ());
1311 do_io_error (transport);
1318 _dbus_assert (bytes_read == 0);
1320 _dbus_verbose ("Disconnected from remote app\n");
1321 do_io_error (transport);
1327 static int kdbus_send_auth (DBusTransport *transport, const DBusString *buffer)
1330 int bytes_written = -1;
1331 struct kdbus_msg *msg;
1332 struct kdbus_item *item;
1334 len = _dbus_string_get_length (buffer);
1335 // data = _dbus_string_get_const_data_len (buffer, 0, len);
1337 msg = kdbus_init_msg(NULL, 1, 0, FALSE, 0, (DBusTransportKdbus*)transport);
1339 MSG_ITEM_BUILD_VEC(_dbus_string_get_const_data_len (buffer, 0, len), len);
1342 if(ioctl(((DBusTransportKdbus*)transport)->fd, KDBUS_CMD_MSG_SEND, msg))
1346 _dbus_verbose ("Error writing auth: %d, %m\n", errno);
1349 bytes_written = len;
1351 return bytes_written;
1354 /* Return value is whether we successfully wrote any bytes */
1356 write_data_from_auth (DBusTransport *transport)
1358 // DBusTransportKdbus *socket_transport = (DBusTransportSocket*) transport;
1360 const DBusString *buffer;
1362 if (!_dbus_auth_get_bytes_to_send (transport->auth,
1366 bytes_written = kdbus_send_auth (transport, buffer);
1368 if (bytes_written > 0)
1370 _dbus_auth_bytes_sent (transport->auth, bytes_written);
1373 else if (bytes_written < 0)
1375 /* EINTR already handled for us */
1377 if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1381 _dbus_verbose ("Error writing to remote app: %s\n",
1382 _dbus_strerror_from_errno ());
1383 do_io_error (transport);
1392 exchange_credentials (DBusTransport *transport,
1393 dbus_bool_t do_reading,
1394 dbus_bool_t do_writing)
1396 DBusTransportKdbus *socket_transport = (DBusTransportKdbus*) transport;
1397 DBusError error = DBUS_ERROR_INIT;
1399 _dbus_verbose ("exchange_credentials: do_reading = %d, do_writing = %d\n",
1400 do_reading, do_writing);
1402 if (do_writing && transport->send_credentials_pending)
1404 if (_dbus_send_credentials_socket (socket_transport->fd,
1407 transport->send_credentials_pending = FALSE;
1411 _dbus_verbose ("Failed to write credentials: %s\n", error.message);
1412 dbus_error_free (&error);
1413 do_io_error (transport);
1417 if (do_reading && transport->receive_credentials_pending)
1419 /* FIXME this can fail due to IO error _or_ OOM, broken
1420 * (somewhat tricky to fix since the OOM error can be set after
1421 * we already read the credentials byte, so basically we need to
1422 * separate reading the byte and storing it in the
1423 * transport->credentials). Does not really matter for now
1424 * because storing in credentials never actually fails on unix.
1426 if (_dbus_read_credentials_socket (socket_transport->fd,
1427 transport->credentials,
1430 transport->receive_credentials_pending = FALSE;
1434 _dbus_verbose ("Failed to read credentials %s\n", error.message);
1435 dbus_error_free (&error);
1436 do_io_error (transport);
1440 if (!(transport->send_credentials_pending ||
1441 transport->receive_credentials_pending))
1443 if (!_dbus_auth_set_credentials (transport->auth,
1444 transport->credentials))
1452 do_authentication (DBusTransport *transport,
1453 dbus_bool_t do_reading,
1454 dbus_bool_t do_writing,
1455 dbus_bool_t *auth_completed)
1458 dbus_bool_t orig_auth_state;
1462 orig_auth_state = _dbus_transport_try_to_authenticate (transport);
1464 /* This is essential to avoid the check_write_watch() at the end,
1465 * we don't want to add a write watch in do_iteration before
1466 * we try writing and get EAGAIN
1468 if (orig_auth_state)
1471 *auth_completed = FALSE;
1475 _dbus_transport_ref (transport);
1477 while (!_dbus_transport_try_to_authenticate (transport) &&
1478 _dbus_transport_get_is_connected (transport))
1480 if (!exchange_credentials (transport, do_reading, do_writing))
1486 if (transport->send_credentials_pending ||
1487 transport->receive_credentials_pending)
1489 _dbus_verbose ("send_credentials_pending = %d receive_credentials_pending = %d\n",
1490 transport->send_credentials_pending,
1491 transport->receive_credentials_pending);
1495 #define TRANSPORT_SIDE(t) ((t)->is_server ? "server" : "client")
1496 switch (_dbus_auth_do_work (transport->auth))
1498 case DBUS_AUTH_STATE_WAITING_FOR_INPUT:
1499 _dbus_verbose (" %s auth state: waiting for input\n",
1500 TRANSPORT_SIDE (transport));
1501 if (!do_reading || !read_data_into_auth (transport, &oom))
1505 case DBUS_AUTH_STATE_WAITING_FOR_MEMORY:
1506 _dbus_verbose (" %s auth state: waiting for memory\n",
1507 TRANSPORT_SIDE (transport));
1512 case DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND:
1513 _dbus_verbose (" %s auth state: bytes to send\n",
1514 TRANSPORT_SIDE (transport));
1515 if (!do_writing || !write_data_from_auth (transport))
1519 case DBUS_AUTH_STATE_NEED_DISCONNECT:
1520 _dbus_verbose (" %s auth state: need to disconnect\n",
1521 TRANSPORT_SIDE (transport));
1522 do_io_error (transport);
1525 case DBUS_AUTH_STATE_AUTHENTICATED:
1526 _dbus_verbose (" %s auth state: authenticated\n",
1527 TRANSPORT_SIDE (transport));
1534 *auth_completed = (orig_auth_state != _dbus_transport_try_to_authenticate (transport));
1536 check_read_watch (transport);
1537 check_write_watch (transport);
1538 _dbus_transport_unref (transport);
1547 /* returns false on oom */
1549 do_writing (DBusTransport *transport)
1551 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1554 #ifdef DBUS_AUTHENTICATION
1555 /* No messages without authentication! */
1556 if (!_dbus_transport_try_to_authenticate (transport))
1558 _dbus_verbose ("Not authenticated, not writing anything\n");
1563 if (transport->disconnected)
1565 _dbus_verbose ("Not connected, not writing anything\n");
1570 _dbus_verbose ("do_writing(), have_messages = %d, fd = %d\n",
1571 _dbus_connection_has_messages_to_send_unlocked (transport->connection),
1572 kdbus_transport->fd);
1577 while (!transport->disconnected && _dbus_connection_has_messages_to_send_unlocked (transport->connection))
1580 DBusMessage *message;
1581 const DBusString *header;
1582 const DBusString *body;
1583 int total_bytes_to_write;
1584 const char* pDestination;
1586 message = _dbus_connection_get_message_to_send (transport->connection);
1587 _dbus_assert (message != NULL);
1588 if(dbus_message_get_sender(message) == NULL) //needed for daemon to pass pending activation messages
1590 dbus_message_unlock(message);
1591 dbus_message_set_sender(message, kdbus_transport->sender);
1592 dbus_message_lock (message);
1594 _dbus_message_get_network_data (message, &header, &body);
1595 total_bytes_to_write = _dbus_string_get_length(header) + _dbus_string_get_length(body);
1596 pDestination = dbus_message_get_destination(message);
1600 if(!strcmp(pDestination, DBUS_SERVICE_DBUS))
1602 if(!strcmp(dbus_message_get_interface(message), DBUS_INTERFACE_DBUS))
1606 ret = emulateOrgFreedesktopDBus(transport, message);
1614 bytes_written = total_bytes_to_write;
1617 //else send to "daemon" as to normal recipient
1621 if (_dbus_auth_needs_encoding (transport->auth))
1623 if (_dbus_string_get_length (&kdbus_transport->encoded_outgoing) == 0)
1625 if (!_dbus_auth_encode_data (transport->auth,
1626 header, &kdbus_transport->encoded_outgoing))
1632 if (!_dbus_auth_encode_data (transport->auth,
1633 body, &kdbus_transport->encoded_outgoing))
1635 _dbus_string_set_length (&kdbus_transport->encoded_outgoing, 0);
1641 total_bytes_to_write = _dbus_string_get_length (&kdbus_transport->encoded_outgoing);
1642 if(total_bytes_to_write > kdbus_transport->max_bytes_written_per_iteration)
1645 bytes_written = kdbus_write_msg(kdbus_transport, message, pDestination, TRUE);
1649 if(total_bytes_to_write > kdbus_transport->max_bytes_written_per_iteration)
1652 bytes_written = kdbus_write_msg(kdbus_transport, message, pDestination, FALSE);
1656 if (bytes_written < 0)
1658 /* EINTR already handled for us */
1660 /* For some discussion of why we also ignore EPIPE here, see
1661 * http://lists.freedesktop.org/archives/dbus/2008-March/009526.html
1664 if (_dbus_get_is_errno_eagain_or_ewouldblock () || _dbus_get_is_errno_epipe ())
1668 _dbus_verbose ("Error writing to remote app: %s\n", _dbus_strerror_from_errno ());
1669 do_io_error (transport);
1675 _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
1676 total_bytes_to_write);
1678 kdbus_transport->message_bytes_written += bytes_written;
1680 _dbus_assert (kdbus_transport->message_bytes_written <=
1681 total_bytes_to_write);
1683 if (kdbus_transport->message_bytes_written == total_bytes_to_write)
1685 kdbus_transport->message_bytes_written = 0;
1686 _dbus_string_set_length (&kdbus_transport->encoded_outgoing, 0);
1687 _dbus_string_compact (&kdbus_transport->encoded_outgoing, 2048);
1689 _dbus_connection_message_sent_unlocked (transport->connection,
1701 /* returns false on out-of-memory */
1703 do_reading (DBusTransport *transport)
1705 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1708 dbus_bool_t oom = FALSE;
1711 _dbus_verbose ("fd = %d\n",kdbus_transport->fd);
1713 #ifdef DBUS_AUTHENTICATION
1714 /* No messages without authentication! */
1715 if (!_dbus_transport_try_to_authenticate (transport))
1721 /* See if we've exceeded max messages and need to disable reading */
1722 check_read_watch (transport);
1724 _dbus_assert (kdbus_transport->read_watch != NULL ||
1725 transport->disconnected);
1727 if (transport->disconnected)
1730 if (!dbus_watch_get_enabled (kdbus_transport->read_watch))
1733 if (!_dbus_message_loader_get_unix_fds(transport->loader, &fds, &n_fds))
1735 _dbus_verbose ("Out of memory reading file descriptors\n");
1739 _dbus_message_loader_get_buffer (transport->loader, &buffer);
1741 if (_dbus_auth_needs_decoding (transport->auth))
1743 bytes_read = kdbus_read_message(kdbus_transport, &kdbus_transport->encoded_incoming, fds, &n_fds);
1745 _dbus_assert (_dbus_string_get_length (&kdbus_transport->encoded_incoming) == bytes_read);
1749 if (!_dbus_auth_decode_data (transport->auth,
1750 &kdbus_transport->encoded_incoming,
1753 _dbus_verbose ("Out of memory decoding incoming data\n");
1754 _dbus_message_loader_return_buffer (transport->loader,
1756 _dbus_string_get_length (buffer));
1761 _dbus_string_set_length (&kdbus_transport->encoded_incoming, 0);
1762 _dbus_string_compact (&kdbus_transport->encoded_incoming, 2048);
1766 bytes_read = kdbus_read_message(kdbus_transport, buffer, fds, &n_fds);
1768 if (bytes_read >= 0 && n_fds > 0)
1769 _dbus_verbose("Read %i unix fds\n", n_fds);
1771 _dbus_message_loader_return_buffer (transport->loader,
1773 bytes_read < 0 ? 0 : bytes_read);
1774 _dbus_message_loader_return_unix_fds(transport->loader, fds, bytes_read < 0 ? 0 : n_fds);
1778 /* EINTR already handled for us */
1780 if (_dbus_get_is_errno_enomem ())
1782 _dbus_verbose ("Out of memory in read()/do_reading()\n");
1786 else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1790 _dbus_verbose ("Error reading from remote app: %s\n",
1791 _dbus_strerror_from_errno ());
1792 do_io_error (transport);
1796 else if (bytes_read == 0)
1798 _dbus_verbose ("Disconnected from remote app\n");
1799 do_io_error (transport);
1804 _dbus_verbose (" read %d bytes\n", bytes_read);
1806 if (!_dbus_transport_queue_messages (transport))
1809 _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
1813 /* Try reading more data until we get EAGAIN and return, or
1814 * exceed max bytes per iteration. If in blocking mode of
1815 * course we'll block instead of returning.
1827 * copy-paste from socket transport.
1830 unix_error_with_read_to_come (DBusTransport *itransport,
1834 DBusTransportKdbus *transport = (DBusTransportKdbus *) itransport;
1836 if (!((flags & DBUS_WATCH_HANGUP) || (flags & DBUS_WATCH_ERROR)))
1839 /* If we have a read watch enabled ...
1840 we -might have data incoming ... => handle the HANGUP there */
1841 if (watch != transport->read_watch && _dbus_watch_get_enabled (transport->read_watch))
1848 * copy-paste from socket transport with needed renames only.
1851 kdbus_handle_watch (DBusTransport *transport,
1855 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1857 _dbus_assert (watch == kdbus_transport->read_watch ||
1858 watch == kdbus_transport->write_watch);
1859 _dbus_assert (watch != NULL);
1861 /* If we hit an error here on a write watch, don't disconnect the transport yet because data can
1862 * still be in the buffer and do_reading may need several iteration to read
1863 * it all (because of its max_bytes_read_per_iteration limit).
1865 if (!(flags & DBUS_WATCH_READABLE) && unix_error_with_read_to_come (transport, watch, flags))
1867 _dbus_verbose ("Hang up or error on watch\n");
1868 _dbus_transport_disconnect (transport);
1872 if (watch == kdbus_transport->read_watch &&
1873 (flags & DBUS_WATCH_READABLE))
1875 #ifdef DBUS_AUTHENTICATION
1876 dbus_bool_t auth_finished;
1879 _dbus_verbose ("handling read watch %p flags = %x\n",
1882 #ifdef DBUS_AUTHENTICATION
1883 if (!do_authentication (transport, TRUE, FALSE, &auth_finished))
1886 /* We don't want to do a read immediately following
1887 * a successful authentication. This is so we
1888 * have a chance to propagate the authentication
1889 * state further up. Specifically, we need to
1890 * process any pending data from the auth object.
1895 if (!do_reading (transport))
1897 _dbus_verbose ("no memory to read\n");
1900 #ifdef DBUS_AUTHENTICATION
1904 _dbus_verbose ("Not reading anything since we just completed the authentication\n");
1908 else if (watch == kdbus_transport->write_watch &&
1909 (flags & DBUS_WATCH_WRITABLE))
1912 _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n",
1913 _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1915 #ifdef DBUS_AUTHENTICATION
1916 if (!do_authentication (transport, FALSE, TRUE, NULL))
1919 if (!do_writing (transport))
1921 _dbus_verbose ("no memory to write\n");
1925 /* See if we still need the write watch */
1926 check_write_watch (transport);
1928 #ifdef DBUS_ENABLE_VERBOSE_MODE
1931 if (watch == kdbus_transport->read_watch)
1932 _dbus_verbose ("asked to handle read watch with non-read condition 0x%x\n",
1934 else if (watch == kdbus_transport->write_watch)
1935 _dbus_verbose ("asked to handle write watch with non-write condition 0x%x\n",
1938 _dbus_verbose ("asked to handle watch %p on fd %d that we don't recognize\n",
1939 watch, dbus_watch_get_socket (watch));
1941 #endif /* DBUS_ENABLE_VERBOSE_MODE */
1947 * copy-paste from socket transport with needed renames only.
1950 kdbus_disconnect (DBusTransport *transport)
1952 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1954 _dbus_verbose ("\n");
1956 free_watches (transport);
1958 _dbus_close_socket (kdbus_transport->fd, NULL);
1959 kdbus_transport->fd = -1;
1963 * copy-paste from socket transport with needed renames only.
1966 kdbus_connection_set (DBusTransport *transport)
1968 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1970 dbus_connection_set_is_authenticated(transport->connection); //now we don't have authentication in kdbus
1972 _dbus_watch_set_handler (kdbus_transport->write_watch,
1973 _dbus_connection_handle_watch,
1974 transport->connection, NULL);
1976 _dbus_watch_set_handler (kdbus_transport->read_watch,
1977 _dbus_connection_handle_watch,
1978 transport->connection, NULL);
1980 if (!_dbus_connection_add_watch_unlocked (transport->connection,
1981 kdbus_transport->write_watch))
1984 if (!_dbus_connection_add_watch_unlocked (transport->connection,
1985 kdbus_transport->read_watch))
1987 _dbus_connection_remove_watch_unlocked (transport->connection,
1988 kdbus_transport->write_watch);
1992 check_read_watch (transport);
1993 check_write_watch (transport);
1998 /** original dbus copy-pasted comment
1999 * @todo We need to have a way to wake up the select sleep if
2000 * a new iteration request comes in with a flag (read/write) that
2001 * we're not currently serving. Otherwise a call that just reads
2002 * could block a write call forever (if there are no incoming
2006 kdbus_do_iteration (DBusTransport *transport,
2008 int timeout_milliseconds)
2010 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
2015 _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p fd = %d\n",
2016 flags & DBUS_ITERATION_DO_READING ? "read" : "",
2017 flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
2018 timeout_milliseconds,
2019 kdbus_transport->read_watch,
2020 kdbus_transport->write_watch,
2021 kdbus_transport->fd);
2023 /* the passed in DO_READING/DO_WRITING flags indicate whether to
2024 * read/write messages, but regardless of those we may need to block
2025 * for reading/writing to do auth. But if we do reading for auth,
2026 * we don't want to read any messages yet if not given DO_READING.
2029 poll_fd.fd = kdbus_transport->fd;
2032 if (_dbus_transport_try_to_authenticate (transport))
2034 /* This is kind of a hack; if we have stuff to write, then try
2035 * to avoid the poll. This is probably about a 5% speedup on an
2036 * echo client/server.
2038 * If both reading and writing were requested, we want to avoid this
2039 * since it could have funky effects:
2040 * - both ends spinning waiting for the other one to read
2041 * data so they can finish writing
2042 * - prioritizing all writing ahead of reading
2044 if ((flags & DBUS_ITERATION_DO_WRITING) &&
2045 !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) &&
2046 !transport->disconnected &&
2047 _dbus_connection_has_messages_to_send_unlocked (transport->connection))
2049 do_writing (transport);
2051 if (transport->disconnected ||
2052 !_dbus_connection_has_messages_to_send_unlocked (transport->connection))
2056 /* If we get here, we decided to do the poll() after all */
2057 _dbus_assert (kdbus_transport->read_watch);
2058 if (flags & DBUS_ITERATION_DO_READING)
2059 poll_fd.events |= _DBUS_POLLIN;
2061 _dbus_assert (kdbus_transport->write_watch);
2062 if (flags & DBUS_ITERATION_DO_WRITING)
2063 poll_fd.events |= _DBUS_POLLOUT;
2067 DBusAuthState auth_state;
2069 auth_state = _dbus_auth_do_work (transport->auth);
2071 if (transport->receive_credentials_pending || auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT)
2072 poll_fd.events |= _DBUS_POLLIN;
2074 if (transport->send_credentials_pending || auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND)
2075 poll_fd.events |= _DBUS_POLLOUT;
2080 if (flags & DBUS_ITERATION_BLOCK)
2081 poll_timeout = timeout_milliseconds;
2085 /* For blocking selects we drop the connection lock here
2086 * to avoid blocking out connection access during a potentially
2087 * indefinite blocking call. The io path is still protected
2088 * by the io_path_cond condvar, so we won't reenter this.
2090 if (flags & DBUS_ITERATION_BLOCK)
2092 _dbus_verbose ("unlock pre poll\n");
2093 _dbus_connection_unlock (transport->connection);
2097 poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
2099 if (poll_res < 0 && _dbus_get_is_errno_eintr ())
2101 _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
2105 if (flags & DBUS_ITERATION_BLOCK)
2107 _dbus_verbose ("lock post poll\n");
2108 _dbus_connection_lock (transport->connection);
2114 poll_fd.revents = 0; /* some concern that posix does not guarantee this;
2115 * valgrind flags it as an error. though it probably
2116 * is guaranteed on linux at least.
2119 if (poll_fd.revents & _DBUS_POLLERR)
2120 do_io_error (transport);
2123 dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
2124 dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0;
2125 #ifdef DBUS_AUTHENTICATION
2126 dbus_bool_t authentication_completed;
2129 _dbus_verbose ("in iteration, need_read=%d need_write=%d\n",
2130 need_read, need_write);
2131 #ifdef DBUS_AUTHENTICATION
2132 do_authentication (transport, need_read, need_write,
2133 &authentication_completed);
2135 /* See comment in socket_handle_watch. */
2136 if (authentication_completed)
2139 if (need_read && (flags & DBUS_ITERATION_DO_READING))
2140 do_reading (transport);
2141 if (need_write && (flags & DBUS_ITERATION_DO_WRITING))
2142 do_writing (transport);
2146 _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
2150 /* We need to install the write watch only if we did not
2151 * successfully write everything. Note we need to be careful that we
2152 * don't call check_write_watch *before* do_writing, since it's
2153 * inefficient to add the write watch, and we can avoid it most of
2154 * the time since we can write immediately.
2156 * However, we MUST always call check_write_watch(); DBusConnection code
2157 * relies on the fact that running an iteration will notice that
2158 * messages are pending.
2160 check_write_watch (transport);
2162 _dbus_verbose (" ... leaving do_iteration()\n");
2166 * copy-paste from socket transport with needed renames only.
2169 kdbus_live_messages_changed (DBusTransport *transport)
2171 /* See if we should look for incoming messages again */
2172 check_read_watch (transport);
2176 kdbus_get_kdbus_fd (DBusTransport *transport,
2179 DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
2181 *fd_p = kdbus_transport->fd;
2186 static const DBusTransportVTable kdbus_vtable = {
2190 kdbus_connection_set,
2192 kdbus_live_messages_changed,
2197 * Creates a new transport for the given kdbus file descriptor. The file
2198 * descriptor must be nonblocking.
2200 * @param fd the file descriptor.
2201 * @param address the transport's address
2202 * @returns the new transport, or #NULL if no memory.
2204 static DBusTransport*
2205 _dbus_transport_new_kdbus_transport (int fd, const DBusString *address)
2207 DBusTransportKdbus *kdbus_transport;
2209 kdbus_transport = dbus_new0 (DBusTransportKdbus, 1);
2210 if (kdbus_transport == NULL)
2213 if (!_dbus_string_init (&kdbus_transport->encoded_outgoing))
2216 if (!_dbus_string_init (&kdbus_transport->encoded_incoming))
2219 kdbus_transport->write_watch = _dbus_watch_new (fd,
2220 DBUS_WATCH_WRITABLE,
2223 if (kdbus_transport->write_watch == NULL)
2226 kdbus_transport->read_watch = _dbus_watch_new (fd,
2227 DBUS_WATCH_READABLE,
2230 if (kdbus_transport->read_watch == NULL)
2233 if (!_dbus_transport_init_base (&kdbus_transport->base,
2238 #ifdef DBUS_AUTHENTICATION
2239 #ifdef HAVE_UNIX_FD_PASSING
2240 _dbus_auth_set_unix_fd_possible(kdbus_transport->base.auth, _dbus_socket_can_pass_unix_fd(fd));
2244 kdbus_transport->fd = fd;
2245 kdbus_transport->message_bytes_written = 0;
2247 /* These values should probably be tunable or something. */
2248 kdbus_transport->max_bytes_read_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2249 kdbus_transport->max_bytes_written_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
2251 kdbus_transport->kdbus_mmap_ptr = NULL;
2252 kdbus_transport->memfd = -1;
2254 return (DBusTransport*) kdbus_transport;
2257 _dbus_watch_invalidate (kdbus_transport->read_watch);
2258 _dbus_watch_unref (kdbus_transport->read_watch);
2260 _dbus_watch_invalidate (kdbus_transport->write_watch);
2261 _dbus_watch_unref (kdbus_transport->write_watch);
2263 _dbus_string_free (&kdbus_transport->encoded_incoming);
2265 _dbus_string_free (&kdbus_transport->encoded_outgoing);
2267 dbus_free (kdbus_transport);
2272 * Opens a connection to the kdbus bus
2274 * This will set FD_CLOEXEC for the socket returned.
2276 * @param path the path to UNIX domain socket
2277 * @param error return location for error code
2278 * @returns connection file descriptor or -1 on error
2280 static int _dbus_connect_kdbus (const char *path, DBusError *error)
2284 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2285 _dbus_verbose ("connecting to kdbus bus %s\n", path);
2287 fd = open(path, O_RDWR|O_CLOEXEC|O_NONBLOCK);
2289 dbus_set_error(error, _dbus_error_from_errno (errno), "Failed to open file descriptor: %s", _dbus_strerror (errno));
2295 * Creates a new transport for kdbus.
2296 * This creates a client-side of a transport.
2298 * @param path the path to the bus.
2299 * @param error address where an error can be returned.
2300 * @returns a new transport, or #NULL on failure.
2302 static DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error)
2305 DBusTransport *transport;
2308 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2310 if (!_dbus_string_init (&address))
2312 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2318 if ((!_dbus_string_append (&address, "kdbus:path=")) || (!_dbus_string_append (&address, path)))
2320 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2324 fd = _dbus_connect_kdbus (path, error);
2327 _DBUS_ASSERT_ERROR_IS_SET (error);
2331 _dbus_verbose ("Successfully connected to kdbus bus %s\n", path);
2333 transport = _dbus_transport_new_kdbus_transport (fd, &address);
2334 if (transport == NULL)
2336 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2340 _dbus_string_free (&address);
2345 _dbus_close_socket (fd, NULL);
2347 _dbus_string_free (&address);
2353 * Opens kdbus transport if method from address entry is kdbus
2355 * @param entry the address entry to try opening
2356 * @param transport_p return location for the opened transport
2357 * @param error error to be set
2358 * @returns result of the attempt
2360 DBusTransportOpenResult _dbus_transport_open_kdbus(DBusAddressEntry *entry,
2361 DBusTransport **transport_p,
2366 method = dbus_address_entry_get_method (entry);
2367 _dbus_assert (method != NULL);
2369 if (strcmp (method, "kdbus") == 0)
2371 const char *path = dbus_address_entry_get_value (entry, "path");
2375 _dbus_set_bad_address (error, "kdbus", "path", NULL);
2376 return DBUS_TRANSPORT_OPEN_BAD_ADDRESS;
2379 *transport_p = _dbus_transport_new_for_kdbus (path, error);
2381 if (*transport_p == NULL)
2383 _DBUS_ASSERT_ERROR_IS_SET (error);
2384 return DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT;
2388 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2389 return DBUS_TRANSPORT_OPEN_OK;
2394 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2395 return DBUS_TRANSPORT_OPEN_NOT_HANDLED;