Small fixes for dbus-kdbus translations
[platform/upstream/dbus.git] / dbus / dbus-transport-kdbus.c
index bc8e7f7..003d0c9 100644 (file)
@@ -28,6 +28,8 @@
 #include <unistd.h>
 #include <sys/mman.h>
 #include <limits.h>
+#include <sys/stat.h>
+#include <openssl/md5.h>
 
 #define KDBUS_ALIGN8(l) (((l) + 7) & ~7)
 #define KDBUS_PART_HEADER_SIZE offsetof(struct kdbus_item, data)
 
 #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.
@@ -60,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
@@ -73,13 +81,17 @@ struct DBusTransportSocket
   DBusString encoded_incoming;          /**< Encoded version of current
                                          *   incoming data.
                                          */
-  void* kdbus_mmap_ptr;
-  int memfd;                            /*   File descriptor to memory
-                                         *   pool from Kdbus kernel module */
+  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 */
 };
 
-
-
 static dbus_bool_t
 socket_get_socket_fd (DBusTransport *transport,
                       int           *fd_p)
@@ -91,65 +103,101 @@ socket_get_socket_fd (DBusTransport *transport,
   return TRUE;
 }
 
-//static void check_read_watch (DBusTransport *transport);
-
 /*
  * Adds locally generated message to received messages queue
  *
  */
-static dbus_bool_t add_message_to_received(DBusMessage *message, DBusTransport *transport)
+static dbus_bool_t add_message_to_received(DBusMessage *message, DBusConnection* connection)
 {
        DBusList *message_link;
 
        message_link = _dbus_list_alloc_link (message);
        if (message_link == NULL)
        {
-               /* it's OK to unref this, nothing that could have attached a callback
-                * has ever seen it */
                dbus_message_unref (message);
                return FALSE;
        }
 
-       _dbus_connection_queue_synthesized_message_link(transport->connection, message_link);
-//     check_read_watch(transport);
+       _dbus_connection_queue_synthesized_message_link(connection, message_link);
 
        return TRUE;
 }
 
-/*static void kdbus_debug_print_bytes(struct DBusString *data, int size)
+static dbus_bool_t reply_with_error(char* error_type, const char* template, const char* object, DBusMessage *message, DBusConnection* connection)
 {
-    uint64_t i;
+       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;
 
-    fprintf (stderr, "\ndata:\n");
-    for(i=0; i < size; i++)
+       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))
     {
-        fprintf (stderr, "%02x", _dbus_string_get_byte(data,i));
+       dbus_message_unref(reply);
+        return FALSE;
     }
-    fprintf (stderr, "\nsize: %d, i: %lu\n", size, i);
-    
-}*/
+    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;
-       int ret;
        
-       if(socket_transport->memfd == -1) 
-       {
-               ret = ioctl(socket_transport->fd, KDBUS_CMD_MEMFD_NEW, &memfd);
-               if (ret < 0) {
+               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;
 }
 
-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)
+/**
+ * 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;
@@ -170,7 +218,7 @@ static struct kdbus_msg* kdbus_init_msg(const char* name, __u64 dst_id, uint64_t
     if (name)
        msg_size += KDBUS_ITEM_SIZE(strlen(name) + 1);
     else if (dst_id == KDBUS_DST_ID_BROADCAST)
-       msg_size += KDBUS_PART_HEADER_SIZE + KDBUS_BLOOM_SIZE_BYTES;
+       msg_size += KDBUS_PART_HEADER_SIZE + transport->bloom_size;
 
     msg = malloc(msg_size);
     if (!msg)
@@ -183,10 +231,23 @@ static struct kdbus_msg* kdbus_init_msg(const char* name, __u64 dst_id, uint64_t
     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);
 
     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;
@@ -198,18 +259,16 @@ static int kdbus_write_msg(DBusTransportSocket *transport, DBusMessage *message,
     uint64_t ret_size = 0;
     uint64_t body_size = 0;
     uint64_t header_size = 0;
-    int ret;
     dbus_bool_t use_memfd;
     const int *unix_fds;
     unsigned fds_count;
-    char *buf;
+    dbus_bool_t autostart;
 
     // determine name and destination id
     if((name = dbus_message_get_destination(message)))
     {
        dst_id = KDBUS_DST_ID_WELL_KNOWN_NAME;
-       
-               if((name[0] == ':') && (name[1] == '1') && (name[2] == '.'))  /* if name starts with ":1." it is a unique name and should be send as number */
+               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 = strtoull(&name[3], NULL, 10);
                name = NULL;
@@ -234,9 +293,11 @@ static int kdbus_write_msg(DBusTransportSocket *transport, DBusMessage *message,
     _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);
+    msg = kdbus_init_msg(name, dst_id, body_size, use_memfd, fds_count, transport);
     msg->cookie = dbus_message_get_serial(message);
-    msg->src_id = strtoull(dbus_bus_get_unique_name(transport->base.connection), NULL , 10);
+    autostart = dbus_message_get_auto_start (message);
+    if(!autostart)
+       msg->flags |= KDBUS_MSG_FLAGS_NO_AUTO_START;
     
     // build message contents
     item = msg->items;
@@ -244,8 +305,9 @@ static int kdbus_write_msg(DBusTransportSocket *transport, DBusMessage *message,
     // case 1 - bulk data transfer - memfd - encoded and plain
     if(use_memfd)          
     {
-           ret = ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 0);
-           if (ret < 0) 
+        char *buf;
+
+       if(ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 0) < 0)
            {
                        _dbus_verbose("memfd sealing failed: \n");
                        goto out;
@@ -273,8 +335,7 @@ static int kdbus_write_msg(DBusTransportSocket *transport, DBusMessage *message,
                munmap(buf, ret_size);
 
                // seal data - kdbus module needs it
-               ret = ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 1);
-               if (ret < 0) {
+               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;
@@ -332,8 +393,8 @@ static int kdbus_write_msg(DBusTransportSocket *transport, DBusMessage *message,
        {
                item = KDBUS_PART_NEXT(item);
                item->type = KDBUS_MSG_BLOOM;
-               item->size = KDBUS_PART_HEADER_SIZE + KDBUS_BLOOM_SIZE_BYTES;
-               strncpy(item->data, dbus_message_get_interface(message), KDBUS_BLOOM_SIZE_BYTES);
+               item->size = KDBUS_PART_HEADER_SIZE + transport->bloom_size;
+               strncpy(item->data, dbus_message_get_interface(message), transport->bloom_size);
        }
 
        again:
@@ -341,43 +402,59 @@ static int kdbus_write_msg(DBusTransportSocket *transport, DBusMessage *message,
        {
                if(errno == EINTR)
                        goto again;
-               if((errno == ESRCH) || (errno == ENXIO))  //when recipient is not available on the bus
+               if((errno == ESRCH) || (errno == ENXIO) || (errno = EADDRNOTAVAIL))  //when recipient is not available on the bus
                {
-                       DBusMessage *errMessage = NULL;
-                       dbus_uint32_t replySerial;
-
-                       errMessage = generate_local_error_message(msg->cookie, DBUS_ERROR_SERVICE_UNKNOWN, (char*)dbus_message_get_destination(message));
-                       if(errMessage == NULL)
+                       if(autostart)
                        {
-                               ret_size = -1;
-                               goto out;
+                               //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;
                        }
-                       replySerial = dbus_message_get_reply_serial(message);
-                       if(replySerial)
-                               dbus_message_set_reply_serial(errMessage, replySerial);
-                       if (!add_message_to_received(errMessage, (DBusTransport*)transport))
-                               ret_size = -1;
-                       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);
                ret_size = -1;
        }
 out:
     free(msg);
+    close(transport->memfd);
 
     return ret_size;
 }
 
-static int64_t kdbus_NameQuery(DBusTransport *transport, char* name, int fd)
+struct nameInfo
+{
+       __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;
-       int64_t ret;
+       int ret;
        uint64_t item_size;
 
+       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;
+       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);
@@ -389,6 +466,10 @@ static int64_t kdbus_NameQuery(DBusTransport *transport, char* name, int fd)
 
        memset(msg, 0, size);
        msg->size = size;
+       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;
@@ -396,90 +477,151 @@ static int64_t kdbus_NameQuery(DBusTransport *transport, char* name, int fd)
        strcpy(item->str, name);
 
        again:
-       if ((ret = ioctl(fd, KDBUS_CMD_NAME_QUERY, msg)))
+       ret = ioctl(fd, KDBUS_CMD_NAME_QUERY, msg);
+       if (ret < 0)
        {
                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
-               ret = msg->id;
+       {
+               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;
 }
 
-static dbus_bool_t emulateOrgFreedesktopDBus(DBusTransport *transport, DBusMessage *message, int fd)
+/**
+ * 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)
 {
-       int64_t ret;
+       int inter_ret;
+       struct nameInfo info;
+       dbus_bool_t ret_value;
 
-       if(!strcmp(dbus_message_get_member(message), "GetNameOwner"))
+       if(!strcmp(dbus_message_get_member(message), "GetNameOwner"))  //returns id of the well known name
        {
                char* name = NULL;
 
                dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
-               _dbus_verbose ("Name to discover: %s   !!!!             !!!!\n", name);
-               ret = kdbus_NameQuery(transport, name, fd);
-               if(ret > 0) //unique id of the name
+               inter_ret = kdbus_NameQuery(name, ((DBusTransportSocket*)transport)->fd, &info);
+               if(inter_ret == 0) //unique id of the name
                {
-                       DBusMessage *reply;
-                       DBusMessageIter args;
-                       char unique_name[(unsigned int)(snprintf(name, 0, "%llu", ULLONG_MAX) + 4)]; //+3 prefix ":1." and +1 closing NULL
+                       char unique_name[(unsigned int)(snprintf(name, 0, "%llu", ULLONG_MAX) + sizeof(":1."))];
                        const char* pString = unique_name;
 
-                       sprintf(unique_name, ":1.%lld", (long long int)ret);
-                       _dbus_verbose("Unique name discovered:%s!!!                       !!!!\n", unique_name);
-                       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, DBUS_TYPE_STRING, &pString))
-                       return FALSE;
-                   if(add_message_to_received(reply, transport))
-                       return TRUE;
+                       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(ret == -ENOENT)  //name has no owner
+               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
                {
-                       DBusMessage *errMessage;
-                       dbus_uint32_t replySerial;
+                       _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;
 
-                       errMessage = generate_local_error_message(1, DBUS_ERROR_NAME_HAS_NO_OWNER, name);
-                       if(errMessage == NULL)
-                               return FALSE;
-                       replySerial = dbus_message_get_reply_serial(message);
-                       if(replySerial)
-                               dbus_message_set_reply_serial(errMessage, replySerial);
-                       if (add_message_to_received(errMessage, transport))
-                               return TRUE;
+               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 sending name query: err %d (%m)\n", errno);
+               {
+                       _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), "NameHasOwner"))
+       else if(!strcmp(dbus_message_get_member(message), "GetConnectionUnixUser"))
+       {
+               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;
-               DBusMessage *reply;
-               DBusMessageIter args;
-               dbus_bool_t result;
 
                dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
-               _dbus_verbose ("Name to discover: %s   !!!!             !!!!\n", name);
-               ret = kdbus_NameQuery(transport, name, fd);
-
-               result = (ret > 0) ? TRUE : FALSE;
-               _dbus_verbose("Discovery: %d !!!                       !!!!\n", (int)result);
-               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, DBUS_TYPE_BOOLEAN, &result))
-                       return FALSE;
-               if(add_message_to_received(reply, transport))
-                       return TRUE;
+               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"))
+       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;
@@ -492,24 +634,24 @@ static dbus_bool_t emulateOrgFreedesktopDBus(DBusTransport *transport, DBusMessa
 
   again:
                cmd_size = 0;
-               if(ioctl(fd, KDBUS_CMD_NAME_LIST, pCmd))
+               if(ioctl(((DBusTransportSocket*)transport)->fd, KDBUS_CMD_NAME_LIST, pCmd))
                {
                        if(errno == EINTR)
                                goto again;
-                       if(errno == ENOBUFS)
-                               cmd_size = pCmd->size;
+                       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)
+               if(cmd_size)  //kernel needs more memory
                {
-                       pCmd = realloc(pCmd, cmd_size);
+                       pCmd = realloc(pCmd, cmd_size);  //prepare memory
                        if(pCmd == NULL)
                                return FALSE;
-                       goto again;
+                       goto again;                                             //and try again
                }
                else
                {
@@ -528,56 +670,114 @@ static dbus_bool_t emulateOrgFreedesktopDBus(DBusTransport *transport, DBusMessa
                        {
                                pName = pCmd_name->name;
                                if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pName))
-                               goto out;
+                               {
+                                       dbus_message_unref(reply);
+                                       goto out;
+                               }
                        }
 
-                       if(add_message_to_received(reply, transport))
+                       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  //temporarily we send that info but methods below should be implemented
+       else if(!strcmp(dbus_message_get_member(message), "GetConnectionSELinuxSecurityContext"))
        {
-               DBusMessage *reply;
-               dbus_uint32_t replySerial;
-
-               reply = generate_local_error_message(1, DBUS_ERROR_UNKNOWN_METHOD, NULL);
-               if(reply == NULL)
-                       return FALSE;
-               replySerial = dbus_message_get_reply_serial(message);
-               if(replySerial)
-                       dbus_message_set_reply_serial(reply, replySerial);
-               if(add_message_to_received(reply, transport))
-                       return TRUE;
+               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 if(!strcmp(dbus_message_get_member(message), "ListActivatableNames"))
+       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
        {
-               //todo
+
        }
        else if(!strcmp(dbus_message_get_member(message), "StartServiceByName"))
        {
-               //todo
+
        }
        else if(!strcmp(dbus_message_get_member(message), "UpdateActivationEnvironment"))
        {
-               //todo
+
        }
-       else if(!strcmp(dbus_message_get_member(message), "GetConnectionUnixUser"))
+       else if(!strcmp(dbus_message_get_member(message), "ReloadConfig"))
        {
-               //todo
+
        }
-       else if(!strcmp(dbus_message_get_member(message), "GetId"))
-       {
-               //todo
-       }*/
+       */
 
-       return FALSE;
+       if(info.sec_label)
+               free(info.sec_label);
+       return ret_value;
 }
 
 #if KDBUS_MSG_DECODE_DEBUG == 1
@@ -645,6 +845,14 @@ TABLE(PAYLOAD) = {
 };
 LOOKUP(PAYLOAD);
 
+/**
+ * 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;
@@ -660,23 +868,32 @@ static int put_message_into_data(DBusMessage *message, char* data)
        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
+ * 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;
+       const struct kdbus_item *item;
        int ret_size = 0;
        DBusMessage *message = NULL;
        DBusMessageIter args;
        const char* emptyString = "";
     const char* pString = NULL;
-       char dbus_name[(unsigned int)(snprintf((char*)pString, 0, "%llu", ULLONG_MAX) + 4)];  //+3 prefix ":1." and +1 closing NULL
+       char dbus_name[(unsigned int)(snprintf((char*)pString, 0, "%llu", ULLONG_MAX) + sizeof(":1."))];
        const char* pDBusName = dbus_name;
-    void* mmap_ptr;
 #if KDBUS_MSG_DECODE_DEBUG == 1
        char buf[32];
 #endif
@@ -690,7 +907,6 @@ static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTranspo
 #endif
 
        *n_fds = 0;
-       mmap_ptr = socket_transport->kdbus_mmap_ptr;
 
        KDBUS_PART_FOREACH(item, msg, items)
        {
@@ -703,31 +919,25 @@ static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTranspo
                switch (item->type)
                {
                        case KDBUS_MSG_PAYLOAD_OFF:
-                       {
-                               uint64_t size = item->vec.size;
-
-                               memcpy(data, (char *)mmap_ptr + item->vec.offset, item->vec.size);
+                               memcpy(data, (char *)socket_transport->kdbus_mmap_ptr + item->vec.offset, item->vec.size);
                                data += item->vec.size;
                                ret_size += item->vec.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)size);
+                                       (unsigned long long)item->vec.size);
                        break;
-                       }
 
                        case KDBUS_MSG_PAYLOAD_MEMFD:
                        {
                                char *buf;
                                uint64_t size;
 
-                 size = item->memfd.size;
-
+                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);
@@ -842,7 +1052,6 @@ static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTranspo
 #endif
 
                        case KDBUS_MSG_REPLY_TIMEOUT:
-                       case KDBUS_MSG_REPLY_DEAD:
                                _dbus_verbose("  +%s (%llu bytes) cookie=%llu\n",
                                           enum_MSG(item->type), item->size, msg->cookie_reply);
 
@@ -856,15 +1065,27 @@ static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTranspo
                                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",
                                        enum_MSG(item->type), (unsigned long long) item->size,
                                        item->name_change.name, item->name_change.old_id,
                                        item->name_change.new_id, item->name_change.flags);
 
-                               message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal
-                                           DBUS_INTERFACE_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;
@@ -875,24 +1096,10 @@ static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTranspo
                                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, &pDBusName))
-                               {
-                                       ret_size = -1;
-                               goto out;
-                               }
-
+                           ITER_APPEND_STR(pString)
+                           ITER_APPEND_STR(emptyString)
+                           ITER_APPEND_STR(pDBusName)
                                dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
-                               dbus_message_set_serial(message, 1);
 
                                ret_size = put_message_into_data(message, data);
                        break;
@@ -903,9 +1110,7 @@ static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTranspo
                                        item->name_change.name, item->name_change.old_id,
                                        item->name_change.new_id, item->name_change.flags);
 
-                               message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal
-                                           DBUS_INTERFACE_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;
@@ -916,24 +1121,10 @@ static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTranspo
                                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, &pDBusName))
-                               {
-                                       ret_size = -1;
-                               goto out;
-                               }
-                           if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &emptyString))
-                               {
-                                       ret_size = -1;
-                               goto out;
-                               }
-
+                           ITER_APPEND_STR(pString)
+                           ITER_APPEND_STR(pDBusName)
+                           ITER_APPEND_STR(emptyString)
                                dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
-                               dbus_message_set_serial(message, 1);
 
                                ret_size = put_message_into_data(message, data);
                        break;
@@ -944,9 +1135,7 @@ static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTranspo
                                        item->name_change.name, item->name_change.old_id,
                                        item->name_change.new_id, item->name_change.flags);
 
-                               message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal
-                                           DBUS_INTERFACE_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;
@@ -957,26 +1146,12 @@ static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTranspo
                                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, &pDBusName))
-                               {
-                                       ret_size = -1;
-                               goto out;
-                               }
+                           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);
-                           if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
-                               {
-                                       ret_size = -1;
-                               goto out;
-                               }
-
+                           ITER_APPEND_STR(pDBusName)
                                dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
-                               dbus_message_set_serial(message, 1);
 
                                ret_size = put_message_into_data(message, data);
                        break;
@@ -987,9 +1162,7 @@ static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTranspo
                                           (unsigned long long) item->id_change.id,
                                           (unsigned long long) item->id_change.flags);
 
-                               message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal
-                                           DBUS_INTERFACE_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;
@@ -998,24 +1171,10 @@ static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTranspo
 
                                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, &pDBusName))
-                               {
-                                       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, &pDBusName))
-                               {
-                                       ret_size = -1;
-                               goto out;
-                               }
-
+                           ITER_APPEND_STR(pDBusName)
+                           ITER_APPEND_STR(emptyString)
+                           ITER_APPEND_STR(pDBusName)
                                dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
-                               dbus_message_set_serial(message, 1);
 
                                ret_size = put_message_into_data(message, data);
                        break;
@@ -1026,9 +1185,7 @@ static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTranspo
                                           (unsigned long long) item->id_change.id,
                                           (unsigned long long) item->id_change.flags);
 
-                               message = dbus_message_new_signal("/org/freedesktop/DBus", // object name of the signal
-                                           DBUS_INTERFACE_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;
@@ -1037,24 +1194,10 @@ static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTranspo
 
                                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, &pDBusName))
-                               {
-                                       ret_size = -1;
-                               goto out;
-                               }
-                           if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &pDBusName))
-                               {
-                                       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_serial(message, 1);
 
                                ret_size = put_message_into_data(message, data);
                        break;
@@ -1079,7 +1222,7 @@ out:
 }
 
 /**
- * Reads message from kdbus to buffer and fds
+ * Reads message from kdbus and puts it into dbus buffer and fds
  *
  * @param transport transport
  * @param buffer place to copy received message to
@@ -1093,14 +1236,15 @@ static int kdbus_read_message(DBusTransportSocket *socket_transport, DBusString
        uint64_t __attribute__ ((__aligned__(8))) offset;
        struct kdbus_msg *msg;
        char *data;
+       int start;
 
-       _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))
        {
                errno = ENOMEM;
            return -1;
        }
-       data = _dbus_string_get_data_len (buffer, 0, socket_transport->max_bytes_read_per_iteration);
+       data = _dbus_string_get_data_len (buffer, start, socket_transport->max_bytes_read_per_iteration);
 
        again:
        if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RECV, &offset) < 0)
@@ -1108,14 +1252,22 @@ static int kdbus_read_message(DBusTransportSocket *socket_transport, DBusString
                if(errno == EINTR)
                        goto again;
                _dbus_verbose("kdbus error receiving message: %d (%m)\n", errno);
-               _dbus_string_set_length (buffer, 0);
+               _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, fds, n_fds);
-       _dbus_string_set_length (buffer, ret_size);
+
+       if(ret_size == -1) /* error */
+       {
+               _dbus_string_set_length (buffer, start);
+               return -1;
+       }
+       else
+               _dbus_string_set_length (buffer, start + ret_size);
+       
 
        again2:
        if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RELEASE, &offset) < 0)
@@ -1606,7 +1758,7 @@ do_writing (DBusTransport *transport)
                {
                        if(!strcmp(pDestination, "org.freedesktop.DBus"))
                        {
-                               if(emulateOrgFreedesktopDBus(transport, message, socket_transport->fd))
+                               if(emulateOrgFreedesktopDBus(transport, message))
                                        bytes_written = total_bytes_to_write;
                                else
                                        bytes_written = -1;
@@ -1690,8 +1842,7 @@ written:
        out:
        if (oom)
                return FALSE;
-       else
-               return TRUE;
+       return TRUE;
 }
 
 /* returns false on out-of-memory */
@@ -1766,7 +1917,7 @@ do_reading (DBusTransport *transport)
 
   _dbus_message_loader_return_buffer (transport->loader,
                                       buffer,
-                                      bytes_read < 0 ? 0 : _dbus_string_get_length (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)
@@ -1816,8 +1967,7 @@ do_reading (DBusTransport *transport)
  out:
   if (oom)
     return FALSE;
-  else
-    return TRUE;
+  return TRUE;
 }
 
 static dbus_bool_t
@@ -1825,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
@@ -2010,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.
@@ -2029,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
@@ -2074,46 +2221,45 @@ 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 ("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;
       }
 
       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;
+         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,
@@ -2123,15 +2269,15 @@ kdbus_do_iteration (DBusTransport *transport,
              if (authentication_completed)
                 goto out;
 #endif
-              if (need_read && (flags & DBUS_ITERATION_DO_READING))
-                do_reading (transport);
-              if (need_write && (flags & DBUS_ITERATION_DO_WRITING))
-                do_writing (transport);
-            }
-        }
+            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
@@ -2144,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
@@ -2270,7 +2416,7 @@ static int _dbus_connect_kdbus (const char *path, DBusError *error)
  * maps memory pool for messages received by the kdbus transport
  *
  * @param transport transport
- * @returns #TRUE on success
+ * @returns #TRUE on success, otherwise FALSE
  */
 static dbus_bool_t kdbus_mmap(DBusTransport* transport)
 {
@@ -2508,7 +2654,6 @@ dbus_bool_t bus_register_kdbus(char* name, DBusConnection *connection, DBusError
        struct kdbus_cmd_hello __attribute__ ((__aligned__(8))) hello;
        int fd;
 
-       memset(&hello, 0, sizeof(hello));
        hello.conn_flags = KDBUS_HELLO_ACCEPT_FD/* |
                           KDBUS_HELLO_ATTACH_COMM |
                           KDBUS_HELLO_ATTACH_EXE |
@@ -2531,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)))
        {
@@ -2604,7 +2750,9 @@ int bus_request_name_kdbus(DBusConnection *connection, const char *name, const u
                return DBUS_REQUEST_NAME_REPLY_IN_QUEUE;
        else
                return DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER;
-       //todo now 1 code is 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
+        */
 }
 
 /**
@@ -2617,12 +2765,24 @@ 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;
@@ -2681,6 +2841,7 @@ void dbus_bus_add_match_kdbus (DBusConnection *connection, const char *rule, DBu
        int name_size;
        char* pName = NULL;
        char* pInterface = NULL;
+       __u64 bloom_size = ((DBusTransportSocket*)dbus_connection_get_transport(connection))->bloom_size;
 
        dbus_connection_get_socket(connection, &fd);
 
@@ -2704,23 +2865,21 @@ void dbus_bus_add_match_kdbus (DBusConnection *connection, const char *rule, DBu
        }
 
        name_size = parse_match_key(rule, "interface='", &pInterface);
-       if((name_size == -1) && (kernel_item == 0))   //means org.freedesktop.DBus
+       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*/
+               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 + KDBUS_BLOOM_SIZE_BYTES;
+               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 - same as interface few line above
+       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*/
+               size += KDBUS_ITEM_SIZE(1)*3 + KDBUS_ITEM_SIZE(sizeof(__u64))*2; /* 3 above     name related items plus 2 id related items*/
        }
-       if(name_size > 0)
+       else if(name_size > 0)
        {
                if(!strncmp(pName, ":1.", 3)) /*if name is unique name it must be converted to unique id*/
                {
@@ -2735,8 +2894,8 @@ void dbus_bus_add_match_kdbus (DBusConnection *connection, const char *rule, DBu
        pCmd_match = alloca(size);
        if(pCmd_match == NULL)
                goto out;
-       memset(pCmd_match, 0, size);
 
+       pCmd_match->id = 0;
        pCmd_match->size = size;
        pCmd_match->cookie = strtoull(dbus_bus_get_unique_name(connection), NULL , 10);
 
@@ -2759,7 +2918,7 @@ void dbus_bus_add_match_kdbus (DBusConnection *connection, const char *rule, DBu
                pItem->type = KDBUS_MATCH_ID_REMOVE;
                pItem->size = KDBUS_PART_HEADER_SIZE + sizeof(__u64);
        }
-       else if(kernel_item)
+       else if(kernel_item) //only one item
        {
                pCmd_match->src_id = 0;
                pItem->type = kernel_item;
@@ -2779,8 +2938,8 @@ void dbus_bus_add_match_kdbus (DBusConnection *connection, const char *rule, DBu
                if(pInterface)
                {
                        pItem->type = KDBUS_MATCH_BLOOM;
-                       pItem->size = KDBUS_PART_HEADER_SIZE + KDBUS_BLOOM_SIZE_BYTES;
-                       strncpy(pItem->data, pInterface, KDBUS_BLOOM_SIZE_BYTES);
+                       pItem->size = KDBUS_PART_HEADER_SIZE + bloom_size;
+                       strncpy(pItem->data, pInterface, bloom_size);
                }
        }