[lib-fix] fixed sending broadcasts bigger than memfd threshold
[platform/upstream/dbus.git] / dbus / dbus-transport-kdbus.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-transport-kdbus.c  kdbus subclasses of DBusTransport
3  *
4  * Copyright (C) 2002, 2003, 2004, 2006  Red Hat Inc
5  * Copyright (C) 2013  Samsung Electronics
6  *
7  * Licensed under the Academic Free License version 2.1
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version and under the terms of the GNU
13  * Lesser General Public License as published by the
14  * Free Software Foundation; either version 2.1 of the License, or (at
15  * your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
25  *
26  */
27 #include "dbus-transport.h"
28 #include "dbus-transport-kdbus.h"
29 #include "dbus-transport-protected.h"
30 #include "dbus-connection-internal.h"
31 #include "kdbus.h"
32 #include "dbus-watch.h"
33 #include "dbus-errors.h"
34 #include "dbus-bus.h"
35 #include "kdbus-common.h"
36 #include <linux/types.h>
37 #include <fcntl.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <sys/ioctl.h>
41 #include <stdio.h>
42 #include <string.h>
43 #include <stdlib.h>
44 #include <unistd.h>
45 #include <sys/mman.h>
46 #include <limits.h>
47 #include <sys/stat.h>
48
49 #define KDBUS_PART_FOREACH(part, head, first)                           \
50         for (part = (head)->first;                                      \
51              (uint8_t *)(part) < (uint8_t *)(head) + (head)->size;      \
52              part = KDBUS_PART_NEXT(part))
53 #define RECEIVE_POOL_SIZE (10 * 1024LU * 1024LU)
54 #define MEMFD_SIZE_THRESHOLD (2 * 1024 * 1024LU) // over this memfd is used
55 //todo add compilation-time check if MEMFD_SIZE_THERSHOLD is lower than max payload vector size defined in kdbus.h
56
57 #define KDBUS_MSG_DECODE_DEBUG 0
58
59 #define ITER_APPEND_STR(string) \
60 if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &string))   \
61 { \
62         ret_size = -1;  \
63         goto out;  \
64 }\
65
66 #define MSG_ITEM_BUILD_VEC(data, datasize)                                    \
67         item->type = KDBUS_MSG_PAYLOAD_VEC;                                     \
68         item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec);         \
69         item->vec.address = (unsigned long) data;                               \
70         item->vec.size = datasize;
71
72 /**
73  * Opaque object representing a transport. In kdbus transport it has nothing common
74  * with socket, but the name was preserved to comply with  upper functions.
75  */
76 typedef struct DBusTransportKdbus DBusTransportKdbus;
77
78 /**
79  * Implementation details of DBusTransportSocket. All members are private.
80  */
81 struct DBusTransportKdbus
82 {
83   DBusTransport base;                   /**< Parent instance */
84   int fd;                               /**< File descriptor. */
85   DBusWatch *read_watch;                /**< Watch for readability. */
86   DBusWatch *write_watch;               /**< Watch for writability. */
87
88   int max_bytes_read_per_iteration;     /**< In kdbus only to control overall message size*/
89   int max_bytes_written_per_iteration;  /**< In kdbus only to control overall message size*/
90
91   int message_bytes_written;            /**< Number of bytes of current
92                                          *   outgoing message that have
93                                          *   been written.
94                                          */
95   void* kdbus_mmap_ptr;                 /**< Mapped memory where Kdbus (kernel) writes
96                                          *   messages incoming to us.
97                                          */
98   int memfd;                            /**< File descriptor to special 
99                                          *   memory pool for bulk data
100                                          *   transfer. Retrieved from 
101                                          *   Kdbus kernel module. 
102                                          */
103   __u64 bloom_size;                                             /**<  bloom filter field size */
104   char* sender;                         /**< uniqe name of the sender */
105 };
106
107 __u64 dbus_transport_get_bloom_size(DBusTransport* transport)
108 {
109   return ((DBusTransportKdbus*)transport)->bloom_size;
110 }
111
112 /*
113  * Adds locally generated message to received messages queue
114  *
115  */
116 static dbus_bool_t add_message_to_received(DBusMessage *message, DBusConnection* connection)
117 {
118         DBusList *message_link;
119
120         message_link = _dbus_list_alloc_link (message);
121         if (message_link == NULL)
122         {
123                 dbus_message_unref (message);
124                 return FALSE;
125         }
126
127         _dbus_connection_queue_synthesized_message_link(connection, message_link);
128
129         return TRUE;
130 }
131
132 /*
133  * Generates local error message as a reply to message given as parameter
134  * and adds generated error message to received messages queue.
135  */
136 static int reply_with_error(char* error_type, const char* template, const char* object, DBusMessage *message, DBusConnection* connection)
137 {
138         DBusMessage *errMessage;
139         char* error_msg = "";
140
141         if(template)
142         {
143                 error_msg = alloca(strlen(template) + strlen(object));
144                 sprintf(error_msg, template, object);
145         }
146         else if(object)
147                 error_msg = (char*)object;
148
149         errMessage = generate_local_error_message(dbus_message_get_serial(message), error_type, error_msg);
150         if(errMessage == NULL)
151                 return -1;
152         if (add_message_to_received(errMessage, connection))
153                 return 0;
154
155         return -1;
156 }
157
158 /*
159  *  Generates reply to the message given as a parameter with one item in the reply body
160  *  and adds generated reply message to received messages queue.
161  */
162 static int reply_1_data(DBusMessage *message, int data_type, void* pData, DBusConnection* connection)
163 {
164         DBusMessageIter args;
165         DBusMessage *reply;
166
167         reply = dbus_message_new_method_return(message);
168         if(reply == NULL)
169                 return -1;
170         dbus_message_set_sender(reply, DBUS_SERVICE_DBUS);
171     dbus_message_iter_init_append(reply, &args);
172     if (!dbus_message_iter_append_basic(&args, data_type, pData))
173     {
174         dbus_message_unref(reply);
175         return -1;
176     }
177     if(add_message_to_received(reply, connection))
178         return 0;
179
180     return -1;
181 }
182
183 /*
184 static int reply_ack(DBusMessage *message, DBusConnection* connection)
185 {
186         DBusMessage *reply;
187
188         reply = dbus_message_new_method_return(message);
189         if(reply == NULL)
190                 return -1;
191     if(add_message_to_received(reply, connection))
192         return 0;
193     return -1;
194 }*/
195
196 /**
197  * Retrieves file descriptor to memory pool from kdbus module.
198  * It is then used for bulk data sending.
199  * Triggered when message payload is over MEMFD_SIZE_THRESHOLD
200  * 
201  */
202 static int kdbus_init_memfd(DBusTransportKdbus* socket_transport)
203 {
204         int memfd;
205         
206                 if (ioctl(socket_transport->fd, KDBUS_CMD_MEMFD_NEW, &memfd) < 0) {
207                         _dbus_verbose("KDBUS_CMD_MEMFD_NEW failed: \n");
208                         return -1;
209                 }
210
211                 socket_transport->memfd = memfd;
212                 _dbus_verbose("kdbus_init_memfd: %d!!\n", socket_transport->memfd);
213         return 0;
214 }
215
216 /**
217  * Initiates Kdbus message structure. 
218  * Calculates it's size, allocates memory and fills some fields.
219  * @param name Well-known name or NULL
220  * @param dst_id Numeric id of recipient
221  * @param body_size size of message body if present
222  * @param use_memfd flag to build memfd message
223  * @param fds_count number of file descriptors used
224  * @param transport transport
225  * @return initialized kdbus message
226  */
227 static struct kdbus_msg* kdbus_init_msg(const char* name, __u64 dst_id, uint64_t body_size, dbus_bool_t use_memfd, int fds_count, DBusTransportKdbus *transport)
228 {
229     struct kdbus_msg* msg;
230     uint64_t msg_size;
231
232     msg_size = sizeof(struct kdbus_msg);
233
234     if(use_memfd == TRUE)  // bulk data - memfd
235         msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_memfd));
236     else
237       {
238         msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));  //header is a must
239         while(body_size > KDBUS_MSG_MAX_PAYLOAD_VEC_SIZE)
240           {
241             msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
242             body_size -= KDBUS_MSG_MAX_PAYLOAD_VEC_SIZE;
243           }
244         if(body_size)
245           msg_size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
246       }
247
248     if(fds_count)
249         msg_size += KDBUS_ITEM_SIZE(sizeof(int)*fds_count);
250
251     if (name)
252         msg_size += KDBUS_ITEM_SIZE(strlen(name) + 1);
253     else if (dst_id == KDBUS_DST_ID_BROADCAST)
254         msg_size += KDBUS_PART_HEADER_SIZE + transport->bloom_size;
255
256     msg = malloc(msg_size);
257     if (!msg)
258     {
259         _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
260                 return NULL;
261     }
262
263     memset(msg, 0, msg_size);
264     msg->size = msg_size;
265     msg->payload_type = KDBUS_PAYLOAD_DBUS1;
266     msg->dst_id = name ? 0 : dst_id;
267     msg->src_id = strtoull(dbus_bus_get_unique_name(transport->base.connection), NULL , 10);
268
269     return msg;
270 }
271
272 /**
273  * Builds and sends kdbus message using DBus message.
274  * Decide whether used payload vector or memfd memory pool.
275  * Handles broadcasts and unicast messages, and passing of Unix fds.
276  * Does error handling.
277  * TODO refactor to be more compact
278  *
279  * @param transport transport
280  * @param message DBus message to be sent
281  * @return size of data sent
282  */
283 static int kdbus_write_msg(DBusTransportKdbus *transport, DBusMessage *message, const char* destination)
284 {
285     struct kdbus_msg *msg;
286     struct kdbus_item *item;
287     uint64_t dst_id = KDBUS_DST_ID_BROADCAST;
288     const DBusString *header;
289     const DBusString *body;
290     uint64_t ret_size = 0;
291     uint64_t body_size = 0;
292     uint64_t header_size = 0;
293   dbus_bool_t use_memfd = FALSE;
294     const int *unix_fds;
295     unsigned fds_count;
296     dbus_bool_t autostart;
297
298     // determine destination and destination id
299     if(destination)
300     {
301         dst_id = KDBUS_DST_ID_WELL_KNOWN_NAME;
302                 if((destination[0] == ':') && (destination[1] == '1') && (destination[2] == '.'))  /* if name starts with ":1." it is a unique name and should be send as number */
303         {
304                 dst_id = strtoull(&destination[3], NULL, 10);
305                 destination = NULL;
306         }    
307     }
308     
309     _dbus_message_get_network_data (message, &header, &body);
310     header_size = _dbus_string_get_length(header);
311     body_size = _dbus_string_get_length(body);
312     ret_size = header_size + body_size;
313
314   // check whether we can and should use memfd
315   if((dst_id != KDBUS_DST_ID_BROADCAST) && (ret_size > MEMFD_SIZE_THRESHOLD))
316     {
317       use_memfd = TRUE;
318       kdbus_init_memfd(transport);
319     }
320     
321     _dbus_message_get_unix_fds(message, &unix_fds, &fds_count);
322
323     // init basic message fields
324     msg = kdbus_init_msg(destination, dst_id, body_size, use_memfd, fds_count, transport);
325     msg->cookie = dbus_message_get_serial(message);
326     autostart = dbus_message_get_auto_start (message);
327     if(!autostart)
328         msg->flags |= KDBUS_MSG_FLAGS_NO_AUTO_START;
329     
330     // build message contents
331     item = msg->items;
332
333     if(use_memfd)          
334     {
335         char *buf;
336
337         if(ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 0) < 0)
338             {
339                         _dbus_verbose("memfd sealing failed: \n");
340                         goto out;
341             }
342
343             buf = mmap(NULL, ret_size, PROT_WRITE, MAP_SHARED, transport->memfd, 0);
344             if (buf == MAP_FAILED) 
345             {
346                         _dbus_verbose("mmap() fd=%i failed:%m", transport->memfd);
347                         goto out;
348             }
349
350                         memcpy(buf, _dbus_string_get_const_data(header), header_size);
351                         if(body_size) {
352                                 buf+=header_size;
353                                 memcpy(buf, _dbus_string_get_const_data(body),  body_size);
354                                 buf-=header_size;
355                 }
356
357                 munmap(buf, ret_size);
358
359                 // seal data - kdbus module needs it
360                 if(ioctl(transport->memfd, KDBUS_CMD_MEMFD_SEAL_SET, 1) < 0) {
361                         _dbus_verbose("memfd sealing failed: %d (%m)\n", errno);
362                         ret_size = -1;
363                         goto out;
364                 }
365
366             item->type = KDBUS_MSG_PAYLOAD_MEMFD;
367                 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_memfd);
368                 item->memfd.size = ret_size;
369                 item->memfd.fd = transport->memfd;
370     }
371     else
372       {
373         _dbus_verbose("sending normal vector data\n");
374         MSG_ITEM_BUILD_VEC(_dbus_string_get_const_data(header), header_size);
375
376       if(body_size)
377         {
378           const char* body_data;
379
380           body_data = _dbus_string_get_const_data(body);
381           while(body_size > KDBUS_MSG_MAX_PAYLOAD_VEC_SIZE)
382             {
383               _dbus_verbose("body attaching\n");
384               item = KDBUS_PART_NEXT(item);
385               MSG_ITEM_BUILD_VEC(body_data, KDBUS_MSG_MAX_PAYLOAD_VEC_SIZE);
386               body_data += KDBUS_MSG_MAX_PAYLOAD_VEC_SIZE;
387               body_size -= KDBUS_MSG_MAX_PAYLOAD_VEC_SIZE;
388             }
389           if(body_size)
390             {
391               _dbus_verbose("body attaching\n");
392               item = KDBUS_PART_NEXT(item);
393               MSG_ITEM_BUILD_VEC(body_data, body_size);
394             }
395         }
396     }
397
398     if(fds_count)
399     {
400         item = KDBUS_PART_NEXT(item);
401         item->type = KDBUS_MSG_FDS;
402         item->size = KDBUS_PART_HEADER_SIZE + (sizeof(int) * fds_count);
403         memcpy(item->fds, unix_fds, sizeof(int) * fds_count);
404     }
405
406         if (destination)
407         {
408                 item = KDBUS_PART_NEXT(item);
409                 item->type = KDBUS_MSG_DST_NAME;
410                 item->size = KDBUS_PART_HEADER_SIZE + strlen(destination) + 1;
411                 memcpy(item->str, destination, item->size - KDBUS_PART_HEADER_SIZE);
412         }
413         else if (dst_id == KDBUS_DST_ID_BROADCAST)
414         {
415                 item = KDBUS_PART_NEXT(item);
416                 item->type = KDBUS_MSG_BLOOM;
417                 item->size = KDBUS_PART_HEADER_SIZE + transport->bloom_size;
418                 strncpy(item->data, dbus_message_get_interface(message), transport->bloom_size);
419         }
420
421         again:
422         if (ioctl(transport->fd, KDBUS_CMD_MSG_SEND, msg))
423         {
424                 if(errno == EINTR)
425                         goto again;
426                 else if(errno == ENXIO) //no such id on the bus
427                 {
428             if(!reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Name \"%s\" does not exist", dbus_message_get_destination(message), message, transport->base.connection))
429                 goto out;
430                 }
431         else if((errno == ESRCH) || (errno = EADDRNOTAVAIL))  //when well known name is not available on the bus
432                 {
433                         if(autostart)
434                         {
435                                 if(!reply_with_error(DBUS_ERROR_SERVICE_UNKNOWN, "The name %s was not provided by any .service files", dbus_message_get_destination(message), message, transport->base.connection))
436                                         goto out;
437                         }
438                         else
439                     if(!reply_with_error(DBUS_ERROR_NAME_HAS_NO_OWNER, "Name \"%s\" does not exist", dbus_message_get_destination(message), message, transport->base.connection))
440                         goto out;
441                 }
442                 _dbus_verbose("kdbus error sending message: err %d (%m)\n", errno);
443                 ret_size = -1;
444         }
445 out:
446     free(msg);
447     if(use_memfd)
448         close(transport->memfd);
449
450     return ret_size;
451 }
452
453 /**
454  * Performs kdbus hello - registration on the kdbus bus
455  *
456  * @param name place to store unique name given by bus
457  * @param transportS transport structure
458  * @returns #TRUE on success
459  */
460 static dbus_bool_t bus_register_kdbus(char* name, DBusTransportKdbus* transportS)
461 {
462         struct kdbus_cmd_hello __attribute__ ((__aligned__(8))) hello;
463
464         hello.conn_flags = KDBUS_HELLO_ACCEPT_FD/* |
465                            KDBUS_HELLO_ATTACH_COMM |
466                            KDBUS_HELLO_ATTACH_EXE |
467                            KDBUS_HELLO_ATTACH_CMDLINE |
468                            KDBUS_HELLO_ATTACH_CAPS |
469                            KDBUS_HELLO_ATTACH_CGROUP |
470                            KDBUS_HELLO_ATTACH_SECLABEL |
471                            KDBUS_HELLO_ATTACH_AUDIT*/;
472         hello.size = sizeof(struct kdbus_cmd_hello);
473         hello.pool_size = RECEIVE_POOL_SIZE;
474
475         if (ioctl(transportS->fd, KDBUS_CMD_HELLO, &hello))
476         {
477                 _dbus_verbose ("Failed to send hello: %m, %d",errno);
478                 return FALSE;
479         }
480
481         sprintf(name, "%llu", (unsigned long long)hello.id);
482         _dbus_verbose("-- Our peer ID is: %s\n", name);
483         transportS->bloom_size = hello.bloom_size;
484
485         transportS->kdbus_mmap_ptr = mmap(NULL, RECEIVE_POOL_SIZE, PROT_READ, MAP_SHARED, transportS->fd, 0);
486         if (transportS->kdbus_mmap_ptr == MAP_FAILED)
487         {
488                 _dbus_verbose("Error when mmap: %m, %d",errno);
489                 return FALSE;
490         }
491
492         return TRUE;
493 }
494
495 /**
496  * Handles messages sent to bus daemon - "org.freedesktop.DBus" and translates them to appropriate
497  * kdbus ioctl commands. Than translate kdbus reply into dbus message and put it into recived messages queue.
498  *
499  * Now it captures only Hello message, which must be handled locally.
500  * All the rest is passed to dbus-daemon.
501  */
502 static int emulateOrgFreedesktopDBus(DBusTransport *transport, DBusMessage *message)
503 {
504   if(!strcmp(dbus_message_get_member(message), "Hello"))
505     {
506       char* name = NULL;
507
508       name = malloc(snprintf(name, 0, "%llu", ULLONG_MAX) + sizeof(":1."));
509       if(name == NULL)
510         return -1;
511       strcpy(name, ":1.");
512       if(!bus_register_kdbus(&name[3], (DBusTransportKdbus*)transport))
513         goto out;
514       if(!register_kdbus_policy(&name[3], transport, geteuid()))
515         goto out;
516
517       ((DBusTransportKdbus*)transport)->sender = name;
518
519       if(!reply_1_data(message, DBUS_TYPE_STRING, &name, transport->connection))
520         return 0;
521
522     out:
523       free(name);
524     }
525   else
526     return 1;  //send to daemon
527
528   return -1;
529 }
530
531 #if KDBUS_MSG_DECODE_DEBUG == 1
532 static char *msg_id(uint64_t id, char *buf)
533 {
534         if (id == 0)
535                 return "KERNEL";
536         if (id == ~0ULL)
537                 return "BROADCAST";
538         sprintf(buf, "%llu", (unsigned long long)id);
539         return buf;
540 }
541 #endif
542 struct kdbus_enum_table {
543         long long id;
544         const char *name;
545 };
546 #define _STRINGIFY(x) #x
547 #define STRINGIFY(x) _STRINGIFY(x)
548 #define ELEMENTSOF(x) (sizeof(x)/sizeof((x)[0]))
549 #define TABLE(what) static struct kdbus_enum_table kdbus_table_##what[]
550 #define ENUM(_id) { .id=_id, .name=STRINGIFY(_id) }
551 #define LOOKUP(what)                                                            \
552         const char *enum_##what(long long id) {                                 \
553         size_t i; \
554                 for (i = 0; i < ELEMENTSOF(kdbus_table_##what); i++)    \
555                         if (id == kdbus_table_##what[i].id)                     \
556                                 return kdbus_table_##what[i].name;              \
557                 return "UNKNOWN";                                               \
558         }
559 const char *enum_MSG(long long id);
560 TABLE(MSG) = {
561         ENUM(_KDBUS_MSG_NULL),
562         ENUM(KDBUS_MSG_PAYLOAD_VEC),
563         ENUM(KDBUS_MSG_PAYLOAD_OFF),
564         ENUM(KDBUS_MSG_PAYLOAD_MEMFD),
565         ENUM(KDBUS_MSG_FDS),
566         ENUM(KDBUS_MSG_BLOOM),
567         ENUM(KDBUS_MSG_DST_NAME),
568         ENUM(KDBUS_MSG_SRC_CREDS),
569         ENUM(KDBUS_MSG_SRC_PID_COMM),
570         ENUM(KDBUS_MSG_SRC_TID_COMM),
571         ENUM(KDBUS_MSG_SRC_EXE),
572         ENUM(KDBUS_MSG_SRC_CMDLINE),
573         ENUM(KDBUS_MSG_SRC_CGROUP),
574         ENUM(KDBUS_MSG_SRC_CAPS),
575         ENUM(KDBUS_MSG_SRC_SECLABEL),
576         ENUM(KDBUS_MSG_SRC_AUDIT),
577         ENUM(KDBUS_MSG_SRC_NAMES),
578         ENUM(KDBUS_MSG_TIMESTAMP),
579         ENUM(KDBUS_MSG_NAME_ADD),
580         ENUM(KDBUS_MSG_NAME_REMOVE),
581         ENUM(KDBUS_MSG_NAME_CHANGE),
582         ENUM(KDBUS_MSG_ID_ADD),
583         ENUM(KDBUS_MSG_ID_REMOVE),
584         ENUM(KDBUS_MSG_REPLY_TIMEOUT),
585         ENUM(KDBUS_MSG_REPLY_DEAD),
586 };
587 LOOKUP(MSG);
588 const char *enum_PAYLOAD(long long id);
589 TABLE(PAYLOAD) = {
590         ENUM(KDBUS_PAYLOAD_KERNEL),
591         ENUM(KDBUS_PAYLOAD_DBUS1),
592         ENUM(KDBUS_PAYLOAD_GVARIANT),
593 };
594 LOOKUP(PAYLOAD);
595
596 /**
597  * Puts locally generated message into received data buffer.
598  * Use only during receiving phase!
599  *
600  * @param message message to load
601  * @param data place to load message
602  * @return size of message
603  */
604 static int put_message_into_data(DBusMessage *message, char* data)
605 {
606         int ret_size;
607     const DBusString *header;
608     const DBusString *body;
609     int size;
610
611     dbus_message_set_serial(message, 1);
612     dbus_message_lock (message);
613     _dbus_message_get_network_data (message, &header, &body);
614     ret_size = _dbus_string_get_length(header);
615         memcpy(data, _dbus_string_get_const_data(header), ret_size);
616         data += ret_size;
617         size = _dbus_string_get_length(body);
618         memcpy(data, _dbus_string_get_const_data(body), size);
619         ret_size += size;
620
621         return ret_size;
622 }
623
624 /**
625  * Get the length of the kdbus message content.
626  *
627  * @param msg kdbus message
628  * @return the length of the kdbus message
629  */
630 static int kdbus_message_size(const struct kdbus_msg* msg)
631 {
632         const struct kdbus_item *item;
633         int ret_size = 0;
634
635         KDBUS_PART_FOREACH(item, msg, items)
636         {
637                 if (item->size <= KDBUS_PART_HEADER_SIZE)
638                 {
639                         _dbus_verbose("  +%s (%llu bytes) invalid data record\n", enum_MSG(item->type), item->size);
640                         return -1;
641                 }
642                 switch (item->type)
643                 {
644                         case KDBUS_MSG_PAYLOAD_OFF:
645                                 ret_size += item->vec.size;
646                                 break;
647                         case KDBUS_MSG_PAYLOAD_MEMFD:
648                                 ret_size += item->memfd.size;
649                                 break;
650                         default:
651                                 break;
652                 }
653         }
654
655         return ret_size;
656 }
657
658 /**
659  * Decodes kdbus message in order to extract dbus message and put it into data and fds.
660  * Also captures and decodes kdbus error messages and kdbus kernel broadcasts and converts
661  * all of them into dbus messages.
662  *
663  * @param msg kdbus message
664  * @param data place to copy dbus message to
665  * @param kdbus_transport transport
666  * @param fds place to store file descriptors received
667  * @param n_fds place to store quantity of file descriptor
668  * @return number of dbus message's bytes received or -1 on error
669  */
670 static int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, DBusTransportKdbus* kdbus_transport, int* fds, int* n_fds)
671 {
672         const struct kdbus_item *item;
673         int ret_size = 0;
674         DBusMessage *message = NULL;
675         DBusMessageIter args;
676         const char* emptyString = "";
677     const char* pString = NULL;
678         char dbus_name[(unsigned int)(snprintf((char*)pString, 0, "%llu", ULLONG_MAX) + sizeof(":1."))];
679         const char* pDBusName = dbus_name;
680 #if KDBUS_MSG_DECODE_DEBUG == 1
681         char buf[32];
682 #endif
683
684 #if KDBUS_MSG_DECODE_DEBUG == 1
685         _dbus_verbose("MESSAGE: %s (%llu bytes) flags=0x%llx, %s â†’ %s, cookie=%llu, timeout=%llu\n",
686                 enum_PAYLOAD(msg->payload_type), (unsigned long long) msg->size,
687                 (unsigned long long) msg->flags,
688                 msg_id(msg->src_id, buf), msg_id(msg->dst_id, buf),
689                 (unsigned long long) msg->cookie, (unsigned long long) msg->timeout_ns);
690 #endif
691
692         *n_fds = 0;
693
694         KDBUS_PART_FOREACH(item, msg, items)
695         {
696                 if (item->size <= KDBUS_PART_HEADER_SIZE)
697                 {
698                         _dbus_verbose("  +%s (%llu bytes) invalid data record\n", enum_MSG(item->type), item->size);
699                         break;  //??? continue (because dbus will find error) or break
700                 }
701
702                 switch (item->type)
703                 {
704                         case KDBUS_MSG_PAYLOAD_OFF:
705                                 memcpy(data, (char *)kdbus_transport->kdbus_mmap_ptr + item->vec.offset, item->vec.size);
706                                 data += item->vec.size;
707                                 ret_size += item->vec.size;
708
709                                 _dbus_verbose("  +%s (%llu bytes) off=%llu size=%llu\n",
710                                         enum_MSG(item->type), item->size,
711                                         (unsigned long long)item->vec.offset,
712                                         (unsigned long long)item->vec.size);
713                         break;
714
715                         case KDBUS_MSG_PAYLOAD_MEMFD:
716                         {
717                                 char *buf;
718                                 uint64_t size;
719
720                                 size = item->memfd.size;
721                                 _dbus_verbose("memfd.size : %llu\n", (unsigned long long)size);
722
723                                 buf = mmap(NULL, size, PROT_READ , MAP_SHARED, item->memfd.fd, 0);
724                                 if (buf == MAP_FAILED)
725                                 {
726                                         _dbus_verbose("mmap() fd=%i failed:%m", item->memfd.fd);
727                                         return -1;
728                                 }
729
730                                 memcpy(data, buf, size);
731                                 data += size;
732                                 ret_size += size;
733
734                                 munmap(buf, size);
735
736                 _dbus_verbose("  +%s (%llu bytes) off=%llu size=%llu\n",
737                                            enum_MSG(item->type), item->size,
738                                            (unsigned long long)item->vec.offset,
739                                            (unsigned long long)item->vec.size);
740                         break;
741                         }
742
743                         case KDBUS_MSG_FDS:
744                         {
745                                 int i;
746
747                                 *n_fds = (item->size - KDBUS_PART_HEADER_SIZE) / sizeof(int);
748                                 memcpy(fds, item->fds, *n_fds * sizeof(int));
749                     for (i = 0; i < *n_fds; i++)
750                       _dbus_fd_set_close_on_exec(fds[i]);
751                         break;
752                         }
753
754 #if KDBUS_MSG_DECODE_DEBUG == 1
755                         case KDBUS_MSG_SRC_CREDS:
756                                 _dbus_verbose("  +%s (%llu bytes) uid=%lld, gid=%lld, pid=%lld, tid=%lld, starttime=%lld\n",
757                                         enum_MSG(item->type), item->size,
758                                         item->creds.uid, item->creds.gid,
759                                         item->creds.pid, item->creds.tid,
760                                         item->creds.starttime);
761                         break;
762
763                         case KDBUS_MSG_SRC_PID_COMM:
764                         case KDBUS_MSG_SRC_TID_COMM:
765                         case KDBUS_MSG_SRC_EXE:
766                         case KDBUS_MSG_SRC_CGROUP:
767                         case KDBUS_MSG_SRC_SECLABEL:
768                         case KDBUS_MSG_DST_NAME:
769                                 _dbus_verbose("  +%s (%llu bytes) '%s' (%zu)\n",
770                                            enum_MSG(item->type), item->size, item->str, strlen(item->str));
771                                 break;
772
773                         case KDBUS_MSG_SRC_CMDLINE:
774                         case KDBUS_MSG_SRC_NAMES: {
775                                 __u64 size = item->size - KDBUS_PART_HEADER_SIZE;
776                                 const char *str = item->str;
777                                 int count = 0;
778
779                                 _dbus_verbose("  +%s (%llu bytes) ", enum_MSG(item->type), item->size);
780                                 while (size) {
781                                         _dbus_verbose("'%s' ", str);
782                                         size -= strlen(str) + 1;
783                                         str += strlen(str) + 1;
784                                         count++;
785                                 }
786
787                                 _dbus_verbose("(%d string%s)\n", count, (count == 1) ? "" : "s");
788                                 break;
789                         }
790
791                         case KDBUS_MSG_SRC_AUDIT:
792                                 _dbus_verbose("  +%s (%llu bytes) loginuid=%llu sessionid=%llu\n",
793                                            enum_MSG(item->type), item->size,
794                                            (unsigned long long)item->data64[0],
795                                            (unsigned long long)item->data64[1]);
796                                 break;
797
798                         case KDBUS_MSG_SRC_CAPS: {
799                                 int n;
800                                 const uint32_t *cap;
801                                 int i;
802
803                                 _dbus_verbose("  +%s (%llu bytes) len=%llu bytes)\n",
804                                            enum_MSG(item->type), item->size,
805                                            (unsigned long long)item->size - KDBUS_PART_HEADER_SIZE);
806
807                                 cap = item->data32;
808                                 n = (item->size - KDBUS_PART_HEADER_SIZE) / 4 / sizeof(uint32_t);
809
810                                 _dbus_verbose("    CapInh=");
811                                 for (i = 0; i < n; i++)
812                                         _dbus_verbose("%08x", cap[(0 * n) + (n - i - 1)]);
813
814                                 _dbus_verbose(" CapPrm=");
815                                 for (i = 0; i < n; i++)
816                                         _dbus_verbose("%08x", cap[(1 * n) + (n - i - 1)]);
817
818                                 _dbus_verbose(" CapEff=");
819                                 for (i = 0; i < n; i++)
820                                         _dbus_verbose("%08x", cap[(2 * n) + (n - i - 1)]);
821
822                                 _dbus_verbose(" CapInh=");
823                                 for (i = 0; i < n; i++)
824                                         _dbus_verbose("%08x", cap[(3 * n) + (n - i - 1)]);
825                                 _dbus_verbose("\n");
826                                 break;
827                         }
828
829                         case KDBUS_MSG_TIMESTAMP:
830                                 _dbus_verbose("  +%s (%llu bytes) realtime=%lluns monotonic=%lluns\n",
831                                            enum_MSG(item->type), item->size,
832                                            (unsigned long long)item->timestamp.realtime_ns,
833                                            (unsigned long long)item->timestamp.monotonic_ns);
834                                 break;
835 #endif
836
837                         case KDBUS_MSG_REPLY_TIMEOUT:
838                                 _dbus_verbose("  +%s (%llu bytes) cookie=%llu\n",
839                                            enum_MSG(item->type), item->size, msg->cookie_reply);
840
841                                 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NO_REPLY, NULL);
842                                 if(message == NULL)
843                                 {
844                                         ret_size = -1;
845                                         goto out;
846                                 }
847
848                                 ret_size = put_message_into_data(message, data);
849                         break;
850
851                         case KDBUS_MSG_REPLY_DEAD:
852                                 _dbus_verbose("  +%s (%llu bytes) cookie=%llu\n",
853                                            enum_MSG(item->type), item->size, msg->cookie_reply);
854
855                                 message = generate_local_error_message(msg->cookie_reply, DBUS_ERROR_NAME_HAS_NO_OWNER, NULL);
856                                 if(message == NULL)
857                                 {
858                                         ret_size = -1;
859                                         goto out;
860                                 }
861
862                                 ret_size = put_message_into_data(message, data);
863                         break;
864
865                         case KDBUS_MSG_NAME_ADD:
866                                 _dbus_verbose("  +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
867                                         enum_MSG(item->type), (unsigned long long) item->size,
868                                         item->name_change.name, item->name_change.old_id,
869                                         item->name_change.new_id, item->name_change.flags);
870
871                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
872                                 if(message == NULL)
873                                 {
874                                         ret_size = -1;
875                                         goto out;
876                                 }
877
878                                 sprintf(dbus_name,":1.%llu",item->name_change.new_id);
879                                 pString = item->name_change.name;
880                                 _dbus_verbose ("Name added: %s\n", pString);
881                             dbus_message_iter_init_append(message, &args);
882                             ITER_APPEND_STR(pString)
883                             ITER_APPEND_STR(emptyString)
884                             ITER_APPEND_STR(pDBusName)
885                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
886
887                                 ret_size = put_message_into_data(message, data);
888                         break;
889
890                         case KDBUS_MSG_NAME_REMOVE:
891                                 _dbus_verbose("  +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
892                                         enum_MSG(item->type), (unsigned long long) item->size,
893                                         item->name_change.name, item->name_change.old_id,
894                                         item->name_change.new_id, item->name_change.flags);
895
896                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged"); // name of the signal
897                                 if(message == NULL)
898                                 {
899                                         ret_size = -1;
900                                         goto out;
901                                 }
902
903                                 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
904                                 pString = item->name_change.name;
905                                 _dbus_verbose ("Name removed: %s\n", pString);
906                             dbus_message_iter_init_append(message, &args);
907                             ITER_APPEND_STR(pString)
908                             ITER_APPEND_STR(pDBusName)
909                             ITER_APPEND_STR(emptyString)
910                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
911
912                                 ret_size = put_message_into_data(message, data);
913                         break;
914
915                         case KDBUS_MSG_NAME_CHANGE:
916                                 _dbus_verbose("  +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
917                                         enum_MSG(item->type), (unsigned long long) item->size,
918                                         item->name_change.name, item->name_change.old_id,
919                                         item->name_change.new_id, item->name_change.flags);
920
921                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
922                                 if(message == NULL)
923                                 {
924                                         ret_size = -1;
925                                         goto out;
926                                 }
927
928                                 sprintf(dbus_name,":1.%llu",item->name_change.old_id);
929                                 pString = item->name_change.name;
930                                 _dbus_verbose ("Name changed: %s\n", pString);
931                             dbus_message_iter_init_append(message, &args);
932                             ITER_APPEND_STR(pString)
933                             ITER_APPEND_STR(pDBusName)
934                             sprintf(&dbus_name[3],"%llu",item->name_change.new_id);
935                             _dbus_verbose ("New id: %s\n", pDBusName);
936                             ITER_APPEND_STR(pDBusName)
937                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
938
939                                 ret_size = put_message_into_data(message, data);
940                         break;
941
942                         case KDBUS_MSG_ID_ADD:
943                                 _dbus_verbose("  +%s (%llu bytes) id=%llu flags=%llu\n",
944                                            enum_MSG(item->type), (unsigned long long) item->size,
945                                            (unsigned long long) item->id_change.id,
946                                            (unsigned long long) item->id_change.flags);
947
948                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
949                                 if(message == NULL)
950                                 {
951                                         ret_size = -1;
952                                         goto out;
953                                 }
954
955                                 sprintf(dbus_name,":1.%llu",item->id_change.id);
956                             dbus_message_iter_init_append(message, &args);
957                             ITER_APPEND_STR(pDBusName)
958                             ITER_APPEND_STR(emptyString)
959                             ITER_APPEND_STR(pDBusName)
960                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
961
962                                 ret_size = put_message_into_data(message, data);
963                         break;
964
965                         case KDBUS_MSG_ID_REMOVE:
966                                 _dbus_verbose("  +%s (%llu bytes) id=%llu flags=%llu\n",
967                                            enum_MSG(item->type), (unsigned long long) item->size,
968                                            (unsigned long long) item->id_change.id,
969                                            (unsigned long long) item->id_change.flags);
970
971                                 message = dbus_message_new_signal(DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameOwnerChanged");
972                                 if(message == NULL)
973                                 {
974                                         ret_size = -1;
975                                         goto out;
976                                 }
977
978                                 sprintf(dbus_name,":1.%llu",item->id_change.id);
979                             dbus_message_iter_init_append(message, &args);
980                             ITER_APPEND_STR(pDBusName)
981                             ITER_APPEND_STR(pDBusName)
982                             ITER_APPEND_STR(emptyString)
983                                 dbus_message_set_sender(message, DBUS_SERVICE_DBUS);
984
985                                 ret_size = put_message_into_data(message, data);
986                         break;
987 #if KDBUS_MSG_DECODE_DEBUG == 1
988                         default:
989                                 _dbus_verbose("  +%s (%llu bytes)\n", enum_MSG(item->type), item->size);
990                         break;
991 #endif
992                 }
993         }
994
995 #if KDBUS_MSG_DECODE_DEBUG == 1
996
997         if ((char *)item - ((char *)msg + msg->size) >= 8)
998                 _dbus_verbose("invalid padding at end of message\n");
999 #endif
1000
1001 out:
1002         if(message)
1003                 dbus_message_unref(message);
1004         return ret_size;
1005 }
1006
1007 /**
1008  * Reads message from kdbus and puts it into dbus buffer and fds
1009  *
1010  * @param transport transport
1011  * @param buffer place to copy received message to
1012  * @param fds place to store file descriptors sent in the message
1013  * @param n_fds place  to store number of file descriptors
1014  * @return size of received message on success, -1 on error
1015  */
1016 static int kdbus_read_message(DBusTransportKdbus *socket_transport, DBusString *buffer, int* fds, int* n_fds)
1017 {
1018         int ret_size, buf_size;
1019         uint64_t __attribute__ ((__aligned__(8))) offset;
1020         struct kdbus_msg *msg;
1021         char *data;
1022         int start;
1023
1024         start = _dbus_string_get_length (buffer);
1025
1026         again:
1027         if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RECV, &offset) < 0)
1028         {
1029                 if(errno == EINTR)
1030                         goto again;
1031                 _dbus_verbose("kdbus error receiving message: %d (%m)\n", errno);
1032                 _dbus_string_set_length (buffer, start);
1033                 return -1;
1034         }
1035
1036         msg = (struct kdbus_msg *)((char*)socket_transport->kdbus_mmap_ptr + offset);
1037
1038         buf_size = kdbus_message_size(msg);
1039         if (buf_size == -1)
1040         {
1041                 _dbus_verbose("kdbus error - too short message: %d (%m)\n", errno);
1042                 return -1;
1043         }
1044
1045         /* What is the maximum size of the locally generated message?
1046            I just assume 2048 bytes */
1047         buf_size = MAX(buf_size, 2048);
1048
1049         if (!_dbus_string_lengthen (buffer, buf_size))
1050         {
1051                 errno = ENOMEM;
1052                 return -1;
1053         }
1054         data = _dbus_string_get_data_len (buffer, start, buf_size);
1055
1056         ret_size = kdbus_decode_msg(msg, data, socket_transport, fds, n_fds);
1057
1058         if(ret_size == -1) /* error */
1059         {
1060                 _dbus_string_set_length (buffer, start);
1061                 return -1;
1062         }
1063         else if (buf_size != ret_size) /* case of locally generated message */
1064         {
1065                 _dbus_string_set_length (buffer, start + ret_size);
1066         }
1067
1068         again2:
1069         if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_RELEASE, &offset) < 0)
1070         {
1071                 if(errno == EINTR)
1072                         goto again2;
1073                 _dbus_verbose("kdbus error freeing message: %d (%m)\n", errno);
1074                 return -1;
1075         }
1076
1077         return ret_size;
1078 }
1079 /*
1080  * copy-paste from socket transport with needed renames only.
1081  */
1082 static void
1083 free_watches (DBusTransport *transport)
1084 {
1085   DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1086
1087   _dbus_verbose ("start\n");
1088
1089   if (kdbus_transport->read_watch)
1090     {
1091       if (transport->connection)
1092         _dbus_connection_remove_watch_unlocked (transport->connection,
1093                                                 kdbus_transport->read_watch);
1094       _dbus_watch_invalidate (kdbus_transport->read_watch);
1095       _dbus_watch_unref (kdbus_transport->read_watch);
1096       kdbus_transport->read_watch = NULL;
1097     }
1098
1099   if (kdbus_transport->write_watch)
1100     {
1101       if (transport->connection)
1102         _dbus_connection_remove_watch_unlocked (transport->connection,
1103                                                 kdbus_transport->write_watch);
1104       _dbus_watch_invalidate (kdbus_transport->write_watch);
1105       _dbus_watch_unref (kdbus_transport->write_watch);
1106       kdbus_transport->write_watch = NULL;
1107     }
1108
1109   _dbus_verbose ("end\n");
1110 }
1111
1112 /*
1113  * copy-paste from socket transport with needed renames only.
1114  */
1115 static void
1116 transport_finalize (DBusTransport *transport)
1117 {
1118   _dbus_verbose ("\n");
1119
1120   free_watches (transport);
1121
1122   _dbus_transport_finalize_base (transport);
1123
1124   _dbus_assert (((DBusTransportKdbus*) transport)->read_watch == NULL);
1125   _dbus_assert (((DBusTransportKdbus*) transport)->write_watch == NULL);
1126
1127   dbus_free (transport);
1128 }
1129
1130 /*
1131  * copy-paste from socket transport with needed renames only.
1132  */
1133 static void
1134 check_write_watch (DBusTransport *transport)
1135 {
1136   DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1137   dbus_bool_t needed;
1138
1139   if (transport->connection == NULL)
1140     return;
1141
1142   if (transport->disconnected)
1143     {
1144       _dbus_assert (kdbus_transport->write_watch == NULL);
1145       return;
1146     }
1147
1148   _dbus_transport_ref (transport);
1149
1150   needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection);
1151
1152   _dbus_verbose ("check_write_watch(): needed = %d on connection %p watch %p fd = %d outgoing messages exist %d\n",
1153                  needed, transport->connection, kdbus_transport->write_watch,
1154                  kdbus_transport->fd,
1155                  _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1156
1157   _dbus_connection_toggle_watch_unlocked (transport->connection,
1158                                           kdbus_transport->write_watch,
1159                                           needed);
1160
1161   _dbus_transport_unref (transport);
1162 }
1163
1164 /*
1165  * copy-paste from socket transport with needed renames only.
1166  */
1167 static void
1168 check_read_watch (DBusTransport *transport)
1169 {
1170   DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1171   dbus_bool_t need_read_watch;
1172
1173   _dbus_verbose ("fd = %d\n",kdbus_transport->fd);
1174
1175   if (transport->connection == NULL)
1176     return;
1177
1178   if (transport->disconnected)
1179     {
1180       _dbus_assert (kdbus_transport->read_watch == NULL);
1181       return;
1182     }
1183
1184   _dbus_transport_ref (transport);
1185
1186    need_read_watch =
1187       (_dbus_counter_get_size_value (transport->live_messages) < transport->max_live_messages_size) &&
1188       (_dbus_counter_get_unix_fd_value (transport->live_messages) < transport->max_live_messages_unix_fds);
1189
1190   _dbus_verbose ("  setting read watch enabled = %d\n", need_read_watch);
1191   _dbus_connection_toggle_watch_unlocked (transport->connection,
1192                                           kdbus_transport->read_watch,
1193                                           need_read_watch);
1194
1195   _dbus_transport_unref (transport);
1196 }
1197
1198 /*
1199  * copy-paste from socket transport.
1200  */
1201 static void
1202 do_io_error (DBusTransport *transport)
1203 {
1204   _dbus_transport_ref (transport);
1205   _dbus_transport_disconnect (transport);
1206   _dbus_transport_unref (transport);
1207 }
1208
1209 /* returns false on oom */
1210 static dbus_bool_t
1211 do_writing (DBusTransport *transport)
1212 {
1213         DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1214         dbus_bool_t oom;
1215
1216         if (transport->disconnected)
1217     {
1218                 _dbus_verbose ("Not connected, not writing anything\n");
1219                 return TRUE;
1220     }
1221
1222 #if 1
1223         _dbus_verbose ("do_writing(), have_messages = %d, fd = %d\n",
1224                  _dbus_connection_has_messages_to_send_unlocked (transport->connection),
1225                  kdbus_transport->fd);
1226 #endif
1227
1228         oom = FALSE;
1229
1230         while (!transport->disconnected && _dbus_connection_has_messages_to_send_unlocked (transport->connection))
1231     {
1232                 int bytes_written;
1233                 DBusMessage *message;
1234                 const DBusString *header;
1235                 const DBusString *body;
1236                 int total_bytes_to_write;
1237                 const char* pDestination;
1238
1239                 message = _dbus_connection_get_message_to_send (transport->connection);
1240                 _dbus_assert (message != NULL);
1241                 if(dbus_message_get_sender(message) == NULL)  //needed for daemon to pass pending activation messages
1242                 {
1243             dbus_message_unlock(message);
1244             dbus_message_set_sender(message, kdbus_transport->sender);
1245             dbus_message_lock (message);
1246                 }
1247                 _dbus_message_get_network_data (message, &header, &body);
1248                 total_bytes_to_write = _dbus_string_get_length(header) + _dbus_string_get_length(body);
1249                 pDestination = dbus_message_get_destination(message);
1250
1251                 if(pDestination)
1252                 {
1253                         if(!strcmp(pDestination, DBUS_SERVICE_DBUS))
1254                         {
1255                                 if(!strcmp(dbus_message_get_interface(message), DBUS_INTERFACE_DBUS))
1256                                 {
1257                                         int ret;
1258
1259                                         ret = emulateOrgFreedesktopDBus(transport, message);
1260                                         if(ret < 0)
1261                                         {
1262                                                 bytes_written = -1;
1263                                                 goto written;
1264                                         }
1265                                         else if(ret == 0)
1266                                         {
1267                                                 bytes_written = total_bytes_to_write;
1268                                                 goto written;
1269                                         }
1270                                         //else send to "daemon" as to normal recipient
1271                                 }
1272                         }
1273                 }
1274
1275                 if(total_bytes_to_write > kdbus_transport->max_bytes_written_per_iteration)
1276                   return -E2BIG;
1277
1278                 bytes_written = kdbus_write_msg(kdbus_transport, message, pDestination);
1279
1280
1281 written:
1282                 if (bytes_written < 0)
1283                 {
1284                         /* EINTR already handled for us */
1285
1286           /* For some discussion of why we also ignore EPIPE here, see
1287            * http://lists.freedesktop.org/archives/dbus/2008-March/009526.html
1288            */
1289
1290                         if (_dbus_get_is_errno_eagain_or_ewouldblock () || _dbus_get_is_errno_epipe ())
1291                                 goto out;
1292                         else
1293                         {
1294                                 _dbus_verbose ("Error writing to remote app: %s\n", _dbus_strerror_from_errno ());
1295                                 do_io_error (transport);
1296                                 goto out;
1297                         }
1298                 }
1299                 else
1300                 {
1301                         _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
1302                          total_bytes_to_write);
1303
1304                         kdbus_transport->message_bytes_written += bytes_written;
1305
1306                         _dbus_assert (kdbus_transport->message_bytes_written <=
1307                         total_bytes_to_write);
1308
1309                           if (kdbus_transport->message_bytes_written == total_bytes_to_write)
1310                           {
1311                                   kdbus_transport->message_bytes_written = 0;
1312                                   _dbus_connection_message_sent_unlocked (transport->connection,
1313                                                                                                                   message);
1314                           }
1315                 }
1316     }
1317
1318         out:
1319         if (oom)
1320                 return FALSE;
1321         return TRUE;
1322 }
1323
1324 /* returns false on out-of-memory */
1325 static dbus_bool_t
1326 do_reading (DBusTransport *transport)
1327 {
1328   DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1329   DBusString *buffer;
1330   int bytes_read;
1331   dbus_bool_t oom = FALSE;
1332   int *fds, n_fds;
1333
1334   _dbus_verbose ("fd = %d\n",kdbus_transport->fd);
1335
1336  again:
1337
1338   /* See if we've exceeded max messages and need to disable reading */
1339   check_read_watch (transport);
1340
1341   _dbus_assert (kdbus_transport->read_watch != NULL ||
1342                 transport->disconnected);
1343
1344   if (transport->disconnected)
1345     goto out;
1346
1347   if (!dbus_watch_get_enabled (kdbus_transport->read_watch))
1348     return TRUE;
1349
1350   if (!_dbus_message_loader_get_unix_fds(transport->loader, &fds, &n_fds))
1351   {
1352       _dbus_verbose ("Out of memory reading file descriptors\n");
1353       oom = TRUE;
1354       goto out;
1355   }
1356   _dbus_message_loader_get_buffer (transport->loader, &buffer);
1357
1358   bytes_read = kdbus_read_message(kdbus_transport, buffer, fds, &n_fds);
1359
1360   if (bytes_read >= 0 && n_fds > 0)
1361     _dbus_verbose("Read %i unix fds\n", n_fds);
1362
1363   _dbus_message_loader_return_buffer (transport->loader,
1364                                       buffer,
1365                                       bytes_read < 0 ? 0 : bytes_read);
1366   _dbus_message_loader_return_unix_fds(transport->loader, fds, bytes_read < 0 ? 0 : n_fds);
1367
1368   if (bytes_read < 0)
1369     {
1370       /* EINTR already handled for us */
1371
1372       if (_dbus_get_is_errno_enomem ())
1373         {
1374           _dbus_verbose ("Out of memory in read()/do_reading()\n");
1375           oom = TRUE;
1376           goto out;
1377         }
1378       else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1379         goto out;
1380       else
1381         {
1382           _dbus_verbose ("Error reading from remote app: %s\n",
1383                          _dbus_strerror_from_errno ());
1384           do_io_error (transport);
1385           goto out;
1386         }
1387     }
1388   else if (bytes_read == 0)
1389     {
1390       _dbus_verbose ("Disconnected from remote app\n");
1391       do_io_error (transport);
1392       goto out;
1393     }
1394   else
1395     {
1396       _dbus_verbose (" read %d bytes\n", bytes_read);
1397
1398       if (!_dbus_transport_queue_messages (transport))
1399         {
1400           oom = TRUE;
1401           _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
1402           goto out;
1403         }
1404
1405       /* Try reading more data until we get EAGAIN and return, or
1406        * exceed max bytes per iteration.  If in blocking mode of
1407        * course we'll block instead of returning.
1408        */
1409       goto again;
1410     }
1411
1412  out:
1413   if (oom)
1414     return FALSE;
1415   return TRUE;
1416 }
1417
1418 /*
1419  * copy-paste from socket transport.
1420  */
1421 static dbus_bool_t
1422 unix_error_with_read_to_come (DBusTransport *itransport,
1423                               DBusWatch     *watch,
1424                               unsigned int   flags)
1425 {
1426    DBusTransportKdbus *transport = (DBusTransportKdbus *) itransport;
1427
1428    if (!((flags & DBUS_WATCH_HANGUP) || (flags & DBUS_WATCH_ERROR)))
1429       return FALSE;
1430
1431   /* If we have a read watch enabled ...
1432      we -might have data incoming ... => handle the HANGUP there */
1433    if (watch != transport->read_watch && _dbus_watch_get_enabled (transport->read_watch))
1434       return FALSE;
1435
1436    return TRUE;
1437 }
1438
1439 /*
1440  * copy-paste from socket transport with needed renames only.
1441  */
1442 static dbus_bool_t
1443 kdbus_handle_watch (DBusTransport *transport,
1444                    DBusWatch     *watch,
1445                    unsigned int   flags)
1446 {
1447   DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1448
1449   _dbus_assert (watch == kdbus_transport->read_watch ||
1450                 watch == kdbus_transport->write_watch);
1451   _dbus_assert (watch != NULL);
1452
1453   /* If we hit an error here on a write watch, don't disconnect the transport yet because data can
1454    * still be in the buffer and do_reading may need several iteration to read
1455    * it all (because of its max_bytes_read_per_iteration limit).
1456    */
1457   if (!(flags & DBUS_WATCH_READABLE) && unix_error_with_read_to_come (transport, watch, flags))
1458     {
1459       _dbus_verbose ("Hang up or error on watch\n");
1460       _dbus_transport_disconnect (transport);
1461       return TRUE;
1462     }
1463
1464   if (watch == kdbus_transport->read_watch &&
1465       (flags & DBUS_WATCH_READABLE))
1466     {
1467       _dbus_verbose ("handling read watch %p flags = %x\n",
1468                      watch, flags);
1469
1470           if (!do_reading (transport))
1471             {
1472               _dbus_verbose ("no memory to read\n");
1473               return FALSE;
1474             }
1475
1476     }
1477   else if (watch == kdbus_transport->write_watch &&
1478            (flags & DBUS_WATCH_WRITABLE))
1479     {
1480       _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n",
1481                      _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1482
1483       if (!do_writing (transport))
1484         {
1485           _dbus_verbose ("no memory to write\n");
1486           return FALSE;
1487         }
1488
1489       /* See if we still need the write watch */
1490       check_write_watch (transport);
1491     }
1492
1493   return TRUE;
1494 }
1495
1496 /*
1497  * copy-paste from socket transport with needed renames only.
1498  */
1499 static void
1500 kdbus_disconnect (DBusTransport *transport)
1501 {
1502   DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1503
1504   _dbus_verbose ("\n");
1505
1506   free_watches (transport);
1507
1508   _dbus_close_socket (kdbus_transport->fd, NULL);
1509   kdbus_transport->fd = -1;
1510 }
1511
1512 /*
1513  * copy-paste from socket transport with needed renames only.
1514  */
1515 static dbus_bool_t
1516 kdbus_connection_set (DBusTransport *transport)
1517 {
1518   DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1519
1520   dbus_connection_set_is_authenticated(transport->connection); //now we don't have authentication in kdbus
1521
1522   _dbus_watch_set_handler (kdbus_transport->write_watch,
1523                            _dbus_connection_handle_watch,
1524                            transport->connection, NULL);
1525
1526   _dbus_watch_set_handler (kdbus_transport->read_watch,
1527                            _dbus_connection_handle_watch,
1528                            transport->connection, NULL);
1529
1530   if (!_dbus_connection_add_watch_unlocked (transport->connection,
1531                                             kdbus_transport->write_watch))
1532     return FALSE;
1533
1534   if (!_dbus_connection_add_watch_unlocked (transport->connection,
1535                                             kdbus_transport->read_watch))
1536     {
1537       _dbus_connection_remove_watch_unlocked (transport->connection,
1538                                               kdbus_transport->write_watch);
1539       return FALSE;
1540     }
1541
1542   check_read_watch (transport);
1543   check_write_watch (transport);
1544
1545   return TRUE;
1546 }
1547
1548 /**  original dbus copy-pasted comment
1549  * @todo We need to have a way to wake up the select sleep if
1550  * a new iteration request comes in with a flag (read/write) that
1551  * we're not currently serving. Otherwise a call that just reads
1552  * could block a write call forever (if there are no incoming
1553  * messages).
1554  */
1555 static  void
1556 kdbus_do_iteration (DBusTransport *transport,
1557                    unsigned int   flags,
1558                    int            timeout_milliseconds)
1559 {
1560         DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1561         DBusPollFD poll_fd;
1562         int poll_res;
1563         int poll_timeout;
1564
1565         _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p fd = %d\n",
1566                  flags & DBUS_ITERATION_DO_READING ? "read" : "",
1567                  flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
1568                  timeout_milliseconds,
1569                  kdbus_transport->read_watch,
1570                  kdbus_transport->write_watch,
1571                  kdbus_transport->fd);
1572
1573   /* the passed in DO_READING/DO_WRITING flags indicate whether to
1574    * read/write messages, but regardless of those we may need to block
1575    * for reading/writing to do auth.  But if we do reading for auth,
1576    * we don't want to read any messages yet if not given DO_READING.
1577    */
1578
1579    poll_fd.fd = kdbus_transport->fd;
1580    poll_fd.events = 0;
1581
1582    if (_dbus_transport_try_to_authenticate (transport))
1583    {
1584       /* This is kind of a hack; if we have stuff to write, then try
1585        * to avoid the poll. This is probably about a 5% speedup on an
1586        * echo client/server.
1587        *
1588        * If both reading and writing were requested, we want to avoid this
1589        * since it could have funky effects:
1590        *   - both ends spinning waiting for the other one to read
1591        *     data so they can finish writing
1592        *   - prioritizing all writing ahead of reading
1593        */
1594       if ((flags & DBUS_ITERATION_DO_WRITING) &&
1595           !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) &&
1596           !transport->disconnected &&
1597           _dbus_connection_has_messages_to_send_unlocked (transport->connection))
1598       {
1599          do_writing (transport);
1600
1601          if (transport->disconnected ||
1602               !_dbus_connection_has_messages_to_send_unlocked (transport->connection))
1603             goto out;
1604       }
1605
1606       /* If we get here, we decided to do the poll() after all */
1607       _dbus_assert (kdbus_transport->read_watch);
1608       if (flags & DBUS_ITERATION_DO_READING)
1609              poll_fd.events |= _DBUS_POLLIN;
1610
1611       _dbus_assert (kdbus_transport->write_watch);
1612       if (flags & DBUS_ITERATION_DO_WRITING)
1613          poll_fd.events |= _DBUS_POLLOUT;
1614    }
1615    else
1616    {
1617       DBusAuthState auth_state;
1618
1619       auth_state = _dbus_auth_do_work (transport->auth);
1620
1621       if (transport->receive_credentials_pending || auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT)
1622              poll_fd.events |= _DBUS_POLLIN;
1623
1624       if (transport->send_credentials_pending || auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND)
1625              poll_fd.events |= _DBUS_POLLOUT;
1626    }
1627
1628    if (poll_fd.events)
1629    {
1630       if (flags & DBUS_ITERATION_BLOCK)
1631              poll_timeout = timeout_milliseconds;
1632       else
1633              poll_timeout = 0;
1634
1635       /* For blocking selects we drop the connection lock here
1636        * to avoid blocking out connection access during a potentially
1637        * indefinite blocking call. The io path is still protected
1638        * by the io_path_cond condvar, so we won't reenter this.
1639        */
1640       if (flags & DBUS_ITERATION_BLOCK)
1641       {
1642          _dbus_verbose ("unlock pre poll\n");
1643          _dbus_connection_unlock (transport->connection);
1644       }
1645
1646     again:
1647       poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
1648
1649       if (poll_res < 0 && _dbus_get_is_errno_eintr ())
1650       {
1651          _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
1652          goto again;
1653       }
1654
1655       if (flags & DBUS_ITERATION_BLOCK)
1656       {
1657          _dbus_verbose ("lock post poll\n");
1658          _dbus_connection_lock (transport->connection);
1659       }
1660
1661       if (poll_res >= 0)
1662       {
1663          if (poll_res == 0)
1664             poll_fd.revents = 0; /* some concern that posix does not guarantee this;
1665                                   * valgrind flags it as an error. though it probably
1666                                   * is guaranteed on linux at least.
1667                                   */
1668
1669          if (poll_fd.revents & _DBUS_POLLERR)
1670             do_io_error (transport);
1671          else
1672          {
1673             dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
1674             dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0;
1675
1676             _dbus_verbose ("in iteration, need_read=%d need_write=%d\n",
1677                              need_read, need_write);
1678
1679             if (need_read && (flags & DBUS_ITERATION_DO_READING))
1680                do_reading (transport);
1681             if (need_write && (flags & DBUS_ITERATION_DO_WRITING))
1682                do_writing (transport);
1683          }
1684       }
1685       else
1686          _dbus_verbose ("Error from _dbus_poll(): %s\n", _dbus_strerror_from_errno ());
1687    }
1688
1689  out:
1690   /* We need to install the write watch only if we did not
1691    * successfully write everything. Note we need to be careful that we
1692    * don't call check_write_watch *before* do_writing, since it's
1693    * inefficient to add the write watch, and we can avoid it most of
1694    * the time since we can write immediately.
1695    *
1696    * However, we MUST always call check_write_watch(); DBusConnection code
1697    * relies on the fact that running an iteration will notice that
1698    * messages are pending.
1699    */
1700    check_write_watch (transport);
1701
1702    _dbus_verbose (" ... leaving do_iteration()\n");
1703 }
1704
1705 /*
1706  * copy-paste from socket transport with needed renames only.
1707  */
1708 static void
1709 kdbus_live_messages_changed (DBusTransport *transport)
1710 {
1711   /* See if we should look for incoming messages again */
1712   check_read_watch (transport);
1713 }
1714
1715 static dbus_bool_t
1716 kdbus_get_kdbus_fd (DBusTransport *transport,
1717                       int           *fd_p)
1718 {
1719   DBusTransportKdbus *kdbus_transport = (DBusTransportKdbus*) transport;
1720
1721   *fd_p = kdbus_transport->fd;
1722
1723   return TRUE;
1724 }
1725
1726 static const DBusTransportVTable kdbus_vtable = {
1727   transport_finalize,
1728   kdbus_handle_watch,
1729   kdbus_disconnect,
1730   kdbus_connection_set,
1731   kdbus_do_iteration,
1732   kdbus_live_messages_changed,
1733   kdbus_get_kdbus_fd
1734 };
1735
1736 /**
1737  * Creates a new transport for the given kdbus file descriptor.  The file
1738  * descriptor must be nonblocking.
1739  *
1740  * @param fd the file descriptor.
1741  * @param address the transport's address
1742  * @returns the new transport, or #NULL if no memory.
1743  */
1744 static DBusTransport*
1745 _dbus_transport_new_kdbus_transport (int fd, const DBusString *address)
1746 {
1747         DBusTransportKdbus *kdbus_transport;
1748
1749   kdbus_transport = dbus_new0 (DBusTransportKdbus, 1);
1750   if (kdbus_transport == NULL)
1751     return NULL;
1752
1753   kdbus_transport->write_watch = _dbus_watch_new (fd,
1754                                                  DBUS_WATCH_WRITABLE,
1755                                                  FALSE,
1756                                                  NULL, NULL, NULL);
1757   if (kdbus_transport->write_watch == NULL)
1758     goto failed_2;
1759
1760   kdbus_transport->read_watch = _dbus_watch_new (fd,
1761                                                 DBUS_WATCH_READABLE,
1762                                                 FALSE,
1763                                                 NULL, NULL, NULL);
1764   if (kdbus_transport->read_watch == NULL)
1765     goto failed_3;
1766
1767   if (!_dbus_transport_init_base (&kdbus_transport->base,
1768                                   &kdbus_vtable,
1769                                   NULL, address))
1770     goto failed_4;
1771
1772   kdbus_transport->fd = fd;
1773   kdbus_transport->message_bytes_written = 0;
1774
1775   /* These values should probably be tunable or something. */
1776   kdbus_transport->max_bytes_read_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
1777   kdbus_transport->max_bytes_written_per_iteration = DBUS_MAXIMUM_MESSAGE_LENGTH;
1778
1779   kdbus_transport->kdbus_mmap_ptr = NULL;
1780   kdbus_transport->memfd = -1;
1781   
1782   return (DBusTransport*) kdbus_transport;
1783
1784  failed_4:
1785   _dbus_watch_invalidate (kdbus_transport->read_watch);
1786   _dbus_watch_unref (kdbus_transport->read_watch);
1787  failed_3:
1788   _dbus_watch_invalidate (kdbus_transport->write_watch);
1789   _dbus_watch_unref (kdbus_transport->write_watch);
1790  failed_2:
1791   dbus_free (kdbus_transport);
1792   return NULL;
1793 }
1794
1795 /**
1796  * Opens a connection to the kdbus bus
1797  *
1798  * This will set FD_CLOEXEC for the socket returned.
1799  *
1800  * @param path the path to UNIX domain socket
1801  * @param error return location for error code
1802  * @returns connection file descriptor or -1 on error
1803  */
1804 static int _dbus_connect_kdbus (const char *path, DBusError *error)
1805 {
1806         int fd;
1807
1808         _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1809         _dbus_verbose ("connecting to kdbus bus %s\n", path);
1810
1811         fd = open(path, O_RDWR|O_CLOEXEC|O_NONBLOCK);
1812         if (fd < 0)
1813                 dbus_set_error(error, _dbus_error_from_errno (errno), "Failed to open file descriptor: %s", _dbus_strerror (errno));
1814
1815         return fd;
1816 }
1817
1818 /**
1819  * Creates a new transport for kdbus.
1820  * This creates a client-side of a transport.
1821  *
1822  * @param path the path to the bus.
1823  * @param error address where an error can be returned.
1824  * @returns a new transport, or #NULL on failure.
1825  */
1826 static DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error)
1827 {
1828         int fd;
1829         DBusTransport *transport;
1830         DBusString address;
1831
1832         _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1833
1834         if (!_dbus_string_init (&address))
1835     {
1836                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1837                 return NULL;
1838     }
1839
1840         fd = -1;
1841
1842         if ((!_dbus_string_append (&address, "kdbus:path=")) || (!_dbus_string_append (&address, path)))
1843     {
1844                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1845                 goto failed_0;
1846     }
1847
1848         fd = _dbus_connect_kdbus (path, error);
1849         if (fd < 0)
1850     {
1851                 _DBUS_ASSERT_ERROR_IS_SET (error);
1852                 goto failed_0;
1853     }
1854
1855         _dbus_verbose ("Successfully connected to kdbus bus %s\n", path);
1856
1857         transport = _dbus_transport_new_kdbus_transport (fd, &address);
1858         if (transport == NULL)
1859     {
1860                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1861                 goto failed_1;
1862     }
1863
1864         _dbus_string_free (&address);
1865
1866         return transport;
1867
1868         failed_1:
1869                 _dbus_close_socket (fd, NULL);
1870         failed_0:
1871                 _dbus_string_free (&address);
1872         return NULL;
1873 }
1874
1875
1876 /**
1877  * Opens kdbus transport if method from address entry is kdbus
1878  *
1879  * @param entry the address entry to try opening
1880  * @param transport_p return location for the opened transport
1881  * @param error error to be set
1882  * @returns result of the attempt
1883  */
1884 DBusTransportOpenResult _dbus_transport_open_kdbus(DBusAddressEntry  *entry,
1885                                                            DBusTransport    **transport_p,
1886                                                            DBusError         *error)
1887 {
1888         const char *method;
1889
1890         method = dbus_address_entry_get_method (entry);
1891         _dbus_assert (method != NULL);
1892
1893         if (strcmp (method, "kdbus") == 0)
1894     {
1895                 const char *path = dbus_address_entry_get_value (entry, "path");
1896
1897                 if (path == NULL)
1898         {
1899                         _dbus_set_bad_address (error, "kdbus", "path", NULL);
1900                         return DBUS_TRANSPORT_OPEN_BAD_ADDRESS;
1901         }
1902
1903         *transport_p = _dbus_transport_new_for_kdbus (path, error);
1904
1905         if (*transport_p == NULL)
1906         {
1907                 _DBUS_ASSERT_ERROR_IS_SET (error);
1908                 return DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT;
1909         }
1910         else
1911         {
1912                 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1913                 return DBUS_TRANSPORT_OPEN_OK;
1914         }
1915     }
1916         else
1917     {
1918                 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1919                 return DBUS_TRANSPORT_OPEN_NOT_HANDLED;
1920     }
1921 }