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