X-Git-Url: http://review.tizen.org/git/?a=blobdiff_plain;f=dbus%2Fdbus-transport-kdbus.c;h=003d0c9821e80b7feffb08f41f2652e4605645e2;hb=5b2c2f7b42ce7158f61065d59b3de71ab3feb14e;hp=5ef4424cabd33cf298d28b3c5e8d51bb1d0407c8;hpb=58df94b3075c84072f93238c6b8f9dc9816b0272;p=platform%2Fupstream%2Fdbus.git diff --git a/dbus/dbus-transport-kdbus.c b/dbus/dbus-transport-kdbus.c index 5ef4424..003d0c9 100644 --- a/dbus/dbus-transport-kdbus.c +++ b/dbus/dbus-transport-kdbus.c @@ -17,6 +17,7 @@ #include "dbus-watch.h" #include "dbus-errors.h" #include "dbus-bus.h" +#include #include #include #include @@ -26,7 +27,9 @@ #include #include #include -#include +#include +#include +#include #define KDBUS_ALIGN8(l) (((l) + 7) & ~7) #define KDBUS_PART_HEADER_SIZE offsetof(struct kdbus_item, data) @@ -38,13 +41,17 @@ for (part = (head)->first; \ (uint8_t *)(part) < (uint8_t *)(head) + (head)->size; \ part = KDBUS_PART_NEXT(part)) -#define POOL_SIZE (16 * 1024LU * 1024LU) +#define RECEIVE_POOL_SIZE (10 * 1024LU * 1024LU) +#define MEMFD_SIZE_THRESHOLD (2 * 1024 * 1024LU) // over this memfd is used -/*struct and type below copied from dbus_transport_socket.c - * needed for _dbus_transport_new_for_socket_kdbus and kdbus_vtable(?) - * todo maybe DBusTransportSocket and _dbus_transport_new_for_socket_kdbus not needed here - - * maybe only static const DBusTransportVTable implementation will be enough - */ +#define KDBUS_MSG_DECODE_DEBUG 0 + +#define ITER_APPEND_STR(string) \ +if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &string)) \ +{ \ + ret_size = -1; \ + goto out; \ +}\ /** * Opaque object representing a socket file descriptor transport. @@ -61,8 +68,8 @@ struct DBusTransportSocket DBusWatch *read_watch; /**< Watch for readability. */ DBusWatch *write_watch; /**< Watch for writability. */ - int max_bytes_read_per_iteration; /**< To avoid blocking too long. */ - int max_bytes_written_per_iteration; /**< To avoid blocking too long. */ + int max_bytes_read_per_iteration; /**< In kdbus only to control overall message size*/ + int max_bytes_written_per_iteration; /**< In kdbus only to control overall message size*/ int message_bytes_written; /**< Number of bytes of current * outgoing message that have @@ -74,23 +81,17 @@ struct DBusTransportSocket DBusString encoded_incoming; /**< Encoded version of current * incoming data. */ - void* kdbus_mmap_ptr; + void* kdbus_mmap_ptr; /**< Mapped memory where Kdbus (kernel) writes + * messages incoming to us. + */ + int memfd; /**< File descriptor to special + * memory pool for bulk data + * transfer. Retrieved from + * Kdbus kernel module. + */ + __u64 bloom_size; /**< bloom filter field size */ }; - -//prototypes of local functions, needed for compiler -int _dbus_connect_kdbus (const char *path, DBusError *error); -DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error); -DBusTransport* _dbus_transport_new_for_socket_kdbus (int fd, const DBusString *server_guid, const DBusString *address); -struct kdbus_policy *make_policy_name(const char *name); -struct kdbus_policy *make_policy_access(__u64 type, __u64 bits, __u64 id); -void append_policy(struct kdbus_cmd_policy *cmd_policy, struct kdbus_policy *policy, __u64 max_size); -int kdbus_write_msg(DBusConnection *connection, DBusMessage *message, int fd); -int kdbus_write_msg_encoded(DBusMessage *message, DBusTransportSocket *socket_transport); -dbus_bool_t kdbus_mmap(DBusTransport* transport); -int kdbus_read_message(DBusTransportSocket *socket_transport, DBusString *buffer); -int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, void* mmap_ptr); - static dbus_bool_t socket_get_socket_fd (DBusTransport *transport, int *fd_p) @@ -102,147 +103,359 @@ socket_get_socket_fd (DBusTransport *transport, return TRUE; } -int kdbus_write_msg(DBusConnection *connection, DBusMessage *message, int fd) +/* + * Adds locally generated message to received messages queue + * + */ +static dbus_bool_t add_message_to_received(DBusMessage *message, DBusConnection* connection) { - struct kdbus_msg *msg; - struct kdbus_item *item; - uint64_t size; - const char *name; - uint64_t dst_id = KDBUS_DST_ID_BROADCAST; - const DBusString *header; - const DBusString *body; - uint64_t ret_size; + DBusList *message_link; + + message_link = _dbus_list_alloc_link (message); + if (message_link == NULL) + { + dbus_message_unref (message); + return FALSE; + } + + _dbus_connection_queue_synthesized_message_link(connection, message_link); + + return TRUE; +} + +static dbus_bool_t reply_with_error(char* error_type, const char* template, const char* object, DBusMessage *message, DBusConnection* connection) +{ + DBusMessage *errMessage; + char* error_msg = ""; + + if(template) + { + error_msg = alloca(strlen(template) + strlen(object)); + sprintf(error_msg, template, object); + } + else if(object) + error_msg = (char*)object; + + errMessage = generate_local_error_message(dbus_message_get_serial(message), error_type, error_msg); + if(errMessage == NULL) + return FALSE; + if (add_message_to_received(errMessage, connection)) + return TRUE; + + return FALSE; +} + +static dbus_bool_t reply_1_data(DBusMessage *message, int data_type, void* pData, DBusConnection* connection) +{ + DBusMessageIter args; + DBusMessage *reply; + + reply = dbus_message_new_method_return(message); + if(reply == NULL) + return FALSE; + dbus_message_set_sender(reply, DBUS_SERVICE_DBUS); + dbus_message_iter_init_append(reply, &args); + if (!dbus_message_iter_append_basic(&args, data_type, pData)) + { + dbus_message_unref(reply); + return FALSE; + } + if(add_message_to_received(reply, connection)) + return TRUE; + + return FALSE; +} + +/** + * Retrieves file descriptor to memory pool from kdbus module. + * It is then used for bulk data sending. + * Triggered when message payload is over MEMFD_SIZE_THRESHOLD + * + */ +static int kdbus_init_memfd(DBusTransportSocket* socket_transport) +{ + int memfd; + + if (ioctl(socket_transport->fd, KDBUS_CMD_MEMFD_NEW, &memfd) < 0) { + _dbus_verbose("KDBUS_CMD_MEMFD_NEW failed: \n"); + return -1; + } + + socket_transport->memfd = memfd; + _dbus_verbose("kdbus_init_memfd: %d!!\n", socket_transport->memfd); + return 0; +} + +/** + * Initiates Kdbus message structure. + * Calculates it's size, allocates memory and fills some fields. + * @param name Well-known name or NULL + * @param dst_id Numeric id of recipient + * @param body_size size of message body if present + * @param use_memfd flag to build memfd message + * @param fds_count number of file descriptors used + * @param transport transport + * @return initialized kdbus message + */ +static struct kdbus_msg* kdbus_init_msg(const char* name, __u64 dst_id, uint64_t body_size, dbus_bool_t use_memfd, int fds_count, DBusTransportSocket *transport) +{ + struct kdbus_msg* msg; + uint64_t msg_size; + + msg_size = sizeof(struct kdbus_msg); + + if(use_memfd == TRUE) // bulk data - memfd - encoded and plain + msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_memfd)); + else { + msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec)); + if(body_size) + msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec)); + } + + if(fds_count) + msg_size += KDBUS_ITEM_SIZE(sizeof(int)*fds_count); + + if (name) + msg_size += KDBUS_ITEM_SIZE(strlen(name) + 1); + else if (dst_id == KDBUS_DST_ID_BROADCAST) + msg_size += KDBUS_PART_HEADER_SIZE + transport->bloom_size; + + msg = malloc(msg_size); + if (!msg) + { + _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno)); + return NULL; + } + + memset(msg, 0, msg_size); + msg->size = msg_size; + msg->payload_type = KDBUS_PAYLOAD_DBUS1; + msg->dst_id = name ? 0 : dst_id; + msg->src_id = strtoull(dbus_bus_get_unique_name(transport->base.connection), NULL , 10); -// uint64_t i; + return msg; +} +/** + * Builds and sends kdbus message using Dbus message. + * Decide whether used payload vector or memfd memory pool. + * Handles broadcasts and unicast messages, and passing of Unix fds. + * Does error handling. + * TODO refactor to be more compact + * + * @param transport transport + * @param message DBus message to be sent + * @param encoded flag if the message is encoded + * @return size of data sent + */ +static int kdbus_write_msg(DBusTransportSocket *transport, DBusMessage *message, dbus_bool_t encoded) +{ + struct kdbus_msg *msg; + struct kdbus_item *item; + const char *name; + uint64_t dst_id = KDBUS_DST_ID_BROADCAST; + const DBusString *header; + const DBusString *body; + uint64_t ret_size = 0; + uint64_t body_size = 0; + uint64_t header_size = 0; + dbus_bool_t use_memfd; + const int *unix_fds; + unsigned fds_count; + dbus_bool_t autostart; + + // determine name and destination id if((name = dbus_message_get_destination(message))) { - _dbus_verbose ("do writing destination: %s\n", name); //todo can be removed at the end dst_id = KDBUS_DST_ID_WELL_KNOWN_NAME; - if((name[0] == ':') && (name[1] == '1') && (name[2] == '.')) + if((name[0] == ':') && (name[1] == '1') && (name[2] == '.')) /* if name starts with ":1." it is a unique name and should be send as number */ { - dst_id = strtoll(&name[3], NULL, 10); - _dbus_verbose ("do writing uniqe id: %lu\n", dst_id); //todo can be removed at the end + dst_id = strtoull(&name[3], NULL, 10); name = NULL; - } + } } - - _dbus_message_get_network_data (message, &header, &body); - ret_size = (uint64_t)_dbus_string_get_length(header); - - /* fprintf (stderr, "\nheader:\n"); - for(i=0; i < ret_size; i++) + + // get size of data + if(encoded) + ret_size = _dbus_string_get_length (&transport->encoded_outgoing); + else { - fprintf (stderr, "%02x", _dbus_string_get_byte(header,i)); + _dbus_message_get_network_data (message, &header, &body); + header_size = _dbus_string_get_length(header); + body_size = _dbus_string_get_length(body); + ret_size = header_size + body_size; } - fprintf (stderr, "\nret size: %lu, i: %lu\n", ret_size, i);*/ -// _dbus_verbose("padding bytes for header: %lu \n", KDBUS_ALIGN8(ret_size) - ret_size); + // check if message size is big enough to use memfd kdbus transport + use_memfd = ret_size > MEMFD_SIZE_THRESHOLD ? TRUE : FALSE; + if(use_memfd) kdbus_init_memfd(transport); + + _dbus_message_get_unix_fds(message, &unix_fds, &fds_count); + + // init basic message fields + msg = kdbus_init_msg(name, dst_id, body_size, use_memfd, fds_count, transport); + msg->cookie = dbus_message_get_serial(message); + autostart = dbus_message_get_auto_start (message); + if(!autostart) + msg->flags |= KDBUS_MSG_FLAGS_NO_AUTO_START; + + // build message contents + item = msg->items; + + // case 1 - bulk data transfer - memfd - encoded and plain + if(use_memfd) + { + char *buf; + + if(ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 0) < 0) + { + _dbus_verbose("memfd sealing failed: \n"); + goto out; + } - size = sizeof(struct kdbus_msg); - size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec)); - size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec)); + buf = mmap(NULL, ret_size, PROT_WRITE, MAP_SHARED, transport->memfd, 0); + if (buf == MAP_FAILED) + { + _dbus_verbose("mmap() fd=%i failed:%m", transport->memfd); + goto out; + } - if (dst_id == KDBUS_DST_ID_BROADCAST) - size += KDBUS_PART_HEADER_SIZE + 64; + if(encoded) + memcpy(buf, &transport->encoded_outgoing, ret_size); + else + { + memcpy(buf, _dbus_string_get_const_data(header), header_size); + if(body_size) { + buf+=header_size; + memcpy(buf, _dbus_string_get_const_data(body), body_size); + buf-=header_size; + } + } - if (name) - size += KDBUS_ITEM_SIZE(strlen(name) + 1); + munmap(buf, ret_size); - msg = malloc(size); - if (!msg) - { - _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno)); - return -1; - } + // seal data - kdbus module needs it + if(ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 1) < 0) { + _dbus_verbose("memfd sealing failed: %d (%m)\n", errno); + ret_size = -1; + goto out; + } - memset(msg, 0, size); - msg->size = size; - msg->src_id = strtoll(dbus_bus_get_unique_name(connection), NULL , 10); - _dbus_verbose("sending msg, src_id=%llu\n", msg->src_id); - msg->dst_id = name ? 0 : dst_id; - msg->cookie = dbus_message_get_serial(message); - msg->payload_type = KDBUS_PAYLOAD_DBUS1; + item->type = KDBUS_MSG_PAYLOAD_MEMFD; + item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_memfd); + item->memfd.size = ret_size; + item->memfd.fd = transport->memfd; + // case 2 - small encoded - don't use memfd + } else if(encoded) { + _dbus_verbose("sending encoded data\n"); + + item->type = KDBUS_MSG_PAYLOAD_VEC; + item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec); + item->vec.address = (unsigned long) &transport->encoded_outgoing; + item->vec.size = _dbus_string_get_length (&transport->encoded_outgoing); + + // case 3 - small not encoded - don't use memfd + } else { + _dbus_verbose("sending normal vector data\n"); + + item->type = KDBUS_MSG_PAYLOAD_VEC; + item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec); + item->vec.address = (unsigned long) _dbus_string_get_const_data(header); + item->vec.size = header_size; + + if(body_size) + { + _dbus_verbose("body attaching\n"); + item = KDBUS_PART_NEXT(item); + item->type = KDBUS_MSG_PAYLOAD_VEC; + item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec); + item->vec.address = (unsigned long) _dbus_string_get_const_data(body); + item->vec.size = body_size; + } + } - item = msg->items; + if(fds_count) + { + item = KDBUS_PART_NEXT(item); + item->type = KDBUS_MSG_FDS; + item->size = KDBUS_PART_HEADER_SIZE + (sizeof(int) * fds_count); + memcpy(item->fds, unix_fds, sizeof(int) * fds_count); + } if (name) { + item = KDBUS_PART_NEXT(item); item->type = KDBUS_MSG_DST_NAME; item->size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1; strcpy(item->str, name); - item = KDBUS_PART_NEXT(item); } - - item->type = KDBUS_MSG_PAYLOAD_VEC; - item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec); - item->vec.address = (uint64_t)_dbus_string_get_const_data(header); - item->vec.size = ret_size; - item = KDBUS_PART_NEXT(item); - - item->type = KDBUS_MSG_PAYLOAD_VEC; - item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec); - item->vec.address = (uint64_t)_dbus_string_get_const_data(body); - item->vec.size = (uint64_t)_dbus_string_get_length(body); - ret_size += item->vec.size; - - /* fprintf (stderr, "\nbody:\n"); - for(i=0; i < item->vec.size; i++) - { - fprintf (stderr, "%02x", _dbus_string_get_byte(body,i)); - } - fprintf (stderr, "\nitem->vec.size: %llu, i: %lu\n", item->vec.size, i);*/ - - item = KDBUS_PART_NEXT(item); - - if (dst_id == KDBUS_DST_ID_BROADCAST) + else if (dst_id == KDBUS_DST_ID_BROADCAST) { + item = KDBUS_PART_NEXT(item); item->type = KDBUS_MSG_BLOOM; - item->size = KDBUS_PART_HEADER_SIZE + 64; + item->size = KDBUS_PART_HEADER_SIZE + transport->bloom_size; + strncpy(item->data, dbus_message_get_interface(message), transport->bloom_size); } again: - if (ioctl(fd, KDBUS_CMD_MSG_SEND, msg)) + if (ioctl(transport->fd, KDBUS_CMD_MSG_SEND, msg)) { if(errno == EINTR) goto again; + if((errno == ESRCH) || (errno == ENXIO) || (errno = EADDRNOTAVAIL)) //when recipient is not available on the bus + { + if(autostart) + { + //todo start service here, otherwise + 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)) + goto out; + } + else + if(reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Name \"%s\" does not exist", dbus_message_get_destination(message), message, transport->base.connection)) + goto out; + + } _dbus_verbose("kdbus error sending message: err %d (%m)\n", errno); - return -1; + ret_size = -1; } +out: + free(msg); + close(transport->memfd); - free(msg); - - return ret_size; + return ret_size; } -int kdbus_write_msg_encoded(DBusMessage *message, DBusTransportSocket *socket_transport) +struct nameInfo { - struct kdbus_msg *msg; + __u64 uniqueId; + __u64 userId; + __u64 processId; + __u32 sec_label_len; + char *sec_label; +}; + +/** + * Performs kdbus query of id of the given name + * + * @param name name to query for + * @param fd bus file + * @param ownerID place to store id of the name + * @return 0 on success, -errno if failed + */ +static int kdbus_NameQuery(char* name, int fd, struct nameInfo* pInfo) +{ + struct kdbus_cmd_name_info *msg; struct kdbus_item *item; uint64_t size; - const char *name; - uint64_t dst_id = KDBUS_DST_ID_BROADCAST; - uint64_t ret_size; - - if((name = dbus_message_get_destination(message))) - { - _dbus_verbose ("do writing encoded message destination: %s\n", name); //todo can be removed at the end - if((name[0] == '1') && (name[1] == ':')) - { - dst_id = strtoll(&name[2], NULL, 10); - _dbus_verbose ("do writing encoded message uniqe id form name: %lu\n", dst_id); //todo can be removed at the end - name = NULL; - } - } - - size = sizeof(struct kdbus_msg); - size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec)); - - if (dst_id == KDBUS_DST_ID_BROADCAST) - size += KDBUS_PART_HEADER_SIZE + 64; + int ret; + uint64_t item_size; - if (name) - size += KDBUS_ITEM_SIZE(strlen(name) + 1); + pInfo->sec_label_len = 0; + pInfo->sec_label = NULL; + + item_size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1; + item_size = (item_size < 56) ? 56 : item_size; //at least 56 bytes are needed by kernel to place info about name, otherwise error + size = sizeof(struct kdbus_cmd_name_info) + item_size; msg = malloc(size); if (!msg) @@ -253,51 +466,322 @@ int kdbus_write_msg_encoded(DBusMessage *message, DBusTransportSocket *socket_tr memset(msg, 0, size); msg->size = size; - msg->src_id = strtoll(dbus_bus_get_unique_name(socket_transport->base.connection), NULL , 10); - _dbus_verbose("sending encoded msg, src_id=%llu\n", msg->src_id); - msg->dst_id = name ? 0 : dst_id; - msg->cookie = dbus_message_get_serial(message); - msg->payload_type = KDBUS_PAYLOAD_DBUS1; + if((name[0] == ':') && (name[1] == '1') && (name[2] == '.')) /* if name starts with ":1." it is a unique name and should be send as number */ + msg->id = strtoull(&name[3], NULL, 10); + else + msg->id = 0; item = msg->items; + item->type = KDBUS_NAME_INFO_ITEM_NAME; + item->size = item_size; + strcpy(item->str, name); - if (name) + again: + ret = ioctl(fd, KDBUS_CMD_NAME_QUERY, msg); + if (ret < 0) { - item->type = KDBUS_MSG_DST_NAME; - item->size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1; - strcpy(item->str, name); - item = KDBUS_PART_NEXT(item); + if(errno == EINTR) + goto again; + else if(ret == -ENOBUFS) + { + msg = realloc(msg, msg->size); //prepare memory + if(msg != NULL) + goto again; + } + pInfo->uniqueId = 0; + ret = -errno; } + else + { + pInfo->uniqueId = msg->id; + pInfo->userId = msg->creds.uid; + pInfo->processId = msg->creds.pid; +_dbus_verbose ("I'm alive 1\n"); + item = msg->items; + while((uint8_t *)(item) < (uint8_t *)(msg) + msg->size) + { + if(item->type == KDBUS_NAME_INFO_ITEM_SECLABEL) + { + pInfo->sec_label_len = item->size - KDBUS_PART_HEADER_SIZE - 1; + if(pInfo->sec_label_len != 0) + pInfo->sec_label = malloc(pInfo->sec_label_len); + if(pInfo->sec_label == NULL) + ret = -1; + else + memcpy(pInfo->sec_label, item->data, pInfo->sec_label_len); + + break; + } + item = KDBUS_PART_NEXT(item); + } + } + + free(msg); + return ret; +} - item->type = KDBUS_MSG_PAYLOAD_VEC; - item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec); - item->vec.address = (uint64_t)&socket_transport->encoded_outgoing; - item->vec.size = _dbus_string_get_length (&socket_transport->encoded_outgoing); - item = KDBUS_PART_NEXT(item); +/** + * Handles messages sent to bus daemon - "org.freedesktop.DBus" and translates them to appropriate + * kdbus ioctl commands. Than translate kdbus reply into dbus message and put it into recived messages queue. + * + * !!! Not all methods are handled !!! Doubt if it is even possible. + * If method is not handled, returns error reply org.freedesktop.DBus.Error.UnknownMethod + * + * Handled methods: + * - GetNameOwner + * - NameHasOwner + * - ListNames + * + * Not handled methods: + * - ListActivatableNames + * - StartServiceByName + * - UpdateActivationEnvironment + * - GetConnectionUnixUser + * - GetId + */ +static dbus_bool_t emulateOrgFreedesktopDBus(DBusTransport *transport, DBusMessage *message) +{ + int inter_ret; + struct nameInfo info; + dbus_bool_t ret_value; - if (dst_id == KDBUS_DST_ID_BROADCAST) + if(!strcmp(dbus_message_get_member(message), "GetNameOwner")) //returns id of the well known name { - item->type = KDBUS_MSG_BLOOM; - item->size = KDBUS_PART_HEADER_SIZE + 64; + char* name = NULL; + + dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID); + inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info); + if(inter_ret == 0) //unique id of the name + { + char unique_name[(unsigned int)(snprintf(name, 0, "%llu", ULLONG_MAX) + sizeof(":1."))]; + const char* pString = unique_name; + + sprintf(unique_name, ":1.%llu", (unsigned long long int)info.uniqueId); + _dbus_verbose("Unique name discovered:%s\n", unique_name); + ret_value = reply_1_data(message, DBUS_TYPE_STRING, &pString, transport->connection); + } + else if(inter_ret == -ENOENT) //name has no owner + return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get owner of name '%s': no such name", name, message, transport->connection); + else + { + _dbus_verbose("kdbus error sending name query: err %d (%m)\n", errno); + ret_value = reply_with_error(DBUS_ERROR_FAILED, "Could not determine unique name for '%s'", name, message, transport->connection); + } } + else if(!strcmp(dbus_message_get_member(message), "NameHasOwner")) //returns if name is currently registered on the bus + { + char* name = NULL; + dbus_bool_t result; - again: - if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_SEND, msg)) + dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID); + inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info); + if((inter_ret == 0) || (inter_ret == -ENOENT)) + { + result = (inter_ret == 0) ? TRUE : FALSE; + ret_value = reply_1_data(message, DBUS_TYPE_BOOLEAN, &result, transport->connection); + } + else + { + _dbus_verbose("kdbus error checking if name exists: err %d (%m)\n", errno); + ret_value = reply_with_error(DBUS_ERROR_FAILED, "Could not determine whether name '%s' exists", name, message, transport->connection); + } + } + else if(!strcmp(dbus_message_get_member(message), "GetConnectionUnixUser")) { - if(errno == EINTR) - goto again; - _dbus_verbose("error sending encoded message: err %d (%m)\n", errno); - return -1; + char* name = NULL; + + dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID); + inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info); + if(inter_ret == 0) //name found + { + _dbus_verbose("User id:%llu\n", (unsigned long long) info.userId); + ret_value = reply_1_data(message, DBUS_TYPE_UINT32, &info.userId, transport->connection); + } + else if(inter_ret == -ENOENT) //name has no owner + return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get UID of name '%s': no such name", name, message, transport->connection); + else + { + _dbus_verbose("kdbus error determining UID: err %d (%m)\n", errno); + ret_value = reply_with_error(DBUS_ERROR_FAILED, "Could not determine UID for '%s'", name, message, transport->connection); + } } + else if(!strcmp(dbus_message_get_member(message), "GetConnectionUnixProcessID")) + { + char* name = NULL; + + dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID); + inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info); + if(inter_ret == 0) //name found + ret_value = reply_1_data(message, DBUS_TYPE_UINT32, &info.processId, transport->connection); + else if(inter_ret == -ENOENT) //name has no owner + return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get PID of name '%s': no such name", name, message, transport->connection); + else + { + _dbus_verbose("kdbus error determining PID: err %d (%m)\n", errno); + ret_value = reply_with_error(DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN,"Could not determine PID for '%s'", name, message, transport->connection); + } + } + else if(!strcmp(dbus_message_get_member(message), "ListNames")) //return all well known names on he bus + { + struct kdbus_cmd_names* pCmd; + uint64_t cmd_size; - free(msg); + cmd_size = sizeof(struct kdbus_cmd_names) + KDBUS_ITEM_SIZE(1); + pCmd = malloc(cmd_size); + if(pCmd == NULL) + goto out; + pCmd->size = cmd_size; - return ret_size; + again: + cmd_size = 0; + if(ioctl(((DBusTransportSocket*)transport)->fd, KDBUS_CMD_NAME_LIST, pCmd)) + { + if(errno == EINTR) + goto again; + if(errno == ENOBUFS) //buffer to small to put all names into it + cmd_size = pCmd->size; //here kernel tells how much memory it needs + else + { + _dbus_verbose("kdbus error asking for name list: err %d (%m)\n",errno); + goto out; + } + } + if(cmd_size) //kernel needs more memory + { + pCmd = realloc(pCmd, cmd_size); //prepare memory + if(pCmd == NULL) + return FALSE; + goto again; //and try again + } + else + { + DBusMessage *reply; + DBusMessageIter args; + struct kdbus_cmd_name* pCmd_name; + char* pName; + + reply = dbus_message_new_method_return(message); + if(reply == NULL) + goto out; + dbus_message_set_sender(reply, DBUS_SERVICE_DBUS); + dbus_message_iter_init_append(reply, &args); + + for (pCmd_name = pCmd->names; (uint8_t *)(pCmd_name) < (uint8_t *)(pCmd) + pCmd->size; pCmd_name = KDBUS_PART_NEXT(pCmd_name)) + { + pName = pCmd_name->name; + if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pName)) + { + dbus_message_unref(reply); + goto out; + } + } + + if(add_message_to_received(reply, transport->connection)) + { + free(pCmd); + return TRUE; + } + } +out: + if(pCmd) + free(pCmd); + return FALSE; + } + else if(!strcmp(dbus_message_get_member(message), "GetId")) + { + char* path; + char uuid[DBUS_UUID_LENGTH_BYTES]; + struct stat stats; + MD5_CTX md5; + DBusString binary, encoded; + + ret_value = FALSE; + path = &transport->address[11]; //start of kdbus bus path + if(stat(path, &stats) < -1) + { + _dbus_verbose("kdbus error reading stats of bus: err %d (%m)\n", errno); + return reply_with_error(DBUS_ERROR_FAILED, "Could not determine bus '%s' uuid", path, message, transport->connection); + } + + MD5_Init(&md5); + MD5_Update(&md5, path, strlen(path)); + MD5_Update(&md5, &stats.st_ctim.tv_sec, sizeof(stats.st_ctim.tv_sec)); + MD5_Final(uuid, &md5); + + if(!_dbus_string_init (&encoded)) + goto outgid; + _dbus_string_init_const_len (&binary, uuid, DBUS_UUID_LENGTH_BYTES); + if(!_dbus_string_hex_encode (&binary, 0, &encoded, _dbus_string_get_length (&encoded))) + goto outb; + path = (char*)_dbus_string_get_const_data (&encoded); + ret_value = reply_1_data(message, DBUS_TYPE_STRING, &path, transport->connection); + + outb: + _dbus_string_free(&binary); + _dbus_string_free(&encoded); + outgid: + return ret_value; + } + else if(!strcmp(dbus_message_get_member(message), "GetAdtAuditSessionData")) + { + char* name = NULL; + + dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID); + return reply_with_error(DBUS_ERROR_ADT_AUDIT_DATA_UNKNOWN, "Could not determine audit session data for '%s'", name, message, transport->connection); + } + else if(!strcmp(dbus_message_get_member(message), "GetConnectionSELinuxSecurityContext")) + { + char* name = NULL; + + dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID); + inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info); + if(inter_ret == -ENOENT) //name has no owner + return reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Could not get security context of name '%s': no such name", name, message, transport->connection); + else if(inter_ret < 0) + return reply_with_error(DBUS_ERROR_SELINUX_SECURITY_CONTEXT_UNKNOWN, "Could not determine security context for '%s'", name, message, transport->connection); + else + { + DBusMessage *reply; + + ret_value = FALSE; + reply = dbus_message_new_method_return(message); + if(reply != NULL) + { + dbus_message_set_sender(reply, DBUS_SERVICE_DBUS); + if (!dbus_message_append_args (reply, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &info.sec_label, info.sec_label_len, DBUS_TYPE_INVALID)) + dbus_message_unref(reply); + else if(add_message_to_received(reply, transport->connection)) + ret_value = TRUE; + } + } + } + else + return reply_with_error(DBUS_ERROR_UNKNOWN_METHOD, NULL, (char*)dbus_message_get_member(message), message, transport->connection); +/* else if(!strcmp(dbus_message_get_member(message), "ListActivatableNames")) //todo + { + + } + else if(!strcmp(dbus_message_get_member(message), "StartServiceByName")) + { + + } + else if(!strcmp(dbus_message_get_member(message), "UpdateActivationEnvironment")) + { + + } + else if(!strcmp(dbus_message_get_member(message), "ReloadConfig")) + { + + } + */ + + if(info.sec_label) + free(info.sec_label); + return ret_value; } -//todo functions from kdbus-utli.c for printing messages - maybe to remove at the end -char *msg_id(uint64_t id, char *buf); -char *msg_id(uint64_t id, char *buf) +#if KDBUS_MSG_DECODE_DEBUG == 1 +static char *msg_id(uint64_t id, char *buf) { if (id == 0) return "KERNEL"; @@ -306,7 +790,7 @@ char *msg_id(uint64_t id, char *buf) sprintf(buf, "%llu", (unsigned long long)id); return buf; } - +#endif struct kdbus_enum_table { long long id; const char *name; @@ -361,93 +845,130 @@ TABLE(PAYLOAD) = { }; LOOKUP(PAYLOAD); - //todo handling of all msg items -int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, void* mmap_ptr) +/** + * Puts locally generated message into received data buffer. + * Use only during receiving phase! + * + * @param message message to load + * @param data place to load message + * @return size of message + */ +static int put_message_into_data(DBusMessage *message, char* data) +{ + int ret_size; + const DBusString *header; + const DBusString *body; + int size; + + dbus_message_lock (message); + _dbus_message_get_network_data (message, &header, &body); + ret_size = _dbus_string_get_length(header); + memcpy(data, _dbus_string_get_const_data(header), ret_size); + data += ret_size; + size = _dbus_string_get_length(body); + memcpy(data, _dbus_string_get_const_data(body), size); + ret_size += size; + dbus_message_unref(message); + + return ret_size; +} +/** + * Decodes kdbus message in order to extract dbus message and put it into data and fds. + * Also captures and decodes kdbus error messages and kdbus kernel broadcasts and converts + * all of them into dbus messages. + * + * @param msg kdbus message + * @param data place to copy dbus message to + * @param socket_transport transport + * @param fds place to store file descriptors received + * @param n_fds place to store quantity of file descriptor + * @return number of dbus message's bytes received or -1 on error + */ +static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTransportSocket* socket_transport, int* fds, int* n_fds) { - const struct kdbus_item *item = msg->items; - char buf[32]; //todo to be removed after development + const struct kdbus_item *item; int ret_size = 0; DBusMessage *message = NULL; DBusMessageIter args; - char* pStringMallocked = NULL; - const char* dbus = "org.freedesktop.DBus"; const char* emptyString = ""; - const DBusString *header; - const DBusString *body; - int size; const char* pString = NULL; + char dbus_name[(unsigned int)(snprintf((char*)pString, 0, "%llu", ULLONG_MAX) + sizeof(":1."))]; + const char* pDBusName = dbus_name; +#if KDBUS_MSG_DECODE_DEBUG == 1 + char buf[32]; +#endif -// uint64_t i; - +#if KDBUS_MSG_DECODE_DEBUG == 1 _dbus_verbose("MESSAGE: %s (%llu bytes) flags=0x%llx, %s → %s, cookie=%llu, timeout=%llu\n", enum_PAYLOAD(msg->payload_type), (unsigned long long) msg->size, (unsigned long long) msg->flags, msg_id(msg->src_id, buf), msg_id(msg->dst_id, buf), (unsigned long long) msg->cookie, (unsigned long long) msg->timeout_ns); +#endif + + *n_fds = 0; KDBUS_PART_FOREACH(item, msg, items) { if (item->size <= KDBUS_PART_HEADER_SIZE) { _dbus_verbose(" +%s (%llu bytes) invalid data record\n", enum_MSG(item->type), item->size); - break; //todo to be discovered and rewritten + break; //??? continue (because dbus will find error) or break } switch (item->type) { case KDBUS_MSG_PAYLOAD_OFF: - { - char *s; + memcpy(data, (char *)socket_transport->kdbus_mmap_ptr + item->vec.offset, item->vec.size); + data += item->vec.size; + ret_size += item->vec.size; - if (item->vec.offset == ~0ULL) - s = "[padding bytes]"; - else - { -// uint64_t i; - - s = (char *)mmap_ptr + item->vec.offset; - /* fprintf(stderr,"\nmmap: %lu", (uint64_t)mmap_ptr); - fprintf (stderr, "\nheader: %llu\n", item->vec.size); - for(i=0; i < item->vec.size; i++) - { - fprintf (stderr, "%02x", (int)s[i]); - } - fprintf (stderr, "\nret size: %llu, i: %lu\n", item->vec.size, i);*/ - - memcpy(data, s, item->vec.size); - data += item->vec.size; - ret_size += item->vec.size; - } - - _dbus_verbose(" +%s (%llu bytes) off=%llu size=%llu '%s'\n", - enum_MSG(item->type), item->size, - (unsigned long long)item->vec.offset, - (unsigned long long)item->vec.size, s); - break; - } + _dbus_verbose(" +%s (%llu bytes) off=%llu size=%llu\n", + enum_MSG(item->type), item->size, + (unsigned long long)item->vec.offset, + (unsigned long long)item->vec.size); + break; case KDBUS_MSG_PAYLOAD_MEMFD: { char *buf; uint64_t size; - buf = mmap(NULL, item->memfd.size, PROT_READ, MAP_SHARED, item->memfd.fd, 0); - if (buf == MAP_FAILED) { + size = item->memfd.size; + _dbus_verbose("memfd.size : %llu\n", (unsigned long long)size); + + buf = mmap(NULL, size, PROT_READ , MAP_SHARED, item->memfd.fd, 0); + if (buf == MAP_FAILED) + { _dbus_verbose("mmap() fd=%i failed:%m", item->memfd.fd); - break; + return -1; } - if (ioctl(item->memfd.fd, KDBUS_CMD_MEMFD_SIZE_GET, &size) < 0) { - _dbus_verbose("KDBUS_CMD_MEMFD_SIZE_GET failed: %m\n"); - break; - } + memcpy(data, buf, size); + data += size; + ret_size += size; - _dbus_verbose(" +%s (%llu bytes) fd=%i size=%llu filesize=%llu '%s'\n", - enum_MSG(item->type), item->size, item->memfd.fd, - (unsigned long long)item->memfd.size, (unsigned long long)size, buf); - break; + munmap(buf, size); + + _dbus_verbose(" +%s (%llu bytes) off=%llu size=%llu\n", + enum_MSG(item->type), item->size, + (unsigned long long)item->vec.offset, + (unsigned long long)item->vec.size); + break; } + case KDBUS_MSG_FDS: + { + int i; + + *n_fds = (item->size - KDBUS_PART_HEADER_SIZE) / sizeof(int); + memcpy(fds, item->fds, *n_fds * sizeof(int)); + for (i = 0; i < *n_fds; i++) + _dbus_fd_set_close_on_exec(fds[i]); + break; + } + +#if KDBUS_MSG_DECODE_DEBUG == 1 case KDBUS_MSG_SRC_CREDS: _dbus_verbose(" +%s (%llu bytes) uid=%lld, gid=%lld, pid=%lld, tid=%lld, starttime=%lld\n", enum_MSG(item->type), item->size, @@ -468,7 +989,7 @@ int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, void* mmap_ptr) case KDBUS_MSG_SRC_CMDLINE: case KDBUS_MSG_SRC_NAMES: { - size_t size = item->size - KDBUS_PART_HEADER_SIZE; + __u64 size = item->size - KDBUS_PART_HEADER_SIZE; const char *str = item->str; int count = 0; @@ -528,11 +1049,35 @@ int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, void* mmap_ptr) (unsigned long long)item->timestamp.realtime_ns, (unsigned long long)item->timestamp.monotonic_ns); break; +#endif - case KDBUS_MSG_REPLY_TIMEOUT: //todo translate to kdbus message + case KDBUS_MSG_REPLY_TIMEOUT: _dbus_verbose(" +%s (%llu bytes) cookie=%llu\n", enum_MSG(item->type), item->size, msg->cookie_reply); - break; + + message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NO_REPLY, NULL); + if(message == NULL) + { + ret_size = -1; + goto out; + } + + ret_size = put_message_into_data(message, data); + break; + + case KDBUS_MSG_REPLY_DEAD: + _dbus_verbose(" +%s (%llu bytes) cookie=%llu\n", + enum_MSG(item->type), item->size, msg->cookie_reply); + + message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NAME_HAS_NO_OWNER, NULL); + if(message == NULL) + { + ret_size = -1; + goto out; + } + + ret_size = put_message_into_data(message, data); + break; case KDBUS_MSG_NAME_ADD: _dbus_verbose(" +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n", @@ -540,57 +1085,23 @@ int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, void* mmap_ptr) item->name_change.name, item->name_change.old_id, item->name_change.new_id, item->name_change.flags); - pStringMallocked = malloc (sizeof(item->name_change.new_id)*2.5 + 4); - if(pStringMallocked) - { - strcpy(pStringMallocked,":1."); - sprintf(&pStringMallocked[3],"%llu",item->name_change.new_id); - _dbus_verbose ("Name added for id: %s\n", pStringMallocked); //todo to be removed - } - else - return -1; - - message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal - dbus, // interface name of the signal - "NameOwnerChanged"); // name of the signal + message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged"); if(message == NULL) { ret_size = -1; goto out; } + sprintf(dbus_name,":1.%llu",item->name_change.new_id); pString = item->name_change.name; _dbus_verbose ("Name added: %s\n", pString); dbus_message_iter_init_append(message, &args); - if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING,&pString)) - { - ret_size = -1; - goto out; - } - if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &emptyString)) - { - ret_size = -1; - goto out; - } - if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pStringMallocked)) - { - ret_size = -1; - goto out; - } - - dbus_message_set_sender(message, dbus); - dbus_message_set_serial(message, 1); + ITER_APPEND_STR(pString) + ITER_APPEND_STR(emptyString) + ITER_APPEND_STR(pDBusName) + dbus_message_set_sender(message, DBUS_SERVICE_DBUS); - dbus_message_lock (message); - _dbus_message_get_network_data (message, &header, &body); - size = _dbus_string_get_length(header); - memcpy(data, _dbus_string_get_const_data(header), size); - data += size; - ret_size += size; - size = _dbus_string_get_length(body); - memcpy(data, _dbus_string_get_const_data(body), size); - data += size; - ret_size += size; + ret_size = put_message_into_data(message, data); break; case KDBUS_MSG_NAME_REMOVE: @@ -599,74 +1110,23 @@ int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, void* mmap_ptr) item->name_change.name, item->name_change.old_id, item->name_change.new_id, item->name_change.flags); - pStringMallocked = malloc (sizeof(item->name_change.old_id)*2.5 + 4); - if(pStringMallocked) - { - strcpy(pStringMallocked,":1."); - sprintf(&pStringMallocked[3],"%llu",item->name_change.old_id); - _dbus_verbose ("Name removed for id: %s\n", pStringMallocked); //todo to be removed - } - else - return -1; - - message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal - dbus, // interface name of the signal - "NameOwnerChanged"); // name of the signal + message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged"); // name of the signal if(message == NULL) { ret_size = -1; goto out; } + sprintf(dbus_name,":1.%llu",item->name_change.old_id); pString = item->name_change.name; _dbus_verbose ("Name removed: %s\n", pString); dbus_message_iter_init_append(message, &args); - if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING,&pString)) - { - ret_size = -1; - goto out; - } - if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pStringMallocked)) - { - ret_size = -1; - goto out; - } - if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &emptyString)) - { - ret_size = -1; - goto out; - } - - dbus_message_set_sender(message, dbus); - dbus_message_set_serial(message, 1); - - dbus_message_lock (message); - _dbus_message_get_network_data (message, &header, &body); - size = _dbus_string_get_length(header); - memcpy(data, _dbus_string_get_const_data(header), size); - data += size; - ret_size += size; - size = _dbus_string_get_length(body); - memcpy(data, _dbus_string_get_const_data(body), size); - data += size; - ret_size += size; - - /* fprintf (stderr, "\nheader: %llu\n", _dbus_string_get_length(header)); - for(i=0; i < _dbus_string_get_length(header); i++) - { - fprintf (stderr, "%02x", (int)_dbus_string_get_byte(header,i)); - } - fprintf (stderr, "\nbody: %llu\n", _dbus_string_get_length(body)); - for(i=0; i < _dbus_string_get_length(body); i++) - { - fprintf (stderr, "%02x", (int)_dbus_string_get_byte(body,i)); - } - fprintf (stderr, "\ndata: %llu\n", retsize); - for(i=0; i < _dbus_string_get_length(body); i++) - { - fprintf (stderr, "%02x", (int)_dbus_string_get_byte(body,i)); - }*/ + ITER_APPEND_STR(pString) + ITER_APPEND_STR(pDBusName) + ITER_APPEND_STR(emptyString) + dbus_message_set_sender(message, DBUS_SERVICE_DBUS); + ret_size = put_message_into_data(message, data); break; case KDBUS_MSG_NAME_CHANGE: @@ -675,59 +1135,25 @@ int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, void* mmap_ptr) item->name_change.name, item->name_change.old_id, item->name_change.new_id, item->name_change.flags); - pStringMallocked = malloc (sizeof(item->name_change.new_id)*2.5 + 4); - if(pStringMallocked) - { - strcpy(pStringMallocked,":1."); - sprintf(&pStringMallocked[3],"%llu",item->name_change.old_id); - _dbus_verbose ("Old id: %s\n", pStringMallocked); //todo to be removed - } - else - return -1; - - message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal - dbus, // interface name of the signal - "NameOwnerChanged"); // name of the signal + message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged"); if(message == NULL) { ret_size = -1; goto out; } + sprintf(dbus_name,":1.%llu",item->name_change.old_id); pString = item->name_change.name; _dbus_verbose ("Name changed: %s\n", pString); dbus_message_iter_init_append(message, &args); - if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING,&pString)) - { - ret_size = -1; - goto out; - } - if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pStringMallocked)) - { - ret_size = -1; - goto out; - } - sprintf(&pStringMallocked[3],"%llu",item->name_change.new_id); - _dbus_verbose ("New id: %s\n", pStringMallocked); //todo to be removed - if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pStringMallocked)) - { - ret_size = -1; - goto out; - } - - dbus_message_set_sender(message, dbus); - dbus_message_set_serial(message, 1); - - dbus_message_lock (message); - _dbus_message_get_network_data (message, &header, &body); - size = _dbus_string_get_length(header); - memcpy(data, _dbus_string_get_const_data(header), size); - data += size; - ret_size += size; - size = _dbus_string_get_length(body); - memcpy(data, _dbus_string_get_const_data(body), size); - data += size; - ret_size += size; + ITER_APPEND_STR(pString) + ITER_APPEND_STR(pDBusName) + sprintf(&dbus_name[3],"%llu",item->name_change.new_id); + _dbus_verbose ("New id: %s\n", pDBusName); + ITER_APPEND_STR(pDBusName) + dbus_message_set_sender(message, DBUS_SERVICE_DBUS); + + ret_size = put_message_into_data(message, data); break; case KDBUS_MSG_ID_ADD: @@ -736,55 +1162,21 @@ int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, void* mmap_ptr) (unsigned long long) item->id_change.id, (unsigned long long) item->id_change.flags); - pStringMallocked = malloc (sizeof(item->id_change.id)*2.5 + 4); - if(pStringMallocked) - { - strcpy(pStringMallocked,":1."); - sprintf(&pStringMallocked[3],"%llu",item->id_change.id); - _dbus_verbose ("Id added: %s\n", pStringMallocked); //todo to be removed - } - else - return -1; - - message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal - dbus, // interface name of the signal - "NameOwnerChanged"); // name of the signal + message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged"); if(message == NULL) { ret_size = -1; - goto out; - } - - dbus_message_iter_init_append(message, &args); - if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pStringMallocked)) - { - ret_size = -1; - goto out; - } - if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &emptyString)) - { - ret_size = -1; - goto out; - } - if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pStringMallocked)) - { - ret_size = -1; - goto out; + goto out; } - dbus_message_set_sender(message, dbus); - dbus_message_set_serial(message, 1); + sprintf(dbus_name,":1.%llu",item->id_change.id); + dbus_message_iter_init_append(message, &args); + ITER_APPEND_STR(pDBusName) + ITER_APPEND_STR(emptyString) + ITER_APPEND_STR(pDBusName) + dbus_message_set_sender(message, DBUS_SERVICE_DBUS); - dbus_message_lock (message); - _dbus_message_get_network_data (message, &header, &body); - size = _dbus_string_get_length(header); - memcpy(data, _dbus_string_get_const_data(header), size); - data += size; - ret_size += size; - size = _dbus_string_get_length(body); - memcpy(data, _dbus_string_get_const_data(body), size); - data += size; - ret_size += size; + ret_size = put_message_into_data(message, data); break; case KDBUS_MSG_ID_REMOVE: @@ -793,86 +1185,59 @@ int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, void* mmap_ptr) (unsigned long long) item->id_change.id, (unsigned long long) item->id_change.flags); - pStringMallocked = malloc (sizeof(item->id_change.id)*2.5 + 4); - if(pStringMallocked) - { - strcpy(pStringMallocked,":1."); - sprintf(&pStringMallocked[3],"%llu",item->id_change.id); - _dbus_verbose ("Id removed: %s\n", pStringMallocked); //todo to be removed - } - else - return -1; - - message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal - dbus, // interface name of the signal - "NameOwnerChanged"); // name of the signal + message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged"); if(message == NULL) { ret_size = -1; goto out; } + sprintf(dbus_name,":1.%llu",item->id_change.id); dbus_message_iter_init_append(message, &args); - if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pStringMallocked)) - { - ret_size = -1; - goto out; - } - if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pStringMallocked)) - { - ret_size = -1; - goto out; - } - if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &emptyString)) - { - ret_size = -1; - goto out; - } + ITER_APPEND_STR(pDBusName) + ITER_APPEND_STR(pDBusName) + ITER_APPEND_STR(emptyString) + dbus_message_set_sender(message, DBUS_SERVICE_DBUS); - dbus_message_set_sender(message, dbus); - dbus_message_set_serial(message, 1); - - dbus_message_lock (message); - _dbus_message_get_network_data (message, &header, &body); - size = _dbus_string_get_length(header); - memcpy(data, _dbus_string_get_const_data(header), size); - data += size; - ret_size += size; - size = _dbus_string_get_length(body); - memcpy(data, _dbus_string_get_const_data(body), size); - data += size; - ret_size += size; + ret_size = put_message_into_data(message, data); break; - +#if KDBUS_MSG_DECODE_DEBUG == 1 default: _dbus_verbose(" +%s (%llu bytes)\n", enum_MSG(item->type), item->size); - break; + break; +#endif } } +#if KDBUS_MSG_DECODE_DEBUG == 1 + if ((char *)item - ((char *)msg + msg->size) >= 8) _dbus_verbose("invalid padding at end of message\n"); +#endif out: if(message) dbus_message_unref(message); - if(pStringMallocked) - free((void*)pStringMallocked); return ret_size; } -int kdbus_read_message(DBusTransportSocket *socket_transport, DBusString *buffer) +/** + * Reads message from kdbus and puts it into dbus buffer and fds + * + * @param transport transport + * @param buffer place to copy received message to + * @param fds place to store file descriptors sent in the message + * @param n_fds place to store number of file descriptors + * @return size of received message on success, -1 on error + */ +static int kdbus_read_message(DBusTransportSocket *socket_transport, DBusString *buffer, int* fds, int* n_fds) { int ret_size; - uint64_t offset; + uint64_t __attribute__ ((__aligned__(8))) offset; struct kdbus_msg *msg; - int ret; - int start; char *data; + int start; -// int i; - - _dbus_assert (socket_transport->max_bytes_read_per_iteration >= 0); start = _dbus_string_get_length (buffer); if (!_dbus_string_lengthen (buffer, socket_transport->max_bytes_read_per_iteration)) { @@ -882,34 +1247,34 @@ int kdbus_read_message(DBusTransportSocket *socket_transport, DBusString *buffer data = _dbus_string_get_data_len (buffer, start, socket_transport->max_bytes_read_per_iteration); again: - ret = ioctl(socket_transport->fd, KDBUS_CMD_MSG_RECV, &offset); - if (ret < 0) + if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RECV, &offset) < 0) { if(errno == EINTR) goto again; - _dbus_verbose("kdbus error receiving message: %d (%m)\n", ret); + _dbus_verbose("kdbus error receiving message: %d (%m)\n", errno); _dbus_string_set_length (buffer, start); return -1; } msg = (struct kdbus_msg *)((char*)socket_transport->kdbus_mmap_ptr + offset); - ret_size = kdbus_decode_msg(msg, data, socket_transport->kdbus_mmap_ptr); -/* fprintf (stderr, "\nmessage! start: %u, ret_size: %u\n", start, ret_size); - for(i=0; i < ret_size; i++) - { - fprintf (stderr, "%02x", (int)data[i]); - } - fprintf (stderr, "\nret size: %u, i: %u\n", ret_size, i);*/ - _dbus_string_set_length (buffer, start + ret_size); + ret_size = kdbus_decode_msg(msg, data, socket_transport, fds, n_fds); + + if(ret_size == -1) /* error */ + { + _dbus_string_set_length (buffer, start); + return -1; + } + else + _dbus_string_set_length (buffer, start + ret_size); + again2: - ret = ioctl(socket_transport->fd, KDBUS_CMD_MSG_RELEASE, &offset); - if (ret < 0) + if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RELEASE, &offset) < 0) { if(errno == EINTR) goto again2; - _dbus_verbose("kdbus error freeing message: %d (%m)\n", ret); + _dbus_verbose("kdbus error freeing message: %d (%m)\n", errno); return -1; } @@ -983,8 +1348,11 @@ check_write_watch (DBusTransport *transport) _dbus_transport_ref (transport); +#ifdef DBUS_AUTHENTICATION if (_dbus_transport_get_is_authenticated (transport)) +#endif needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection); +#ifdef DBUS_AUTHENTICATION else { if (transport->send_credentials_pending) @@ -1006,7 +1374,7 @@ check_write_watch (DBusTransport *transport) needed = FALSE; } } - +#endif _dbus_verbose ("check_write_watch(): needed = %d on connection %p watch %p fd = %d outgoing messages exist %d\n", needed, transport->connection, socket_transport->write_watch, socket_transport->fd, @@ -1038,10 +1406,13 @@ check_read_watch (DBusTransport *transport) _dbus_transport_ref (transport); +#ifdef DBUS_AUTHENTICATION if (_dbus_transport_get_is_authenticated (transport)) +#endif need_read_watch = (_dbus_counter_get_size_value (transport->live_messages) < transport->max_live_messages_size) && (_dbus_counter_get_unix_fd_value (transport->live_messages) < transport->max_live_messages_unix_fds); +#ifdef DBUS_AUTHENTICATION else { if (transport->receive_credentials_pending) @@ -1070,6 +1441,7 @@ check_read_watch (DBusTransport *transport) need_read_watch = FALSE; } } +#endif _dbus_verbose (" setting read watch enabled = %d\n", need_read_watch); _dbus_connection_toggle_watch_unlocked (transport->connection, @@ -1087,6 +1459,7 @@ do_io_error (DBusTransport *transport) _dbus_transport_unref (transport); } +#ifdef DBUS_AUTHENTICATION /* return value is whether we successfully read any new data. */ static dbus_bool_t read_data_into_auth (DBusTransport *transport, @@ -1100,8 +1473,7 @@ read_data_into_auth (DBusTransport *transport, _dbus_auth_get_buffer (transport->auth, &buffer); - bytes_read = _dbus_read_socket (socket_transport->fd, - buffer, socket_transport->max_bytes_read_per_iteration); + bytes_read = kdbus_read_message(socket_transport, buffer); _dbus_auth_return_buffer (transport->auth, buffer, bytes_read > 0 ? bytes_read : 0); @@ -1109,7 +1481,6 @@ read_data_into_auth (DBusTransport *transport, if (bytes_read > 0) { _dbus_verbose (" read %d bytes in auth phase\n", bytes_read); - return TRUE; } else if (bytes_read < 0) @@ -1272,7 +1643,6 @@ do_authentication (DBusTransport *transport, { if (!exchange_credentials (transport, do_reading, do_writing)) { - /* OOM */ oom = TRUE; goto out; } @@ -1336,21 +1706,23 @@ do_authentication (DBusTransport *transport, else return TRUE; } +#endif /* returns false on oom */ static dbus_bool_t do_writing (DBusTransport *transport) { - int total; DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport; dbus_bool_t oom; +#ifdef DBUS_AUTHENTICATION /* No messages without authentication! */ if (!_dbus_transport_get_is_authenticated (transport)) { _dbus_verbose ("Not authenticated, not writing anything\n"); return TRUE; } +#endif if (transport->disconnected) { @@ -1365,7 +1737,6 @@ do_writing (DBusTransport *transport) #endif oom = FALSE; - total = 0; while (!transport->disconnected && _dbus_connection_has_messages_to_send_unlocked (transport->connection)) { @@ -1374,25 +1745,28 @@ do_writing (DBusTransport *transport) const DBusString *header; const DBusString *body; int total_bytes_to_write; - - - if (total > socket_transport->max_bytes_written_per_iteration) - { - _dbus_verbose ("%d bytes exceeds %d bytes written per iteration, returning\n", - total, socket_transport->max_bytes_written_per_iteration); - goto out; - } + const char* pDestination; message = _dbus_connection_get_message_to_send (transport->connection); _dbus_assert (message != NULL); dbus_message_lock (message); _dbus_message_get_network_data (message, &header, &body); + total_bytes_to_write = _dbus_string_get_length(header) + _dbus_string_get_length(body); + pDestination = dbus_message_get_destination(message); + if(pDestination) + { + if(!strcmp(pDestination, "org.freedesktop.DBus")) + { + if(emulateOrgFreedesktopDBus(transport, message)) + bytes_written = total_bytes_to_write; + else + bytes_written = -1; + goto written; + } + } if (_dbus_auth_needs_encoding (transport->auth)) { - // Does fd passing even make sense with encoded data? - _dbus_assert(!DBUS_TRANSPORT_CAN_SEND_UNIX_FD(transport)); - if (_dbus_string_get_length (&socket_transport->encoded_outgoing) == 0) { if (!_dbus_auth_encode_data (transport->auth, @@ -1412,14 +1786,20 @@ do_writing (DBusTransport *transport) } total_bytes_to_write = _dbus_string_get_length (&socket_transport->encoded_outgoing); - bytes_written = kdbus_write_msg_encoded(message, socket_transport); + if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration) + return -E2BIG; + + bytes_written = kdbus_write_msg(socket_transport, message, TRUE); } else { - total_bytes_to_write = _dbus_string_get_length(header) + _dbus_string_get_length(body); - bytes_written = kdbus_write_msg(transport->connection, message, socket_transport->fd); + if(total_bytes_to_write > socket_transport->max_bytes_written_per_iteration) + return -E2BIG; + + bytes_written = kdbus_write_msg(socket_transport, message, FALSE); } +written: if (bytes_written < 0) { /* EINTR already handled for us */ @@ -1432,8 +1812,7 @@ do_writing (DBusTransport *transport) goto out; else { - _dbus_verbose ("Error writing to remote app: %s\n", - _dbus_strerror_from_errno ()); + _dbus_verbose ("Error writing to remote app: %s\n", _dbus_strerror_from_errno ()); do_io_error (transport); goto out; } @@ -1443,7 +1822,6 @@ do_writing (DBusTransport *transport) _dbus_verbose (" wrote %d bytes of %d\n", bytes_written, total_bytes_to_write); - total += bytes_written; socket_transport->message_bytes_written += bytes_written; _dbus_assert (socket_transport->message_bytes_written <= @@ -1464,8 +1842,7 @@ do_writing (DBusTransport *transport) out: if (oom) return FALSE; - else - return TRUE; + return TRUE; } /* returns false on out-of-memory */ @@ -1475,31 +1852,22 @@ do_reading (DBusTransport *transport) DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport; DBusString *buffer; int bytes_read; - int total; - dbus_bool_t oom; + dbus_bool_t oom = FALSE; + int *fds, n_fds; _dbus_verbose ("fd = %d\n",socket_transport->fd); +#ifdef DBUS_AUTHENTICATION /* No messages without authentication! */ if (!_dbus_transport_get_is_authenticated (transport)) return TRUE; - - oom = FALSE; - - total = 0; +#endif again: /* See if we've exceeded max messages and need to disable reading */ check_read_watch (transport); - if (total > socket_transport->max_bytes_read_per_iteration) - { - _dbus_verbose ("%d bytes exceeds %d bytes read per iteration, returning\n", - total, socket_transport->max_bytes_read_per_iteration); - goto out; - } - _dbus_assert (socket_transport->read_watch != NULL || transport->disconnected); @@ -1509,64 +1877,48 @@ do_reading (DBusTransport *transport) if (!dbus_watch_get_enabled (socket_transport->read_watch)) return TRUE; - if (_dbus_auth_needs_decoding (transport->auth)) - { - /* Does fd passing even make sense with encoded data? */ - /* _dbus_assert(!DBUS_TRANSPORT_CAN_SEND_UNIX_FD(transport)); - - if (_dbus_string_get_length (&socket_transport->encoded_incoming) > 0) - bytes_read = _dbus_string_get_length (&socket_transport->encoded_incoming); - else - bytes_read = _dbus_read_socket (socket_transport->fd, - &socket_transport->encoded_incoming, - socket_transport->max_bytes_read_per_iteration);*/ + if (!_dbus_message_loader_get_unix_fds(transport->loader, &fds, &n_fds)) + { + _dbus_verbose ("Out of memory reading file descriptors\n"); + oom = TRUE; + goto out; + } + _dbus_message_loader_get_buffer (transport->loader, &buffer); - bytes_read = kdbus_read_message(socket_transport, &socket_transport->encoded_incoming); + if (_dbus_auth_needs_decoding (transport->auth)) + { + bytes_read = kdbus_read_message(socket_transport, &socket_transport->encoded_incoming, fds, &n_fds); - _dbus_assert (_dbus_string_get_length (&socket_transport->encoded_incoming) == - bytes_read); + _dbus_assert (_dbus_string_get_length (&socket_transport->encoded_incoming) == bytes_read); if (bytes_read > 0) - { - int orig_len; - - _dbus_message_loader_get_buffer (transport->loader, - &buffer); - - orig_len = _dbus_string_get_length (buffer); - + { if (!_dbus_auth_decode_data (transport->auth, &socket_transport->encoded_incoming, buffer)) - { + { _dbus_verbose ("Out of memory decoding incoming data\n"); _dbus_message_loader_return_buffer (transport->loader, buffer, - _dbus_string_get_length (buffer) - orig_len); - + _dbus_string_get_length (buffer)); oom = TRUE; goto out; - } - - _dbus_message_loader_return_buffer (transport->loader, - buffer, - _dbus_string_get_length (buffer) - orig_len); + } _dbus_string_set_length (&socket_transport->encoded_incoming, 0); _dbus_string_compact (&socket_transport->encoded_incoming, 2048); - } - } + } + } else - { - _dbus_message_loader_get_buffer (transport->loader, - &buffer); + bytes_read = kdbus_read_message(socket_transport, buffer, fds, &n_fds); - bytes_read = kdbus_read_message(socket_transport, buffer); + if (bytes_read >= 0 && n_fds > 0) + _dbus_verbose("Read %i unix fds\n", n_fds); - _dbus_message_loader_return_buffer (transport->loader, - buffer, - bytes_read < 0 ? 0 : bytes_read); - } + _dbus_message_loader_return_buffer (transport->loader, + buffer, + bytes_read < 0 ? 0 : bytes_read); + _dbus_message_loader_return_unix_fds(transport->loader, fds, bytes_read < 0 ? 0 : n_fds); if (bytes_read < 0) { @@ -1598,8 +1950,6 @@ do_reading (DBusTransport *transport) { _dbus_verbose (" read %d bytes\n", bytes_read); - total += bytes_read; - if (!_dbus_transport_queue_messages (transport)) { oom = TRUE; @@ -1617,8 +1967,7 @@ do_reading (DBusTransport *transport) out: if (oom) return FALSE; - else - return TRUE; + return TRUE; } static dbus_bool_t @@ -1626,18 +1975,17 @@ unix_error_with_read_to_come (DBusTransport *itransport, DBusWatch *watch, unsigned int flags) { - DBusTransportSocket *transport = (DBusTransportSocket *) itransport; + DBusTransportSocket *transport = (DBusTransportSocket *) itransport; - if (!(flags & DBUS_WATCH_HANGUP || flags & DBUS_WATCH_ERROR)) - return FALSE; + if (!((flags & DBUS_WATCH_HANGUP) || (flags & DBUS_WATCH_ERROR))) + return FALSE; /* If we have a read watch enabled ... we -might have data incoming ... => handle the HANGUP there */ - if (watch != transport->read_watch && - _dbus_watch_get_enabled (transport->read_watch)) - return FALSE; + if (watch != transport->read_watch && _dbus_watch_get_enabled (transport->read_watch)) + return FALSE; - return TRUE; + return TRUE; } static dbus_bool_t @@ -1665,11 +2013,14 @@ socket_handle_watch (DBusTransport *transport, if (watch == socket_transport->read_watch && (flags & DBUS_WATCH_READABLE)) { +#ifdef DBUS_AUTHENTICATION dbus_bool_t auth_finished; +#endif #if 1 _dbus_verbose ("handling read watch %p flags = %x\n", watch, flags); #endif +#ifdef DBUS_AUTHENTICATION if (!do_authentication (transport, TRUE, FALSE, &auth_finished)) return FALSE; @@ -1681,16 +2032,19 @@ socket_handle_watch (DBusTransport *transport, */ if (!auth_finished) { +#endif if (!do_reading (transport)) { _dbus_verbose ("no memory to read\n"); return FALSE; } +#ifdef DBUS_AUTHENTICATION } else { _dbus_verbose ("Not reading anything since we just completed the authentication\n"); } +#endif } else if (watch == socket_transport->write_watch && (flags & DBUS_WATCH_WRITABLE)) @@ -1699,9 +2053,10 @@ socket_handle_watch (DBusTransport *transport, _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n", _dbus_connection_has_messages_to_send_unlocked (transport->connection)); #endif +#ifdef DBUS_AUTHENTICATION if (!do_authentication (transport, FALSE, TRUE, NULL)) return FALSE; - +#endif if (!do_writing (transport)) { _dbus_verbose ("no memory to write\n"); @@ -1804,11 +2159,11 @@ kdbus_do_iteration (DBusTransport *transport, * we don't want to read any messages yet if not given DO_READING. */ - poll_fd.fd = socket_transport->fd; - poll_fd.events = 0; + poll_fd.fd = socket_transport->fd; + poll_fd.events = 0; - if (_dbus_transport_get_is_authenticated (transport)) - { + if (_dbus_transport_get_is_authenticated (transport)) + { /* This is kind of a hack; if we have stuff to write, then try * to avoid the poll. This is probably about a 5% speedup on an * echo client/server. @@ -1823,44 +2178,42 @@ kdbus_do_iteration (DBusTransport *transport, !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) && !transport->disconnected && _dbus_connection_has_messages_to_send_unlocked (transport->connection)) - { - do_writing (transport); + { + do_writing (transport); - if (transport->disconnected || + if (transport->disconnected || !_dbus_connection_has_messages_to_send_unlocked (transport->connection)) goto out; - } + } /* If we get here, we decided to do the poll() after all */ _dbus_assert (socket_transport->read_watch); if (flags & DBUS_ITERATION_DO_READING) - poll_fd.events |= _DBUS_POLLIN; + poll_fd.events |= _DBUS_POLLIN; _dbus_assert (socket_transport->write_watch); if (flags & DBUS_ITERATION_DO_WRITING) - poll_fd.events |= _DBUS_POLLOUT; - } - else - { + poll_fd.events |= _DBUS_POLLOUT; + } + else + { DBusAuthState auth_state; auth_state = _dbus_auth_do_work (transport->auth); - if (transport->receive_credentials_pending || - auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT) - poll_fd.events |= _DBUS_POLLIN; + if (transport->receive_credentials_pending || auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT) + poll_fd.events |= _DBUS_POLLIN; - if (transport->send_credentials_pending || - auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND) - poll_fd.events |= _DBUS_POLLOUT; - } + if (transport->send_credentials_pending || auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND) + poll_fd.events |= _DBUS_POLLOUT; + } - if (poll_fd.events) - { + if (poll_fd.events) + { if (flags & DBUS_ITERATION_BLOCK) - poll_timeout = timeout_milliseconds; + poll_timeout = timeout_milliseconds; else - poll_timeout = 0; + poll_timeout = 0; /* For blocking selects we drop the connection lock here * to avoid blocking out connection access during a potentially @@ -1868,70 +2221,63 @@ kdbus_do_iteration (DBusTransport *transport, * by the io_path_cond condvar, so we won't reenter this. */ if (flags & DBUS_ITERATION_BLOCK) - { - _dbus_verbose ("unlock pre poll\n"); - _dbus_connection_unlock (transport->connection); - } - _dbus_verbose ("poll_fd.events: %x, timeout: %d\n", poll_fd.events, poll_timeout); + { + _dbus_verbose ("unlock pre poll\n"); + _dbus_connection_unlock (transport->connection); + } + again: poll_res = _dbus_poll (&poll_fd, 1, poll_timeout); if (poll_res < 0 && _dbus_get_is_errno_eintr ()) { - _dbus_verbose ("Error from _dbus_poll(): %s\n", - _dbus_strerror_from_errno ()); - goto again; + _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ()); + goto again; } - _dbus_verbose ("poll_fd.revents: %x\n", poll_fd.revents); - - /* poll_res = poll_timeout; // todo temporary walkaround of above problem - poll_res = 1; // todo temporary walkaround of above problem - poll_fd.revents = poll_fd.events; // todo temporary walkaround of above problem*/ if (flags & DBUS_ITERATION_BLOCK) - { - _dbus_verbose ("lock post poll\n"); - _dbus_connection_lock (transport->connection); - } + { + _dbus_verbose ("lock post poll\n"); + _dbus_connection_lock (transport->connection); + } if (poll_res >= 0) - { - if (poll_res == 0) + { + if (poll_res == 0) poll_fd.revents = 0; /* some concern that posix does not guarantee this; * valgrind flags it as an error. though it probably * is guaranteed on linux at least. */ - if (poll_fd.revents & _DBUS_POLLERR) + if (poll_fd.revents & _DBUS_POLLERR) do_io_error (transport); - else - { - dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0; - dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0; - dbus_bool_t authentication_completed; + else + { + dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0; + dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0; +#ifdef DBUS_AUTHENTICATION + dbus_bool_t authentication_completed; +#endif - _dbus_verbose ("in iteration, need_read=%d need_write=%d\n", + _dbus_verbose ("in iteration, need_read=%d need_write=%d\n", need_read, need_write); +#ifdef DBUS_AUTHENTICATION do_authentication (transport, need_read, need_write, &authentication_completed); /* See comment in socket_handle_watch. */ if (authentication_completed) goto out; - - if (need_read && (flags & DBUS_ITERATION_DO_READING)) - do_reading (transport); - if (need_write && (flags & DBUS_ITERATION_DO_WRITING)) - do_writing (transport); - } - } +#endif + if (need_read && (flags & DBUS_ITERATION_DO_READING)) + do_reading (transport); + if (need_write && (flags & DBUS_ITERATION_DO_WRITING)) + do_writing (transport); + } + } else - { - _dbus_verbose ("Error from _dbus_poll(): %s\n", - _dbus_strerror_from_errno ()); - } - } - + _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ()); + } out: /* We need to install the write watch only if we did not @@ -1944,9 +2290,9 @@ kdbus_do_iteration (DBusTransport *transport, * relies on the fact that running an iteration will notice that * messages are pending. */ - check_write_watch (transport); + check_write_watch (transport); - _dbus_verbose (" ... leaving do_iteration()\n"); + _dbus_verbose (" ... leaving do_iteration()\n"); } static void @@ -1968,17 +2314,14 @@ static const DBusTransportVTable kdbus_vtable = { /** * Creates a new transport for the given kdbus file descriptor. The file - * descriptor must be nonblocking (use _dbus_set_fd_nonblocking() to - * make it so). + * descriptor must be nonblocking. * * @param fd the file descriptor. - * @param server_guid non-#NULL if this transport is on the server side of a connection * @param address the transport's address * @returns the new transport, or #NULL if no memory. */ -DBusTransport* +static DBusTransport* _dbus_transport_new_for_socket_kdbus (int fd, - const DBusString *server_guid, const DBusString *address) { DBusTransportSocket *socket_transport; @@ -2009,22 +2352,25 @@ _dbus_transport_new_for_socket_kdbus (int fd, if (!_dbus_transport_init_base (&socket_transport->base, &kdbus_vtable, - server_guid, address)) + NULL, address)) goto failed_4; +#ifdef DBUS_AUTHENTICATION #ifdef HAVE_UNIX_FD_PASSING _dbus_auth_set_unix_fd_possible(socket_transport->base.auth, _dbus_socket_can_pass_unix_fd(fd)); #endif +#endif socket_transport->fd = fd; socket_transport->message_bytes_written = 0; /* These values should probably be tunable or something. */ - socket_transport->max_bytes_read_per_iteration = POOL_SIZE; - socket_transport->max_bytes_written_per_iteration = 2048; + socket_transport->max_bytes_read_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH; + socket_transport->max_bytes_written_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH; socket_transport->kdbus_mmap_ptr = NULL; - + socket_transport->memfd = -1; + return (DBusTransport*) socket_transport; failed_4: @@ -2044,44 +2390,39 @@ _dbus_transport_new_for_socket_kdbus (int fd, /** - * Creates a connection to the kdbus bus - * + * Opens a connection to the kdbus bus + * * This will set FD_CLOEXEC for the socket returned. * * @param path the path to UNIX domain socket * @param error return location for error code * @returns connection file descriptor or -1 on error */ -int _dbus_connect_kdbus (const char *path, DBusError *error) +static int _dbus_connect_kdbus (const char *path, DBusError *error) { int fd; _DBUS_ASSERT_ERROR_IS_CLEAR (error); _dbus_verbose ("connecting to kdbus bus %s\n", path); - fd = open(path, O_RDWR|O_CLOEXEC|O_NONBLOCK); //[RP] | O_NONBLOCK added here, in dbus added separately in section commented out below + fd = open(path, O_RDWR|O_CLOEXEC|O_NONBLOCK); if (fd < 0) - { dbus_set_error(error, _dbus_error_from_errno (errno), "Failed to open file descriptor: %s", _dbus_strerror (errno)); - _DBUS_ASSERT_ERROR_IS_SET(error); - return -1; //[RP] not needed here if commented block below is removed - } - - /*if (!_dbus_set_fd_nonblocking (fd, error)) - { - _DBUS_ASSERT_ERROR_IS_SET (error); - _dbus_close (fd, NULL); - return -1; - }*/ return fd; } -dbus_bool_t kdbus_mmap(DBusTransport* transport) +/** + * maps memory pool for messages received by the kdbus transport + * + * @param transport transport + * @returns #TRUE on success, otherwise FALSE + */ +static dbus_bool_t kdbus_mmap(DBusTransport* transport) { DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport; - socket_transport->kdbus_mmap_ptr = mmap(NULL, POOL_SIZE, PROT_READ, MAP_SHARED, socket_transport->fd, 0); + socket_transport->kdbus_mmap_ptr = mmap(NULL, RECEIVE_POOL_SIZE, PROT_READ, MAP_SHARED, socket_transport->fd, 0); if (socket_transport->kdbus_mmap_ptr == MAP_FAILED) return FALSE; @@ -2092,11 +2433,11 @@ dbus_bool_t kdbus_mmap(DBusTransport* transport) * Creates a new transport for kdbus. * This creates a client-side of a transport. * - * @param path the path to the domain socket. + * @param path the path to the bus. * @param error address where an error can be returned. * @returns a new transport, or #NULL on failure. */ -DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error) +static DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error) { int fd; DBusTransport *transport; @@ -2127,7 +2468,7 @@ DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error _dbus_verbose ("Successfully connected to kdbus bus %s\n", path); - transport = _dbus_transport_new_for_socket_kdbus (fd, NULL, &address); + transport = _dbus_transport_new_for_socket_kdbus (fd, &address); if (transport == NULL) { dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); @@ -2147,7 +2488,7 @@ DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error /** - * Opens kdbus transport. + * Opens kdbus transport if method from address entry is kdbus * * @param entry the address entry to try opening * @param transport_p return location for the opened transport @@ -2193,7 +2534,7 @@ DBusTransportOpenResult _dbus_transport_open_kdbus(DBusAddressEntry *entry, } } -struct kdbus_policy *make_policy_name(const char *name) +static struct kdbus_policy *make_policy_name(const char *name) { struct kdbus_policy *p; __u64 size; @@ -2210,7 +2551,7 @@ struct kdbus_policy *make_policy_name(const char *name) return p; } -struct kdbus_policy *make_policy_access(__u64 type, __u64 bits, __u64 id) +static struct kdbus_policy *make_policy_access(__u64 type, __u64 bits, __u64 id) { struct kdbus_policy *p; __u64 size = sizeof(*p); @@ -2229,7 +2570,7 @@ struct kdbus_policy *make_policy_access(__u64 type, __u64 bits, __u64 id) return p; } -void append_policy(struct kdbus_cmd_policy *cmd_policy, struct kdbus_policy *policy, __u64 max_size) +static void append_policy(struct kdbus_cmd_policy *cmd_policy, struct kdbus_policy *policy, __u64 max_size) { struct kdbus_policy *dst = (struct kdbus_policy *) ((char *) cmd_policy + cmd_policy->size); @@ -2241,6 +2582,22 @@ void append_policy(struct kdbus_cmd_policy *cmd_policy, struct kdbus_policy *pol free(policy); } +/** + * Registers kdbus policy for given connection. + * + * Policy sets rights of the name (unique or well known) on the bus. Without policy it is + * not possible to send or receive messages. It must be set separately for unique id and + * well known name of the connection. It is set after registering on the bus, but before + * requesting for name. The policy is valid for the given name, not for the connection. + * + * Name of the policy equals name on the bus. + * + * @param name name of the policy = name of the connection + * @param connection the connection + * @param error place to store errors + * + * @returns #TRUE on success + */ dbus_bool_t bus_register_policy_kdbus(const char* name, DBusConnection *connection, DBusError *error) { struct kdbus_cmd_policy *cmd_policy; @@ -2254,13 +2611,13 @@ dbus_bool_t bus_register_policy_kdbus(const char* name, DBusConnection *connecti return FALSE; } - cmd_policy = (struct kdbus_cmd_policy *) alloca(size); + cmd_policy = alloca(size); memset(cmd_policy, 0, size); policy = (struct kdbus_policy *) cmd_policy->policies; cmd_policy->size = offsetof(struct kdbus_cmd_policy, policies); - policy = make_policy_name(name); //todo to be verified or changed when meaning will be known + policy = make_policy_name(name); append_policy(cmd_policy, policy, size); policy = make_policy_access(KDBUS_POLICY_ACCESS_USER, KDBUS_POLICY_OWN, getuid()); @@ -2282,22 +2639,31 @@ dbus_bool_t bus_register_policy_kdbus(const char* name, DBusConnection *connecti return TRUE; } +/** + * Kdbus part of dbus_bus_register. + * Shouldn't be used separately because it needs to be surrounded + * by other functions as it is done in dbus_bus_register. + * + * @param name place to store unique name given by bus + * @param connection the connection + * @param error place to store errors + * @returns #TRUE on success + */ dbus_bool_t bus_register_kdbus(char* name, DBusConnection *connection, DBusError *error) { - struct kdbus_cmd_hello hello; + struct kdbus_cmd_hello __attribute__ ((__aligned__(8))) hello; int fd; - memset(&hello, 0, sizeof(hello)); - hello.conn_flags = KDBUS_HELLO_ACCEPT_FD | + hello.conn_flags = KDBUS_HELLO_ACCEPT_FD/* | KDBUS_HELLO_ATTACH_COMM | KDBUS_HELLO_ATTACH_EXE | KDBUS_HELLO_ATTACH_CMDLINE | KDBUS_HELLO_ATTACH_CAPS | KDBUS_HELLO_ATTACH_CGROUP | KDBUS_HELLO_ATTACH_SECLABEL | - KDBUS_HELLO_ATTACH_AUDIT; + KDBUS_HELLO_ATTACH_AUDIT*/; hello.size = sizeof(struct kdbus_cmd_hello); - hello.pool_size = POOL_SIZE; + hello.pool_size = RECEIVE_POOL_SIZE; if(!dbus_connection_get_socket(connection, &fd)) { @@ -2310,8 +2676,9 @@ dbus_bool_t bus_register_kdbus(char* name, DBusConnection *connection, DBusError return FALSE; } - _dbus_verbose("-- Our peer ID is: %llu\n", (unsigned long long)hello.id); sprintf(name, "%llu", (unsigned long long)hello.id); + _dbus_verbose("-- Our peer ID is: %s\n", name); + ((DBusTransportSocket*)dbus_connection_get_transport(connection))->bloom_size = hello.bloom_size; if(!kdbus_mmap(dbus_connection_get_transport(connection))) { @@ -2322,7 +2689,23 @@ dbus_bool_t bus_register_kdbus(char* name, DBusConnection *connection, DBusError return TRUE; } -uint64_t bus_request_name_kdbus(DBusConnection *connection, const char *name, const uint64_t flags, DBusError *error) +/** + * kdbus version of dbus_bus_request_name. + * + * Asks the bus to assign the given name to this connection. + * + * Use same flags as original dbus version with one exception below. + * Result flag #DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER is currently + * never returned by kdbus, instead DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER + * is returned by kdbus. + * + * @param connection the connection + * @param name the name to request + * @param flags flags + * @param error location to store the error + * @returns a result code, -1 if error is set + */ +int bus_request_name_kdbus(DBusConnection *connection, const char *name, const uint64_t flags, DBusError *error) { struct kdbus_cmd_name *cmd_name; int fd; @@ -2347,7 +2730,7 @@ uint64_t bus_request_name_kdbus(DBusConnection *connection, const char *name, co if(!dbus_connection_get_socket(connection, &fd)) { dbus_set_error (error, "failed to get fd for name request", NULL); - return FALSE; + return -1; } _dbus_verbose("Request name - flags sent: 0x%llx !!!!!!!!!\n", cmd_name->conn_flags); @@ -2358,7 +2741,7 @@ uint64_t bus_request_name_kdbus(DBusConnection *connection, const char *name, co dbus_set_error(error,_dbus_error_from_errno (errno), "error acquiring name: %s", _dbus_strerror (errno)); if(errno == EEXIST) return DBUS_REQUEST_NAME_REPLY_EXISTS; - return FALSE; + return -1; } _dbus_verbose("Request name - received flag: 0x%llx !!!!!!!!!\n", cmd_name->conn_flags); @@ -2367,7 +2750,9 @@ uint64_t bus_request_name_kdbus(DBusConnection *connection, const char *name, co return DBUS_REQUEST_NAME_REPLY_IN_QUEUE; else return DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER; - //todo now 1 codes are never returned - DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER + /*todo now 1 code is never returned - DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER + * because kdbus never returns it now + */ } /** @@ -2380,34 +2765,225 @@ dbus_bool_t dbus_transport_is_kdbus(DBusConnection *connection) { const char* address = _dbus_connection_get_address(connection); - if(address == strstr(address, "kdbus:path=")) - return TRUE; - else - return FALSE; + if(address) + if(address == strstr(address, "kdbus:path=")) + return TRUE; + return FALSE; +} + +/** + * Seeks key in rule string, and duplicates value of the key into pValue. + * If value is "org.freedesktop.DBus" it is indicated by returning -1, because it + * needs to be handled in different manner. + * Value is duplicated from rule string to newly allocated memory pointe by pValue, + * so it must be freed after use. + * + * @param rule rule to look through + * @param key key to look for + * @param pValue pointer to value of the key found + * @return length of the value string, 0 means not found, -1 means "org.freedesktop.DBus" + */ +static int parse_match_key(const char *rule, const char* key, char** pValue) +{ + const char* pBegin; + const char* pValueEnd; + int value_length = 0; + + pBegin = strstr(rule, key); + if(pBegin) + { + pBegin += strlen(key); + pValueEnd = strchr(pBegin, '\''); + if(pValueEnd) + { + value_length = pValueEnd - pBegin; + *pValue = strndup(pBegin, value_length); + if(*pValue) + { + if(strcmp(*pValue, "org.freedesktop.DBus") == 0) + value_length = -1; + _dbus_verbose ("found for key: %s value:'%s'\n", key, *pValue); + } + } + } + return value_length; } +/** + * Adds a match rule to match broadcast messages going through the message bus. + * Do no affect messages addressed directly. + * + * The "rule" argument is the string form of a match rule. + * + * In kdbus function do not blocks. + * + * Upper function returns nothing because of blocking issues + * so there is no point to return true or false here. + * + * Only part of the dbus's matching capabilities is implemented in kdbus now, because of different mechanism. + * Current mapping: + * interface match key mapped to bloom + * sender match key mapped to src_name + * also handled org.freedesktop.dbus members: NameOwnerChanged, NameLost, NameAcquired + * + * @param connection connection to the message bus + * @param rule textual form of match rule + * @param error location to store any errors - may be NULL + */ void dbus_bus_add_match_kdbus (DBusConnection *connection, const char *rule, DBusError *error) { - struct kdbus_cmd_match cmd_match; + struct kdbus_cmd_match* pCmd_match; + struct kdbus_item *pItem; int fd; + __u64 src_id = KDBUS_MATCH_SRC_ID_ANY; + uint64_t size; + unsigned int kernel_item = 0; + int name_size; + char* pName = NULL; + char* pInterface = NULL; + __u64 bloom_size = ((DBusTransportSocket*)dbus_connection_get_transport(connection))->bloom_size; - memset(&cmd_match, 0, sizeof(cmd_match)); + dbus_connection_get_socket(connection, &fd); - if(!dbus_connection_get_socket(connection, &fd)) + /*parsing rule and calculating size of command*/ + size = sizeof(struct kdbus_cmd_match); + + if(strstr(rule, "member='NameOwnerChanged'")) { - dbus_set_error (error, "failed to get fd for add match", NULL); - return; + kernel_item = KDBUS_MATCH_NAME_CHANGE; + size += KDBUS_ITEM_SIZE(1); + } + else if(strstr(rule, "member='NameLost'")) + { + kernel_item = KDBUS_MATCH_NAME_REMOVE; + size += KDBUS_ITEM_SIZE(1); + } + else if(strstr(rule, "member='NameAcquired'")) + { + kernel_item = KDBUS_MATCH_NAME_ADD; + size += KDBUS_ITEM_SIZE(1); + } + + name_size = parse_match_key(rule, "interface='", &pInterface); + if((name_size == -1) && (kernel_item == 0)) //means org.freedesktop.DBus without specified member + { + kernel_item = ~0; + size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2; /* 3 above name related items plus 2 id related items*/ + } + else if(name_size > 0) /*actual size is not important for interface because bloom size is defined by bus*/ + size += KDBUS_PART_HEADER_SIZE + bloom_size; + + name_size = parse_match_key(rule, "sender='", &pName); + if((name_size == -1) && (kernel_item == 0)) //means org.freedesktop.DBus without specified name - same as interface few line above + { + kernel_item = ~0; + size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2; /* 3 above name related items plus 2 id related items*/ + } + else if(name_size > 0) + { + if(!strncmp(pName, ":1.", 3)) /*if name is unique name it must be converted to unique id*/ + { + src_id = strtoull(&pName[3], NULL, 10); + free(pName); + pName = NULL; + } + else + size += KDBUS_ITEM_SIZE(name_size + 1); //well known name + } + + pCmd_match = alloca(size); + if(pCmd_match == NULL) + goto out; + + pCmd_match->id = 0; + pCmd_match->size = size; + pCmd_match->cookie = strtoull(dbus_bus_get_unique_name(connection), NULL , 10); + + pItem = pCmd_match->items; + if(kernel_item == ~0) //all signals from kernel + { + pCmd_match->src_id = 0; + pItem->type = KDBUS_MATCH_NAME_CHANGE; + pItem->size = KDBUS_PART_HEADER_SIZE + 1; + pItem = KDBUS_PART_NEXT(pItem); + pItem->type = KDBUS_MATCH_NAME_ADD; + pItem->size = KDBUS_PART_HEADER_SIZE + 1; + pItem = KDBUS_PART_NEXT(pItem); + pItem->type = KDBUS_MATCH_NAME_REMOVE; + pItem->size = KDBUS_PART_HEADER_SIZE + 1; + pItem = KDBUS_PART_NEXT(pItem); + pItem->type = KDBUS_MATCH_ID_ADD; + pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64); + pItem = KDBUS_PART_NEXT(pItem); + pItem->type = KDBUS_MATCH_ID_REMOVE; + pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64); + } + else if(kernel_item) //only one item + { + pCmd_match->src_id = 0; + pItem->type = kernel_item; + pItem->size = KDBUS_PART_HEADER_SIZE + 1; } + else + { + pCmd_match->src_id = src_id; + if(pName) + { + pItem->type = KDBUS_MATCH_SRC_NAME; + pItem->size = KDBUS_PART_HEADER_SIZE + name_size + 1; + strcpy(pItem->str, pName); + pItem = KDBUS_PART_NEXT(pItem); + } - cmd_match.size = sizeof(cmd_match); + if(pInterface) + { + pItem->type = KDBUS_MATCH_BLOOM; + pItem->size = KDBUS_PART_HEADER_SIZE + bloom_size; + strncpy(pItem->data, pInterface, bloom_size); + } + } - //todo add matching rules from *rule when it will be docuemnted in kdbus + if(ioctl(fd, KDBUS_CMD_MATCH_ADD, pCmd_match)) + { + if(error) + dbus_set_error(error,_dbus_error_from_errno (errno), "error adding match: %s", _dbus_strerror (errno)); + _dbus_verbose("Failed adding match bus rule %s,\nerror: %d, %m\n", rule, errno); + } + else + _dbus_verbose("Added match bus rule %s\n", rule); +out: + if(pName) + free(pName); + if(pInterface) + free(pInterface); +} - cmd_match.src_id = KDBUS_MATCH_SRC_ID_ANY; +/** + * Opposing to dbus, in kdbus removes all match rules with given + * cookie, which now is equal to uniqe id. + * + * In kdbus this function will not block + * + * @param connection connection to the message bus + * @param error location to store any errors - may be NULL + */ +void dbus_bus_remove_match_kdbus (DBusConnection *connection, DBusError *error) +{ + struct kdbus_cmd_match __attribute__ ((__aligned__(8))) cmd; + int fd; - if (ioctl(fd, KDBUS_CMD_MATCH_ADD, &cmd_match)) - dbus_set_error(error,_dbus_error_from_errno (errno), "error adding match: %s", _dbus_strerror (errno)); + dbus_connection_get_socket(connection, &fd); + cmd.cookie = strtoull(dbus_bus_get_unique_name(connection), NULL , 10); + cmd.id = cmd.cookie; + cmd.size = sizeof(struct kdbus_cmd_match); - _dbus_verbose("Finished adding match bus rule %s !!!!!!!!!\n", rule); + if(ioctl(fd, KDBUS_CMD_MATCH_ADD, &cmd)) + { + if(error) + dbus_set_error(error,_dbus_error_from_errno (errno), "error removing match: %s", _dbus_strerror (errno)); + _dbus_verbose("Failed removing match rule; error: %d, %m\n", errno); + } + else + _dbus_verbose("Match rule removed correctly.\n"); }