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