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