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