Working - simple message passing with serverClient signal send-receive
[platform/upstream/dbus.git] / dbus / dbus-transport-kdbus.c
1 /*
2  * dbus-transport-kdbus.c
3  *
4  * Transport layer using kdbus
5  *
6  *  Created on: Jun 20, 2013
7  *      Author: r.pajak
8  *
9  *
10  */
11
12 #include "dbus-transport.h"
13 #include "dbus-transport-kdbus.h"
14 #include <dbus/dbus-transport-protected.h>
15 #include "dbus-connection-internal.h"
16 #include "kdbus.h"
17 #include "dbus-watch.h"
18 #include "dbus-errors.h"
19 #include "dbus-bus.h"
20 #include <fcntl.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <sys/ioctl.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <sys/mman.h>
29 #include <linux/types.h>
30
31 #define KDBUS_ALIGN8(l) (((l) + 7) & ~7)
32 #define KDBUS_PART_HEADER_SIZE offsetof(struct kdbus_item, data)
33 #define KDBUS_ITEM_SIZE(s) KDBUS_ALIGN8((s) + KDBUS_PART_HEADER_SIZE)
34
35 #define KDBUS_PART_NEXT(part) \
36         (typeof(part))(((uint8_t *)part) + KDBUS_ALIGN8((part)->size))
37 #define KDBUS_PART_FOREACH(part, head, first)                           \
38         for (part = (head)->first;                                      \
39              (uint8_t *)(part) < (uint8_t *)(head) + (head)->size;      \
40              part = KDBUS_PART_NEXT(part))
41 #define POOL_SIZE (16 * 1024LU * 1024LU)
42
43 /*struct and type below copied from dbus_transport_socket.c
44  * needed for _dbus_transport_new_for_socket_kdbus and kdbus_vtable(?)
45  * todo maybe DBusTransportSocket and _dbus_transport_new_for_socket_kdbus not needed here -
46  * maybe only static const DBusTransportVTable implementation will be enough
47  */
48
49 /**
50  * Opaque object representing a socket file descriptor transport.
51  */
52 typedef struct DBusTransportSocket DBusTransportSocket;
53
54 /**
55  * Implementation details of DBusTransportSocket. All members are private.
56  */
57 struct DBusTransportSocket
58 {
59   DBusTransport base;                   /**< Parent instance */
60   int fd;                               /**< File descriptor. */
61   DBusWatch *read_watch;                /**< Watch for readability. */
62   DBusWatch *write_watch;               /**< Watch for writability. */
63
64   int max_bytes_read_per_iteration;     /**< To avoid blocking too long. */
65   int max_bytes_written_per_iteration;  /**< To avoid blocking too long. */
66
67   int message_bytes_written;            /**< Number of bytes of current
68                                          *   outgoing message that have
69                                          *   been written.
70                                          */
71   DBusString encoded_outgoing;          /**< Encoded version of current
72                                          *   outgoing message.
73                                          */
74   DBusString encoded_incoming;          /**< Encoded version of current
75                                          *   incoming data.
76                                          */
77   void* kdbus_mmap_ptr;
78 };
79
80
81 //prototypes of local functions, needed for compiler
82 int _dbus_connect_kdbus (const char *path, DBusError *error);
83 DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error);
84 DBusTransport* _dbus_transport_new_for_socket_kdbus (int fd, const DBusString *server_guid, const DBusString *address);
85 struct kdbus_policy *make_policy_name(const char *name);
86 struct kdbus_policy *make_policy_access(__u64 type, __u64 bits, __u64 id);
87 void append_policy(struct kdbus_cmd_policy *cmd_policy, struct kdbus_policy *policy, __u64 max_size);
88 int kdbus_write_msg(DBusConnection *connection, DBusMessage *message, int fd);
89 int kdbus_write_msg_encoded(DBusMessage *message, DBusTransportSocket *socket_transport);
90 dbus_bool_t kdbus_mmap(DBusTransport* transport);
91 int kdbus_read_message(DBusTransportSocket *socket_transport, DBusString *buffer);
92 int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, void* mmap_ptr);
93
94 static dbus_bool_t
95 socket_get_socket_fd (DBusTransport *transport,
96                       int           *fd_p)
97 {
98   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
99
100   *fd_p = socket_transport->fd;
101
102   return TRUE;
103 }
104
105 int kdbus_write_msg(DBusConnection *connection, DBusMessage *message, int fd)
106 {
107         struct kdbus_msg *msg;
108         struct kdbus_item *item;
109         uint64_t size;
110         const char *name;
111         uint64_t dst_id = KDBUS_DST_ID_BROADCAST;
112     const DBusString *header;
113     const DBusString *body;
114     uint64_t ret_size;
115
116     uint64_t i;
117
118     if((name = dbus_message_get_destination(message)))
119     {
120         _dbus_verbose ("do writing destination: %s\n", name); //todo can be removed at the end
121         if((name[0] == '1') && (name[1] == ':'))
122         {
123                 dst_id = strtoll(&name[2], NULL, 10);
124                 _dbus_verbose ("do writing uniqe id: %lu\n", dst_id); //todo can be removed at the end
125                 name = NULL;
126         }
127     }
128
129     _dbus_message_get_network_data (message, &header, &body);
130     ret_size = (uint64_t)_dbus_string_get_length(header);
131
132     fprintf (stderr, "\nheader:\n");
133     for(i=0; i < ret_size; i++)
134     {
135         fprintf (stderr, "%02x", _dbus_string_get_byte(header,i));
136     }
137     fprintf (stderr, "\nret size: %lu, i: %lu\n", ret_size, i);
138
139     _dbus_verbose("padding bytes for header: %lu \n", KDBUS_ALIGN8(ret_size) - ret_size);
140
141     size = sizeof(struct kdbus_msg);
142         size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
143         if(KDBUS_ALIGN8(ret_size) - ret_size)  //if padding needed
144                 size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));  //additional structure for padding null bytes
145         size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
146
147         if (dst_id == KDBUS_DST_ID_BROADCAST)
148                 size += KDBUS_PART_HEADER_SIZE + 64;
149
150         if (name)
151                 size += KDBUS_ITEM_SIZE(strlen(name) + 1);
152
153         msg = malloc(size);
154         if (!msg)
155         {
156                 _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
157                 return -1;
158         }
159
160         memset(msg, 0, size);
161         msg->size = size;
162         msg->src_id = strtoll(dbus_bus_get_unique_name(connection), NULL , 10);
163         _dbus_verbose("sending msg, src_id=%llu\n", msg->src_id);
164         msg->dst_id = name ? 0 : dst_id;
165         msg->cookie = dbus_message_get_serial(message);
166         msg->payload_type = KDBUS_PAYLOAD_DBUS1;
167
168         item = msg->items;
169
170         if (name)
171         {
172                 item->type = KDBUS_MSG_DST_NAME;
173                 item->size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1;
174                 strcpy(item->str, name);
175                 item = KDBUS_PART_NEXT(item);
176         }
177
178         item->type = KDBUS_MSG_PAYLOAD_VEC;
179         item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec);
180         item->vec.address = (uint64_t)_dbus_string_get_const_data(header);
181         item->vec.size = ret_size;
182         item = KDBUS_PART_NEXT(item);
183
184
185
186         if(KDBUS_ALIGN8(ret_size) - ret_size)
187         {
188                 item->type = KDBUS_MSG_PAYLOAD_VEC;
189                 item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec);
190                 item->vec.address = (uint64_t)NULL;
191                 item->vec.size = KDBUS_ALIGN8(ret_size) - ret_size;
192                 item = KDBUS_PART_NEXT(item);
193         }
194
195         item->type = KDBUS_MSG_PAYLOAD_VEC;
196         item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec);
197         item->vec.address = (uint64_t)_dbus_string_get_const_data(body);
198         item->vec.size = (uint64_t)_dbus_string_get_length(body);
199         ret_size += item->vec.size;
200
201     fprintf (stderr, "\nbody:\n");
202     for(i=0; i < item->vec.size; i++)
203     {
204         fprintf (stderr, "%02x", _dbus_string_get_byte(body,i));
205     }
206     fprintf (stderr, "\nitem->vec.size: %llu, i: %lu\n", item->vec.size, i);
207
208
209         item = KDBUS_PART_NEXT(item);
210
211
212
213         if (dst_id == KDBUS_DST_ID_BROADCAST)
214         {
215                 item->type = KDBUS_MSG_BLOOM;
216                 item->size = KDBUS_PART_HEADER_SIZE + 64;
217         }
218
219         again:
220         if (ioctl(fd, KDBUS_CMD_MSG_SEND, msg))
221         {
222                 if(errno == EINTR)
223                         goto again;
224                 _dbus_verbose("kdbus error sending message: err %d (%m)\n", errno);
225                 return -1;
226         }
227
228         free(msg);
229
230         return ret_size;
231 }
232
233 int kdbus_write_msg_encoded(DBusMessage *message, DBusTransportSocket *socket_transport)
234 {
235         struct kdbus_msg *msg;
236         struct kdbus_item *item;
237         uint64_t size;
238         const char *name;
239         uint64_t dst_id = KDBUS_DST_ID_BROADCAST;
240     uint64_t ret_size;
241
242     if((name = dbus_message_get_destination(message)))
243     {
244         _dbus_verbose ("do writing encoded message destination: %s\n", name); //todo can be removed at the end
245         if((name[0] == '1') && (name[1] == ':'))
246         {
247                 dst_id = strtoll(&name[2], NULL, 10);
248                 _dbus_verbose ("do writing encoded message uniqe id form name: %lu\n", dst_id); //todo can be removed at the end
249                 name = NULL;
250         }
251     }
252
253     size = sizeof(struct kdbus_msg);
254         size += KDBUS_ITEM_SIZE(sizeof(struct kdbus_vec));
255
256         if (dst_id == KDBUS_DST_ID_BROADCAST)
257                 size += KDBUS_PART_HEADER_SIZE + 64;
258
259         if (name)
260                 size += KDBUS_ITEM_SIZE(strlen(name) + 1);
261
262         msg = malloc(size);
263         if (!msg)
264         {
265                 _dbus_verbose("Error allocating memory for: %s,%s\n", _dbus_strerror (errno), _dbus_error_from_errno (errno));
266                 return -1;
267         }
268
269         memset(msg, 0, size);
270         msg->size = size;
271         msg->src_id = strtoll(dbus_bus_get_unique_name(socket_transport->base.connection), NULL , 10);
272         _dbus_verbose("sending encoded msg, src_id=%llu\n", msg->src_id);
273         msg->dst_id = name ? 0 : dst_id;
274         msg->cookie = dbus_message_get_serial(message);
275         msg->payload_type = KDBUS_PAYLOAD_DBUS1;
276
277         item = msg->items;
278
279         if (name)
280         {
281                 item->type = KDBUS_MSG_DST_NAME;
282                 item->size = KDBUS_PART_HEADER_SIZE + strlen(name) + 1;
283                 strcpy(item->str, name);
284                 item = KDBUS_PART_NEXT(item);
285         }
286
287         item->type = KDBUS_MSG_PAYLOAD_VEC;
288         item->size = KDBUS_PART_HEADER_SIZE + sizeof(struct kdbus_vec);
289         item->vec.address = (uint64_t)&socket_transport->encoded_outgoing;
290         item->vec.size = _dbus_string_get_length (&socket_transport->encoded_outgoing);
291         item = KDBUS_PART_NEXT(item);
292
293         if (dst_id == KDBUS_DST_ID_BROADCAST)
294         {
295                 item->type = KDBUS_MSG_BLOOM;
296                 item->size = KDBUS_PART_HEADER_SIZE + 64;
297         }
298
299         again:
300         if (ioctl(socket_transport->fd, KDBUS_CMD_MSG_SEND, msg))
301         {
302                 if(errno == EINTR)
303                         goto again;
304                 _dbus_verbose("error sending encoded message: err %d (%m)\n", errno);
305                 return -1;
306         }
307
308         free(msg);
309
310         return ret_size;
311 }
312
313 //todo functions from kdbus-utli.c for printing messages - maybe to remove at the end
314 char *msg_id(uint64_t id, char *buf);
315 char *msg_id(uint64_t id, char *buf)
316 {
317         if (id == 0)
318                 return "KERNEL";
319         if (id == ~0ULL)
320                 return "BROADCAST";
321         sprintf(buf, "%llu", (unsigned long long)id);
322         return buf;
323 }
324
325 struct kdbus_enum_table {
326         long long id;
327         const char *name;
328 };
329 #define _STRINGIFY(x) #x
330 #define STRINGIFY(x) _STRINGIFY(x)
331 #define ELEMENTSOF(x) (sizeof(x)/sizeof((x)[0]))
332 #define TABLE(what) static struct kdbus_enum_table kdbus_table_##what[]
333 #define ENUM(_id) { .id=_id, .name=STRINGIFY(_id) }
334 #define LOOKUP(what)                                                            \
335         const char *enum_##what(long long id) {                                 \
336         size_t i; \
337                 for (i = 0; i < ELEMENTSOF(kdbus_table_##what); i++)    \
338                         if (id == kdbus_table_##what[i].id)                     \
339                                 return kdbus_table_##what[i].name;              \
340                 return "UNKNOWN";                                               \
341         }
342 const char *enum_MSG(long long id);
343 TABLE(MSG) = {
344         ENUM(_KDBUS_MSG_NULL),
345         ENUM(KDBUS_MSG_PAYLOAD_VEC),
346         ENUM(KDBUS_MSG_PAYLOAD_OFF),
347         ENUM(KDBUS_MSG_PAYLOAD_MEMFD),
348         ENUM(KDBUS_MSG_FDS),
349         ENUM(KDBUS_MSG_BLOOM),
350         ENUM(KDBUS_MSG_DST_NAME),
351         ENUM(KDBUS_MSG_SRC_CREDS),
352         ENUM(KDBUS_MSG_SRC_PID_COMM),
353         ENUM(KDBUS_MSG_SRC_TID_COMM),
354         ENUM(KDBUS_MSG_SRC_EXE),
355         ENUM(KDBUS_MSG_SRC_CMDLINE),
356         ENUM(KDBUS_MSG_SRC_CGROUP),
357         ENUM(KDBUS_MSG_SRC_CAPS),
358         ENUM(KDBUS_MSG_SRC_SECLABEL),
359         ENUM(KDBUS_MSG_SRC_AUDIT),
360         ENUM(KDBUS_MSG_SRC_NAMES),
361         ENUM(KDBUS_MSG_TIMESTAMP),
362         ENUM(KDBUS_MSG_NAME_ADD),
363         ENUM(KDBUS_MSG_NAME_REMOVE),
364         ENUM(KDBUS_MSG_NAME_CHANGE),
365         ENUM(KDBUS_MSG_ID_ADD),
366         ENUM(KDBUS_MSG_ID_REMOVE),
367         ENUM(KDBUS_MSG_REPLY_TIMEOUT),
368         ENUM(KDBUS_MSG_REPLY_DEAD),
369 };
370 LOOKUP(MSG);
371 const char *enum_PAYLOAD(long long id);
372 TABLE(PAYLOAD) = {
373         ENUM(KDBUS_PAYLOAD_KERNEL),
374         ENUM(KDBUS_PAYLOAD_DBUS1),
375         ENUM(KDBUS_PAYLOAD_GVARIANT),
376 };
377 LOOKUP(PAYLOAD);
378
379   //todo handling of all msg items
380 int kdbus_decode_msg(const struct kdbus_msg* msg, char *data, void* mmap_ptr)
381 {
382         const struct kdbus_item *item = msg->items;
383         char buf[32];
384         int ret_size = 0;
385
386         _dbus_verbose("MESSAGE: %s (%llu bytes) flags=0x%llx, %s â†’ %s, cookie=%llu, timeout=%llu\n",
387                 enum_PAYLOAD(msg->payload_type), (unsigned long long) msg->size,
388                 (unsigned long long) msg->flags,
389                 msg_id(msg->src_id, buf), msg_id(msg->dst_id, buf),
390                 (unsigned long long) msg->cookie, (unsigned long long) msg->timeout_ns);
391
392         KDBUS_PART_FOREACH(item, msg, items)
393         {
394                 if (item->size <= KDBUS_PART_HEADER_SIZE) {
395                         _dbus_verbose("  +%s (%llu bytes) invalid data record\n", enum_MSG(item->type), item->size);
396                         break;  //todo to be discovered and rewritten
397                 }
398
399                 switch (item->type)
400                 {
401                         case KDBUS_MSG_PAYLOAD_OFF:
402                         {
403                                 char *s;
404
405                                 if (item->vec.offset == ~0ULL)
406                                         s = "[padding bytes]";
407                                 else
408                                 {
409 //                                      uint64_t i;
410
411                                         s = (char *)mmap_ptr + item->vec.offset;
412                                 /*      fprintf(stderr,"\nmmap: %lu", (uint64_t)mmap_ptr);
413                                         fprintf (stderr, "\nheader: %llu\n", item->vec.size);
414                                     for(i=0; i < item->vec.size; i++)
415                                     {
416                                         fprintf (stderr, "%02x", (int)s[i]);
417                                     }
418                                     fprintf (stderr, "\nret size: %llu, i: %lu\n", item->vec.size, i);*/
419
420                                         memcpy(data, s, item->vec.size);
421                                         data += item->vec.size;
422                                         ret_size += item->vec.size;
423                                 }
424
425                                 _dbus_verbose("  +%s (%llu bytes) off=%llu size=%llu '%s'\n",
426                                            enum_MSG(item->type), item->size,
427                                            (unsigned long long)item->vec.offset,
428                                            (unsigned long long)item->vec.size, s);
429                                 break;
430                         }
431
432                         case KDBUS_MSG_PAYLOAD_MEMFD:
433                         {
434                                 char *buf;
435                                 uint64_t size;
436
437                                 buf = mmap(NULL, item->memfd.size, PROT_READ, MAP_SHARED, item->memfd.fd, 0);
438                                 if (buf == MAP_FAILED) {
439                                         _dbus_verbose("mmap() fd=%i failed:%m", item->memfd.fd);
440                                         break;
441                                 }
442
443                                 if (ioctl(item->memfd.fd, KDBUS_CMD_MEMFD_SIZE_GET, &size) < 0) {
444                                         _dbus_verbose("KDBUS_CMD_MEMFD_SIZE_GET failed: %m\n");
445                                         break;
446                                 }
447
448                                 _dbus_verbose("  +%s (%llu bytes) fd=%i size=%llu filesize=%llu '%s'\n",
449                                            enum_MSG(item->type), item->size, item->memfd.fd,
450                                            (unsigned long long)item->memfd.size, (unsigned long long)size, buf);
451                                 break;
452                         }
453
454                         case KDBUS_MSG_SRC_CREDS:
455                                 _dbus_verbose("  +%s (%llu bytes) uid=%lld, gid=%lld, pid=%lld, tid=%lld, starttime=%lld\n",
456                                         enum_MSG(item->type), item->size,
457                                         item->creds.uid, item->creds.gid,
458                                         item->creds.pid, item->creds.tid,
459                                         item->creds.starttime);
460                         break;
461
462                         case KDBUS_MSG_SRC_PID_COMM:
463                         case KDBUS_MSG_SRC_TID_COMM:
464                         case KDBUS_MSG_SRC_EXE:
465                         case KDBUS_MSG_SRC_CGROUP:
466                         case KDBUS_MSG_SRC_SECLABEL:
467                         case KDBUS_MSG_DST_NAME:
468                                 _dbus_verbose("  +%s (%llu bytes) '%s' (%zu)\n",
469                                            enum_MSG(item->type), item->size, item->str, strlen(item->str));
470                                 break;
471
472                         case KDBUS_MSG_SRC_CMDLINE:
473                         case KDBUS_MSG_SRC_NAMES: {
474                                 size_t size = item->size - KDBUS_PART_HEADER_SIZE;
475                                 const char *str = item->str;
476                                 int count = 0;
477
478                                 _dbus_verbose("  +%s (%llu bytes) ", enum_MSG(item->type), item->size);
479                                 while (size) {
480                                         _dbus_verbose("'%s' ", str);
481                                         size -= strlen(str) + 1;
482                                         str += strlen(str) + 1;
483                                         count++;
484                                 }
485
486                                 _dbus_verbose("(%d string%s)\n", count, (count == 1) ? "" : "s");
487                                 break;
488                         }
489
490                         case KDBUS_MSG_SRC_AUDIT:
491                                 _dbus_verbose("  +%s (%llu bytes) loginuid=%llu sessionid=%llu\n",
492                                            enum_MSG(item->type), item->size,
493                                            (unsigned long long)item->data64[0],
494                                            (unsigned long long)item->data64[1]);
495                                 break;
496
497                         case KDBUS_MSG_SRC_CAPS: {
498                                 int n;
499                                 const uint32_t *cap;
500                                 int i;
501
502                                 _dbus_verbose("  +%s (%llu bytes) len=%llu bytes)\n",
503                                            enum_MSG(item->type), item->size,
504                                            (unsigned long long)item->size - KDBUS_PART_HEADER_SIZE);
505
506                                 cap = item->data32;
507                                 n = (item->size - KDBUS_PART_HEADER_SIZE) / 4 / sizeof(uint32_t);
508
509                                 _dbus_verbose("    CapInh=");
510                                 for (i = 0; i < n; i++)
511                                         _dbus_verbose("%08x", cap[(0 * n) + (n - i - 1)]);
512
513                                 _dbus_verbose(" CapPrm=");
514                                 for (i = 0; i < n; i++)
515                                         _dbus_verbose("%08x", cap[(1 * n) + (n - i - 1)]);
516
517                                 _dbus_verbose(" CapEff=");
518                                 for (i = 0; i < n; i++)
519                                         _dbus_verbose("%08x", cap[(2 * n) + (n - i - 1)]);
520
521                                 _dbus_verbose(" CapInh=");
522                                 for (i = 0; i < n; i++)
523                                         _dbus_verbose("%08x", cap[(3 * n) + (n - i - 1)]);
524                                 _dbus_verbose("\n");
525                                 break;
526                         }
527
528                         case KDBUS_MSG_TIMESTAMP:
529                                 _dbus_verbose("  +%s (%llu bytes) realtime=%lluns monotonic=%lluns\n",
530                                            enum_MSG(item->type), item->size,
531                                            (unsigned long long)item->timestamp.realtime_ns,
532                                            (unsigned long long)item->timestamp.monotonic_ns);
533                                 break;
534
535                         case KDBUS_MSG_REPLY_TIMEOUT:
536                                 _dbus_verbose("  +%s (%llu bytes) cookie=%llu\n",
537                                            enum_MSG(item->type), item->size, msg->cookie_reply);
538                                 break;
539
540                         case KDBUS_MSG_NAME_ADD:
541                         case KDBUS_MSG_NAME_REMOVE:
542                         case KDBUS_MSG_NAME_CHANGE:
543                                 _dbus_verbose("  +%s (%llu bytes) '%s', old id=%lld, new id=%lld, flags=0x%llx\n",
544                                         enum_MSG(item->type), (unsigned long long) item->size,
545                                         item->name_change.name, item->name_change.old_id,
546                                         item->name_change.new_id, item->name_change.flags);
547                         break;
548
549                         case KDBUS_MSG_ID_ADD:
550                         case KDBUS_MSG_ID_REMOVE:
551                                 _dbus_verbose("  +%s (%llu bytes) id=%llu flags=%llu\n",
552                                            enum_MSG(item->type), (unsigned long long) item->size,
553                                            (unsigned long long) item->id_change.id,
554                                            (unsigned long long) item->id_change.flags);
555                         break;
556
557                         default:
558                                 _dbus_verbose("  +%s (%llu bytes)\n", enum_MSG(item->type), item->size);
559                                 break;
560                 }
561         }
562
563         if ((char *)item - ((char *)msg + msg->size) >= 8)
564                 _dbus_verbose("invalid padding at end of message\n");
565
566         return ret_size;
567 }
568
569 int kdbus_read_message(DBusTransportSocket *socket_transport, DBusString *buffer)
570 {
571         int ret_size;
572         uint64_t offset;
573         struct kdbus_msg *msg;
574         int ret;
575         int start;
576         char *data;
577
578 //      int i;
579
580         //todo this block maybe can be removed
581         _dbus_assert (socket_transport->max_bytes_read_per_iteration >= 0);
582         start = _dbus_string_get_length (buffer);
583         if (!_dbus_string_lengthen (buffer, socket_transport->max_bytes_read_per_iteration))
584         {
585                 errno = ENOMEM;
586             return -1;
587         }
588         data = _dbus_string_get_data_len (buffer, start, socket_transport->max_bytes_read_per_iteration);
589
590         again:
591         ret = ioctl(socket_transport->fd, KDBUS_CMD_MSG_RECV, &offset);
592         if (ret < 0)
593         {
594                 if(errno == EINTR)
595                         goto again;
596                 _dbus_verbose("kdbus error receiving message: %d (%m)\n", ret);
597                 _dbus_string_set_length (buffer, start);  //todo probably to remove
598                 return -1;
599         }
600
601         msg = (struct kdbus_msg *)((char*)socket_transport->kdbus_mmap_ptr + offset);
602
603         ret_size = kdbus_decode_msg(msg, data, socket_transport->kdbus_mmap_ptr); //todo data to be replaced by buffer
604 /*      fprintf (stderr, "\nmessage! start: %u, ret_size: %u\n", start, ret_size);
605     for(i=0; i < ret_size; i++)
606     {
607         fprintf (stderr, "%02x", (int)data[i]);
608     }
609     fprintf (stderr, "\nret size: %u, i: %u\n", ret_size, i);*/
610         _dbus_string_set_length (buffer, start + ret_size);
611
612         again2:
613         ret = ioctl(socket_transport->fd, KDBUS_CMD_MSG_RELEASE, &offset);
614         if (ret < 0)
615         {
616                 if(errno == EINTR)
617                         goto again2;
618                 _dbus_verbose("kdbus error freeing message: %d (%m)\n", ret);
619                 return -1;
620         }
621
622         return ret_size;
623 }
624
625 static void
626 free_watches (DBusTransport *transport)
627 {
628   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
629
630   _dbus_verbose ("start\n");
631
632   if (socket_transport->read_watch)
633     {
634       if (transport->connection)
635         _dbus_connection_remove_watch_unlocked (transport->connection,
636                                                 socket_transport->read_watch);
637       _dbus_watch_invalidate (socket_transport->read_watch);
638       _dbus_watch_unref (socket_transport->read_watch);
639       socket_transport->read_watch = NULL;
640     }
641
642   if (socket_transport->write_watch)
643     {
644       if (transport->connection)
645         _dbus_connection_remove_watch_unlocked (transport->connection,
646                                                 socket_transport->write_watch);
647       _dbus_watch_invalidate (socket_transport->write_watch);
648       _dbus_watch_unref (socket_transport->write_watch);
649       socket_transport->write_watch = NULL;
650     }
651
652   _dbus_verbose ("end\n");
653 }
654
655 static void
656 socket_finalize (DBusTransport *transport)
657 {
658   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
659
660   _dbus_verbose ("\n");
661
662   free_watches (transport);
663
664   _dbus_string_free (&socket_transport->encoded_outgoing);
665   _dbus_string_free (&socket_transport->encoded_incoming);
666
667   _dbus_transport_finalize_base (transport);
668
669   _dbus_assert (socket_transport->read_watch == NULL);
670   _dbus_assert (socket_transport->write_watch == NULL);
671
672   dbus_free (transport);
673 }
674
675 static void
676 check_write_watch (DBusTransport *transport)
677 {
678   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
679   dbus_bool_t needed;
680
681   if (transport->connection == NULL)
682     return;
683
684   if (transport->disconnected)
685     {
686       _dbus_assert (socket_transport->write_watch == NULL);
687       return;
688     }
689
690   _dbus_transport_ref (transport);
691
692   if (_dbus_transport_get_is_authenticated (transport))
693     needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection);
694   else
695     {
696       if (transport->send_credentials_pending)
697         needed = TRUE;
698       else
699         {
700           DBusAuthState auth_state;
701
702           auth_state = _dbus_auth_do_work (transport->auth);
703
704           /* If we need memory we install the write watch just in case,
705            * if there's no need for it, it will get de-installed
706            * next time we try reading.
707            */
708           if (auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND ||
709               auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY)
710             needed = TRUE;
711           else
712             needed = FALSE;
713         }
714     }
715
716   _dbus_verbose ("check_write_watch(): needed = %d on connection %p watch %p fd = %d outgoing messages exist %d\n",
717                  needed, transport->connection, socket_transport->write_watch,
718                  socket_transport->fd,
719                  _dbus_connection_has_messages_to_send_unlocked (transport->connection));
720
721   _dbus_connection_toggle_watch_unlocked (transport->connection,
722                                           socket_transport->write_watch,
723                                           needed);
724
725   _dbus_transport_unref (transport);
726 }
727
728 static void
729 check_read_watch (DBusTransport *transport)
730 {
731   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
732   dbus_bool_t need_read_watch;
733
734   _dbus_verbose ("fd = %d\n",socket_transport->fd);
735
736   if (transport->connection == NULL)
737     return;
738
739   if (transport->disconnected)
740     {
741       _dbus_assert (socket_transport->read_watch == NULL);
742       return;
743     }
744
745   _dbus_transport_ref (transport);
746
747   if (_dbus_transport_get_is_authenticated (transport))
748     need_read_watch =
749       (_dbus_counter_get_size_value (transport->live_messages) < transport->max_live_messages_size) &&
750       (_dbus_counter_get_unix_fd_value (transport->live_messages) < transport->max_live_messages_unix_fds);
751   else
752     {
753       if (transport->receive_credentials_pending)
754         need_read_watch = TRUE;
755       else
756         {
757           /* The reason to disable need_read_watch when not WAITING_FOR_INPUT
758            * is to avoid spinning on the file descriptor when we're waiting
759            * to write or for some other part of the auth process
760            */
761           DBusAuthState auth_state;
762
763           auth_state = _dbus_auth_do_work (transport->auth);
764
765           /* If we need memory we install the read watch just in case,
766            * if there's no need for it, it will get de-installed
767            * next time we try reading. If we're authenticated we
768            * install it since we normally have it installed while
769            * authenticated.
770            */
771           if (auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT ||
772               auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY ||
773               auth_state == DBUS_AUTH_STATE_AUTHENTICATED)
774             need_read_watch = TRUE;
775           else
776             need_read_watch = FALSE;
777         }
778     }
779
780   _dbus_verbose ("  setting read watch enabled = %d\n", need_read_watch);
781   _dbus_connection_toggle_watch_unlocked (transport->connection,
782                                           socket_transport->read_watch,
783                                           need_read_watch);
784
785   _dbus_transport_unref (transport);
786 }
787
788 static void
789 do_io_error (DBusTransport *transport)
790 {
791   _dbus_transport_ref (transport);
792   _dbus_transport_disconnect (transport);
793   _dbus_transport_unref (transport);
794 }
795
796 /* return value is whether we successfully read any new data. */
797 static dbus_bool_t
798 read_data_into_auth (DBusTransport *transport,
799                      dbus_bool_t   *oom)
800 {
801   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
802   DBusString *buffer;
803   int bytes_read;
804
805   *oom = FALSE;
806
807   _dbus_auth_get_buffer (transport->auth, &buffer);
808
809   bytes_read = _dbus_read_socket (socket_transport->fd,
810                                   buffer, socket_transport->max_bytes_read_per_iteration);
811
812   _dbus_auth_return_buffer (transport->auth, buffer,
813                             bytes_read > 0 ? bytes_read : 0);
814
815   if (bytes_read > 0)
816     {
817       _dbus_verbose (" read %d bytes in auth phase\n", bytes_read);
818
819       return TRUE;
820     }
821   else if (bytes_read < 0)
822     {
823       /* EINTR already handled for us */
824
825       if (_dbus_get_is_errno_enomem ())
826         {
827           *oom = TRUE;
828         }
829       else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
830         ; /* do nothing, just return FALSE below */
831       else
832         {
833           _dbus_verbose ("Error reading from remote app: %s\n",
834                          _dbus_strerror_from_errno ());
835           do_io_error (transport);
836         }
837
838       return FALSE;
839     }
840   else
841     {
842       _dbus_assert (bytes_read == 0);
843
844       _dbus_verbose ("Disconnected from remote app\n");
845       do_io_error (transport);
846
847       return FALSE;
848     }
849 }
850
851 /* Return value is whether we successfully wrote any bytes */
852 static dbus_bool_t
853 write_data_from_auth (DBusTransport *transport)
854 {
855   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
856   int bytes_written;
857   const DBusString *buffer;
858
859   if (!_dbus_auth_get_bytes_to_send (transport->auth,
860                                      &buffer))
861     return FALSE;
862
863   bytes_written = _dbus_write_socket (socket_transport->fd,
864                                       buffer,
865                                       0, _dbus_string_get_length (buffer));
866
867   if (bytes_written > 0)
868     {
869       _dbus_auth_bytes_sent (transport->auth, bytes_written);
870       return TRUE;
871     }
872   else if (bytes_written < 0)
873     {
874       /* EINTR already handled for us */
875
876       if (_dbus_get_is_errno_eagain_or_ewouldblock ())
877         ;
878       else
879         {
880           _dbus_verbose ("Error writing to remote app: %s\n",
881                          _dbus_strerror_from_errno ());
882           do_io_error (transport);
883         }
884     }
885
886   return FALSE;
887 }
888
889 /* FALSE on OOM */
890 static dbus_bool_t
891 exchange_credentials (DBusTransport *transport,
892                       dbus_bool_t    do_reading,
893                       dbus_bool_t    do_writing)
894 {
895   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
896   DBusError error = DBUS_ERROR_INIT;
897
898   _dbus_verbose ("exchange_credentials: do_reading = %d, do_writing = %d\n",
899                   do_reading, do_writing);
900
901   if (do_writing && transport->send_credentials_pending)
902     {
903       if (_dbus_send_credentials_socket (socket_transport->fd,
904                                          &error))
905         {
906           transport->send_credentials_pending = FALSE;
907         }
908       else
909         {
910           _dbus_verbose ("Failed to write credentials: %s\n", error.message);
911           dbus_error_free (&error);
912           do_io_error (transport);
913         }
914     }
915
916   if (do_reading && transport->receive_credentials_pending)
917     {
918       /* FIXME this can fail due to IO error _or_ OOM, broken
919        * (somewhat tricky to fix since the OOM error can be set after
920        * we already read the credentials byte, so basically we need to
921        * separate reading the byte and storing it in the
922        * transport->credentials). Does not really matter for now
923        * because storing in credentials never actually fails on unix.
924        */
925       if (_dbus_read_credentials_socket (socket_transport->fd,
926                                          transport->credentials,
927                                          &error))
928         {
929           transport->receive_credentials_pending = FALSE;
930         }
931       else
932         {
933           _dbus_verbose ("Failed to read credentials %s\n", error.message);
934           dbus_error_free (&error);
935           do_io_error (transport);
936         }
937     }
938
939   if (!(transport->send_credentials_pending ||
940         transport->receive_credentials_pending))
941     {
942       if (!_dbus_auth_set_credentials (transport->auth,
943                                        transport->credentials))
944         return FALSE;
945     }
946
947   return TRUE;
948 }
949
950 static dbus_bool_t
951 do_authentication (DBusTransport *transport,
952                    dbus_bool_t    do_reading,
953                    dbus_bool_t    do_writing,
954                    dbus_bool_t   *auth_completed)
955 {
956   dbus_bool_t oom;
957   dbus_bool_t orig_auth_state;
958
959   oom = FALSE;
960
961   orig_auth_state = _dbus_transport_get_is_authenticated (transport);
962
963   /* This is essential to avoid the check_write_watch() at the end,
964    * we don't want to add a write watch in do_iteration before
965    * we try writing and get EAGAIN
966    */
967   if (orig_auth_state)
968     {
969       if (auth_completed)
970         *auth_completed = FALSE;
971       return TRUE;
972     }
973
974   _dbus_transport_ref (transport);
975
976   while (!_dbus_transport_get_is_authenticated (transport) &&
977          _dbus_transport_get_is_connected (transport))
978     {
979       if (!exchange_credentials (transport, do_reading, do_writing))
980         {
981           /* OOM */
982           oom = TRUE;
983           goto out;
984         }
985
986       if (transport->send_credentials_pending ||
987           transport->receive_credentials_pending)
988         {
989           _dbus_verbose ("send_credentials_pending = %d receive_credentials_pending = %d\n",
990                          transport->send_credentials_pending,
991                          transport->receive_credentials_pending);
992           goto out;
993         }
994
995 #define TRANSPORT_SIDE(t) ((t)->is_server ? "server" : "client")
996       switch (_dbus_auth_do_work (transport->auth))
997         {
998         case DBUS_AUTH_STATE_WAITING_FOR_INPUT:
999           _dbus_verbose (" %s auth state: waiting for input\n",
1000                          TRANSPORT_SIDE (transport));
1001           if (!do_reading || !read_data_into_auth (transport, &oom))
1002             goto out;
1003           break;
1004
1005         case DBUS_AUTH_STATE_WAITING_FOR_MEMORY:
1006           _dbus_verbose (" %s auth state: waiting for memory\n",
1007                          TRANSPORT_SIDE (transport));
1008           oom = TRUE;
1009           goto out;
1010           break;
1011
1012         case DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND:
1013           _dbus_verbose (" %s auth state: bytes to send\n",
1014                          TRANSPORT_SIDE (transport));
1015           if (!do_writing || !write_data_from_auth (transport))
1016             goto out;
1017           break;
1018
1019         case DBUS_AUTH_STATE_NEED_DISCONNECT:
1020           _dbus_verbose (" %s auth state: need to disconnect\n",
1021                          TRANSPORT_SIDE (transport));
1022           do_io_error (transport);
1023           break;
1024
1025         case DBUS_AUTH_STATE_AUTHENTICATED:
1026           _dbus_verbose (" %s auth state: authenticated\n",
1027                          TRANSPORT_SIDE (transport));
1028           break;
1029         }
1030     }
1031
1032  out:
1033   if (auth_completed)
1034     *auth_completed = (orig_auth_state != _dbus_transport_get_is_authenticated (transport));
1035
1036   check_read_watch (transport);
1037   check_write_watch (transport);
1038   _dbus_transport_unref (transport);
1039
1040   if (oom)
1041     return FALSE;
1042   else
1043     return TRUE;
1044 }
1045
1046 /* returns false on oom */
1047 static dbus_bool_t
1048 do_writing (DBusTransport *transport)
1049 {
1050         int total;
1051         DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1052         dbus_bool_t oom;
1053
1054         /* No messages without authentication! */
1055         if (!_dbus_transport_get_is_authenticated (transport))
1056     {
1057                 _dbus_verbose ("Not authenticated, not writing anything\n");
1058                 return TRUE;
1059     }
1060
1061         if (transport->disconnected)
1062     {
1063                 _dbus_verbose ("Not connected, not writing anything\n");
1064                 return TRUE;
1065     }
1066
1067 #if 1
1068         _dbus_verbose ("do_writing(), have_messages = %d, fd = %d\n",
1069                  _dbus_connection_has_messages_to_send_unlocked (transport->connection),
1070                  socket_transport->fd);
1071 #endif
1072
1073         oom = FALSE;
1074         total = 0;
1075
1076         while (!transport->disconnected && _dbus_connection_has_messages_to_send_unlocked (transport->connection))
1077     {
1078                 int bytes_written;
1079                 DBusMessage *message;
1080                 const DBusString *header;
1081                 const DBusString *body;
1082                 int total_bytes_to_write;
1083
1084
1085                 if (total > socket_transport->max_bytes_written_per_iteration)
1086         {
1087                         _dbus_verbose ("%d bytes exceeds %d bytes written per iteration, returning\n",
1088                          total, socket_transport->max_bytes_written_per_iteration);
1089                         goto out;
1090         }
1091
1092                 message = _dbus_connection_get_message_to_send (transport->connection);
1093                 _dbus_assert (message != NULL);
1094                 dbus_message_lock (message);
1095                 _dbus_message_get_network_data (message, &header, &body);
1096
1097                 if (_dbus_auth_needs_encoding (transport->auth))
1098         {
1099                         // Does fd passing even make sense with encoded data?
1100                         _dbus_assert(!DBUS_TRANSPORT_CAN_SEND_UNIX_FD(transport));
1101
1102                         if (_dbus_string_get_length (&socket_transport->encoded_outgoing) == 0)
1103             {
1104                                 if (!_dbus_auth_encode_data (transport->auth,
1105                                            header, &socket_transport->encoded_outgoing))
1106                 {
1107                                         oom = TRUE;
1108                                         goto out;
1109                 }
1110
1111                                 if (!_dbus_auth_encode_data (transport->auth,
1112                                            body, &socket_transport->encoded_outgoing))
1113                 {
1114                                         _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
1115                                         oom = TRUE;
1116                                         goto out;
1117                 }
1118             }
1119
1120                         total_bytes_to_write = _dbus_string_get_length (&socket_transport->encoded_outgoing);
1121                         bytes_written = kdbus_write_msg_encoded(message, socket_transport);
1122         }
1123                 else
1124                 {
1125                         total_bytes_to_write = _dbus_string_get_length(header) + _dbus_string_get_length(body);
1126                         bytes_written = kdbus_write_msg(transport->connection, message, socket_transport->fd);
1127                 }
1128
1129                 if (bytes_written < 0)
1130                 {
1131                         /* EINTR already handled for us */
1132
1133           /* For some discussion of why we also ignore EPIPE here, see
1134            * http://lists.freedesktop.org/archives/dbus/2008-March/009526.html
1135            */
1136
1137                         if (_dbus_get_is_errno_eagain_or_ewouldblock () || _dbus_get_is_errno_epipe ())
1138                                 goto out;
1139                         else
1140                         {
1141                                 _dbus_verbose ("Error writing to remote app: %s\n",
1142                                                          _dbus_strerror_from_errno ());
1143                                 do_io_error (transport);
1144                                 goto out;
1145                         }
1146                 }
1147                 else
1148                 {
1149                         _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
1150                          total_bytes_to_write);
1151
1152                         total += bytes_written;
1153                         socket_transport->message_bytes_written += bytes_written;
1154
1155                         _dbus_assert (socket_transport->message_bytes_written <=
1156                         total_bytes_to_write);
1157
1158                           if (socket_transport->message_bytes_written == total_bytes_to_write)
1159                           {
1160                                   socket_transport->message_bytes_written = 0;
1161                                   _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
1162                                   _dbus_string_compact (&socket_transport->encoded_outgoing, 2048);
1163
1164                                   _dbus_connection_message_sent_unlocked (transport->connection,
1165                                                                                                                   message);
1166                           }
1167                 }
1168     }
1169
1170         out:
1171         if (oom)
1172                 return FALSE;
1173         else
1174                 return TRUE;
1175 }
1176
1177 /* returns false on out-of-memory */
1178 static dbus_bool_t
1179 do_reading (DBusTransport *transport)
1180 {
1181   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1182   DBusString *buffer;
1183   int bytes_read;
1184   int total;
1185   dbus_bool_t oom;
1186
1187   _dbus_verbose ("fd = %d\n",socket_transport->fd);
1188
1189   /* No messages without authentication! */
1190   if (!_dbus_transport_get_is_authenticated (transport))
1191     return TRUE;
1192
1193   oom = FALSE;
1194
1195   total = 0;
1196
1197  again:
1198
1199   /* See if we've exceeded max messages and need to disable reading */
1200   check_read_watch (transport);
1201
1202   if (total > socket_transport->max_bytes_read_per_iteration)
1203     {
1204       _dbus_verbose ("%d bytes exceeds %d bytes read per iteration, returning\n",
1205                      total, socket_transport->max_bytes_read_per_iteration);
1206       goto out;
1207     }
1208
1209   _dbus_assert (socket_transport->read_watch != NULL ||
1210                 transport->disconnected);
1211
1212   if (transport->disconnected)
1213     goto out;
1214
1215   if (!dbus_watch_get_enabled (socket_transport->read_watch))
1216     return TRUE;
1217
1218   if (_dbus_auth_needs_decoding (transport->auth))  //todo
1219     {
1220       /* Does fd passing even make sense with encoded data? */
1221       _dbus_assert(!DBUS_TRANSPORT_CAN_SEND_UNIX_FD(transport));
1222
1223       if (_dbus_string_get_length (&socket_transport->encoded_incoming) > 0)
1224         bytes_read = _dbus_string_get_length (&socket_transport->encoded_incoming);
1225       else
1226         bytes_read = _dbus_read_socket (socket_transport->fd,
1227                                         &socket_transport->encoded_incoming,
1228                                         socket_transport->max_bytes_read_per_iteration);
1229
1230       _dbus_assert (_dbus_string_get_length (&socket_transport->encoded_incoming) ==
1231                     bytes_read);
1232
1233       if (bytes_read > 0)
1234         {
1235           int orig_len;
1236
1237           _dbus_message_loader_get_buffer (transport->loader,
1238                                            &buffer);
1239
1240           orig_len = _dbus_string_get_length (buffer);
1241
1242           if (!_dbus_auth_decode_data (transport->auth,
1243                                        &socket_transport->encoded_incoming,
1244                                        buffer))
1245             {
1246               _dbus_verbose ("Out of memory decoding incoming data\n");
1247               _dbus_message_loader_return_buffer (transport->loader,
1248                                               buffer,
1249                                               _dbus_string_get_length (buffer) - orig_len);
1250
1251               oom = TRUE;
1252               goto out;
1253             }
1254
1255           _dbus_message_loader_return_buffer (transport->loader,
1256                                               buffer,
1257                                               _dbus_string_get_length (buffer) - orig_len);
1258
1259           _dbus_string_set_length (&socket_transport->encoded_incoming, 0);
1260           _dbus_string_compact (&socket_transport->encoded_incoming, 2048);
1261         }
1262     }
1263   else
1264     {
1265       _dbus_message_loader_get_buffer (transport->loader,
1266                                        &buffer);
1267
1268       bytes_read = kdbus_read_message(socket_transport, buffer);
1269
1270       _dbus_message_loader_return_buffer (transport->loader,
1271                                           buffer,
1272                                           bytes_read < 0 ? 0 : bytes_read);
1273     }
1274
1275   if (bytes_read < 0)
1276     {
1277       /* EINTR already handled for us */
1278
1279       if (_dbus_get_is_errno_enomem ())
1280         {
1281           _dbus_verbose ("Out of memory in read()/do_reading()\n");
1282           oom = TRUE;
1283           goto out;
1284         }
1285       else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
1286         goto out;
1287       else
1288         {
1289           _dbus_verbose ("Error reading from remote app: %s\n",
1290                          _dbus_strerror_from_errno ());
1291           do_io_error (transport);
1292           goto out;
1293         }
1294     }
1295   else if (bytes_read == 0)
1296     {
1297       _dbus_verbose ("Disconnected from remote app\n");
1298 //      do_io_error (transport);  todo temporarily commented out for tests
1299       goto out;
1300     }
1301   else
1302     {
1303       _dbus_verbose (" read %d bytes\n", bytes_read);
1304
1305       total += bytes_read;
1306
1307       if (!_dbus_transport_queue_messages (transport))
1308         {
1309           oom = TRUE;
1310           _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
1311           goto out;
1312         }
1313
1314       /* Try reading more data until we get EAGAIN and return, or
1315        * exceed max bytes per iteration.  If in blocking mode of
1316        * course we'll block instead of returning.
1317        */
1318       goto again;
1319     }
1320
1321  out:
1322   if (oom)
1323     return FALSE;
1324   else
1325     return TRUE;
1326 }
1327
1328 static dbus_bool_t
1329 unix_error_with_read_to_come (DBusTransport *itransport,
1330                               DBusWatch     *watch,
1331                               unsigned int   flags)
1332 {
1333   DBusTransportSocket *transport = (DBusTransportSocket *) itransport;
1334
1335   if (!(flags & DBUS_WATCH_HANGUP || flags & DBUS_WATCH_ERROR))
1336     return FALSE;
1337
1338   /* If we have a read watch enabled ...
1339      we -might have data incoming ... => handle the HANGUP there */
1340   if (watch != transport->read_watch &&
1341       _dbus_watch_get_enabled (transport->read_watch))
1342     return FALSE;
1343
1344   return TRUE;
1345 }
1346
1347 static dbus_bool_t
1348 socket_handle_watch (DBusTransport *transport,
1349                    DBusWatch     *watch,
1350                    unsigned int   flags)
1351 {
1352   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1353
1354   _dbus_assert (watch == socket_transport->read_watch ||
1355                 watch == socket_transport->write_watch);
1356   _dbus_assert (watch != NULL);
1357
1358   /* If we hit an error here on a write watch, don't disconnect the transport yet because data can
1359    * still be in the buffer and do_reading may need several iteration to read
1360    * it all (because of its max_bytes_read_per_iteration limit).
1361    */
1362   if (!(flags & DBUS_WATCH_READABLE) && unix_error_with_read_to_come (transport, watch, flags))
1363     {
1364       _dbus_verbose ("Hang up or error on watch\n");
1365       _dbus_transport_disconnect (transport);
1366       return TRUE;
1367     }
1368
1369   if (watch == socket_transport->read_watch &&
1370       (flags & DBUS_WATCH_READABLE))
1371     {
1372       dbus_bool_t auth_finished;
1373 #if 1
1374       _dbus_verbose ("handling read watch %p flags = %x\n",
1375                      watch, flags);
1376 #endif
1377       if (!do_authentication (transport, TRUE, FALSE, &auth_finished))
1378         return FALSE;
1379
1380       /* We don't want to do a read immediately following
1381        * a successful authentication.  This is so we
1382        * have a chance to propagate the authentication
1383        * state further up.  Specifically, we need to
1384        * process any pending data from the auth object.
1385        */
1386       if (!auth_finished)
1387         {
1388           if (!do_reading (transport))
1389             {
1390               _dbus_verbose ("no memory to read\n");
1391               return FALSE;
1392             }
1393         }
1394       else
1395         {
1396           _dbus_verbose ("Not reading anything since we just completed the authentication\n");
1397         }
1398     }
1399   else if (watch == socket_transport->write_watch &&
1400            (flags & DBUS_WATCH_WRITABLE))
1401     {
1402 #if 1
1403       _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n",
1404                      _dbus_connection_has_messages_to_send_unlocked (transport->connection));
1405 #endif
1406       if (!do_authentication (transport, FALSE, TRUE, NULL))
1407         return FALSE;
1408
1409       if (!do_writing (transport))
1410         {
1411           _dbus_verbose ("no memory to write\n");
1412           return FALSE;
1413         }
1414
1415       /* See if we still need the write watch */
1416       check_write_watch (transport);
1417     }
1418 #ifdef DBUS_ENABLE_VERBOSE_MODE
1419   else
1420     {
1421       if (watch == socket_transport->read_watch)
1422         _dbus_verbose ("asked to handle read watch with non-read condition 0x%x\n",
1423                        flags);
1424       else if (watch == socket_transport->write_watch)
1425         _dbus_verbose ("asked to handle write watch with non-write condition 0x%x\n",
1426                        flags);
1427       else
1428         _dbus_verbose ("asked to handle watch %p on fd %d that we don't recognize\n",
1429                        watch, dbus_watch_get_socket (watch));
1430     }
1431 #endif /* DBUS_ENABLE_VERBOSE_MODE */
1432
1433   return TRUE;
1434 }
1435
1436 static void
1437 socket_disconnect (DBusTransport *transport)
1438 {
1439   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1440
1441   _dbus_verbose ("\n");
1442
1443   free_watches (transport);
1444
1445   _dbus_close_socket (socket_transport->fd, NULL);
1446   socket_transport->fd = -1;
1447 }
1448
1449 static dbus_bool_t
1450 socket_connection_set (DBusTransport *transport)
1451 {
1452   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1453
1454   _dbus_watch_set_handler (socket_transport->write_watch,
1455                            _dbus_connection_handle_watch,
1456                            transport->connection, NULL);
1457
1458   _dbus_watch_set_handler (socket_transport->read_watch,
1459                            _dbus_connection_handle_watch,
1460                            transport->connection, NULL);
1461
1462   if (!_dbus_connection_add_watch_unlocked (transport->connection,
1463                                             socket_transport->write_watch))
1464     return FALSE;
1465
1466   if (!_dbus_connection_add_watch_unlocked (transport->connection,
1467                                             socket_transport->read_watch))
1468     {
1469       _dbus_connection_remove_watch_unlocked (transport->connection,
1470                                               socket_transport->write_watch);
1471       return FALSE;
1472     }
1473
1474   check_read_watch (transport);
1475   check_write_watch (transport);
1476
1477   return TRUE;
1478 }
1479
1480 /**
1481  * @todo We need to have a way to wake up the select sleep if
1482  * a new iteration request comes in with a flag (read/write) that
1483  * we're not currently serving. Otherwise a call that just reads
1484  * could block a write call forever (if there are no incoming
1485  * messages).
1486  */
1487 static  void
1488 kdbus_do_iteration (DBusTransport *transport,
1489                    unsigned int   flags,
1490                    int            timeout_milliseconds)
1491 {
1492         DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1493         DBusPollFD poll_fd;
1494         int poll_res;
1495         int poll_timeout;
1496
1497         _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p fd = %d\n",
1498                  flags & DBUS_ITERATION_DO_READING ? "read" : "",
1499                  flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
1500                  timeout_milliseconds,
1501                  socket_transport->read_watch,
1502                  socket_transport->write_watch,
1503                  socket_transport->fd);
1504
1505   /* the passed in DO_READING/DO_WRITING flags indicate whether to
1506    * read/write messages, but regardless of those we may need to block
1507    * for reading/writing to do auth.  But if we do reading for auth,
1508    * we don't want to read any messages yet if not given DO_READING.
1509    */
1510
1511   poll_fd.fd = socket_transport->fd;
1512   poll_fd.events = 0;
1513
1514   if (_dbus_transport_get_is_authenticated (transport))
1515     {
1516       /* This is kind of a hack; if we have stuff to write, then try
1517        * to avoid the poll. This is probably about a 5% speedup on an
1518        * echo client/server.
1519        *
1520        * If both reading and writing were requested, we want to avoid this
1521        * since it could have funky effects:
1522        *   - both ends spinning waiting for the other one to read
1523        *     data so they can finish writing
1524        *   - prioritizing all writing ahead of reading
1525        */
1526       if ((flags & DBUS_ITERATION_DO_WRITING) &&
1527           !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) &&
1528           !transport->disconnected &&
1529           _dbus_connection_has_messages_to_send_unlocked (transport->connection))
1530         {
1531           do_writing (transport);
1532
1533           if (transport->disconnected ||
1534               !_dbus_connection_has_messages_to_send_unlocked (transport->connection))
1535             goto out;
1536         }
1537
1538       /* If we get here, we decided to do the poll() after all */
1539       _dbus_assert (socket_transport->read_watch);
1540       if (flags & DBUS_ITERATION_DO_READING)
1541         poll_fd.events |= _DBUS_POLLIN;
1542
1543       _dbus_assert (socket_transport->write_watch);
1544       if (flags & DBUS_ITERATION_DO_WRITING)
1545         poll_fd.events |= _DBUS_POLLOUT;
1546     }
1547   else
1548     {
1549       DBusAuthState auth_state;
1550
1551       auth_state = _dbus_auth_do_work (transport->auth);
1552
1553       if (transport->receive_credentials_pending ||
1554           auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT)
1555         poll_fd.events |= _DBUS_POLLIN;
1556
1557       if (transport->send_credentials_pending ||
1558           auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND)
1559         poll_fd.events |= _DBUS_POLLOUT;
1560     }
1561
1562   if (poll_fd.events)
1563     {
1564       if (flags & DBUS_ITERATION_BLOCK)
1565         poll_timeout = timeout_milliseconds;
1566       else
1567         poll_timeout = 0;
1568
1569       /* For blocking selects we drop the connection lock here
1570        * to avoid blocking out connection access during a potentially
1571        * indefinite blocking call. The io path is still protected
1572        * by the io_path_cond condvar, so we won't reenter this.
1573        */
1574       if (flags & DBUS_ITERATION_BLOCK)
1575         {
1576           _dbus_verbose ("unlock pre poll\n");
1577           _dbus_connection_unlock (transport->connection);
1578         }
1579       _dbus_verbose ("poll_fd.events: %x, timeout: %d\n", poll_fd.events, poll_timeout);
1580     again:
1581       poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
1582
1583       if (poll_res < 0 && _dbus_get_is_errno_eintr ())
1584       {
1585           _dbus_verbose ("Error from _dbus_poll(): %s\n",
1586                          _dbus_strerror_from_errno ());
1587           goto again;
1588       }
1589       _dbus_verbose ("poll_fd.revents: %x\n", poll_fd.revents);
1590
1591     /*  poll_res = poll_timeout;                        // todo temporary walkaround of above problem
1592       poll_res = 1;                                                     // todo temporary walkaround of above problem
1593       poll_fd.revents = poll_fd.events;    // todo temporary walkaround of above problem*/
1594
1595       if (flags & DBUS_ITERATION_BLOCK)
1596         {
1597           _dbus_verbose ("lock post poll\n");
1598           _dbus_connection_lock (transport->connection);
1599         }
1600
1601       if (poll_res >= 0)
1602         {
1603           if (poll_res == 0)
1604             poll_fd.revents = 0; /* some concern that posix does not guarantee this;
1605                                   * valgrind flags it as an error. though it probably
1606                                   * is guaranteed on linux at least.
1607                                   */
1608
1609           if (poll_fd.revents & _DBUS_POLLERR)
1610             do_io_error (transport);
1611           else
1612             {
1613               dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
1614               dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0;
1615               dbus_bool_t authentication_completed;
1616
1617               _dbus_verbose ("in iteration, need_read=%d need_write=%d\n",
1618                              need_read, need_write);
1619               do_authentication (transport, need_read, need_write,
1620                                  &authentication_completed);
1621
1622               /* See comment in socket_handle_watch. */
1623               if (authentication_completed)
1624                 goto out;
1625
1626               if (need_read && (flags & DBUS_ITERATION_DO_READING))
1627                 do_reading (transport);
1628               if (need_write && (flags & DBUS_ITERATION_DO_WRITING))
1629                 do_writing (transport);
1630             }
1631         }
1632       else
1633         {
1634           _dbus_verbose ("Error from _dbus_poll(): %s\n",
1635                          _dbus_strerror_from_errno ());
1636         }
1637     }
1638
1639
1640  out:
1641   /* We need to install the write watch only if we did not
1642    * successfully write everything. Note we need to be careful that we
1643    * don't call check_write_watch *before* do_writing, since it's
1644    * inefficient to add the write watch, and we can avoid it most of
1645    * the time since we can write immediately.
1646    *
1647    * However, we MUST always call check_write_watch(); DBusConnection code
1648    * relies on the fact that running an iteration will notice that
1649    * messages are pending.
1650    */
1651   check_write_watch (transport);
1652
1653   _dbus_verbose (" ... leaving do_iteration()\n");
1654 }
1655
1656 static void
1657 socket_live_messages_changed (DBusTransport *transport)
1658 {
1659   /* See if we should look for incoming messages again */
1660   check_read_watch (transport);
1661 }
1662
1663 static const DBusTransportVTable kdbus_vtable = {
1664   socket_finalize,
1665   socket_handle_watch,
1666   socket_disconnect,
1667   socket_connection_set,
1668   kdbus_do_iteration,
1669   socket_live_messages_changed,
1670   socket_get_socket_fd
1671 };
1672
1673 /**
1674  * Creates a new transport for the given kdbus file descriptor.  The file
1675  * descriptor must be nonblocking (use _dbus_set_fd_nonblocking() to
1676  * make it so).
1677  *
1678  * @param fd the file descriptor.
1679  * @param server_guid non-#NULL if this transport is on the server side of a connection
1680  * @param address the transport's address
1681  * @returns the new transport, or #NULL if no memory.
1682  */
1683 DBusTransport*
1684 _dbus_transport_new_for_socket_kdbus (int       fd,
1685                                           const DBusString *server_guid,
1686                                           const DBusString *address)
1687 {
1688         DBusTransportSocket *socket_transport;
1689
1690   socket_transport = dbus_new0 (DBusTransportSocket, 1);
1691   if (socket_transport == NULL)
1692     return NULL;
1693
1694   if (!_dbus_string_init (&socket_transport->encoded_outgoing))
1695     goto failed_0;
1696
1697   if (!_dbus_string_init (&socket_transport->encoded_incoming))
1698     goto failed_1;
1699
1700   socket_transport->write_watch = _dbus_watch_new (fd,
1701                                                  DBUS_WATCH_WRITABLE,
1702                                                  FALSE,
1703                                                  NULL, NULL, NULL);
1704   if (socket_transport->write_watch == NULL)
1705     goto failed_2;
1706
1707   socket_transport->read_watch = _dbus_watch_new (fd,
1708                                                 DBUS_WATCH_READABLE,
1709                                                 FALSE,
1710                                                 NULL, NULL, NULL);
1711   if (socket_transport->read_watch == NULL)
1712     goto failed_3;
1713
1714   if (!_dbus_transport_init_base (&socket_transport->base,
1715                                   &kdbus_vtable,
1716                                   server_guid, address))
1717     goto failed_4;
1718
1719 #ifdef HAVE_UNIX_FD_PASSING
1720   _dbus_auth_set_unix_fd_possible(socket_transport->base.auth, _dbus_socket_can_pass_unix_fd(fd));
1721 #endif
1722
1723   socket_transport->fd = fd;
1724   socket_transport->message_bytes_written = 0;
1725
1726   /* These values should probably be tunable or something. */
1727   socket_transport->max_bytes_read_per_iteration = POOL_SIZE;
1728   socket_transport->max_bytes_written_per_iteration = 2048;
1729
1730   socket_transport->kdbus_mmap_ptr = NULL;
1731
1732   return (DBusTransport*) socket_transport;
1733
1734  failed_4:
1735   _dbus_watch_invalidate (socket_transport->read_watch);
1736   _dbus_watch_unref (socket_transport->read_watch);
1737  failed_3:
1738   _dbus_watch_invalidate (socket_transport->write_watch);
1739   _dbus_watch_unref (socket_transport->write_watch);
1740  failed_2:
1741   _dbus_string_free (&socket_transport->encoded_incoming);
1742  failed_1:
1743   _dbus_string_free (&socket_transport->encoded_outgoing);
1744  failed_0:
1745   dbus_free (socket_transport);
1746   return NULL;
1747 }
1748
1749
1750 /**
1751  * Creates a connection to the kdbus bus
1752   *
1753  * This will set FD_CLOEXEC for the socket returned.
1754  *
1755  * @param path the path to UNIX domain socket
1756  * @param error return location for error code
1757  * @returns connection file descriptor or -1 on error
1758  */
1759 int _dbus_connect_kdbus (const char *path, DBusError *error)
1760 {
1761         int fd;
1762
1763         _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1764         _dbus_verbose ("connecting to kdbus bus %s\n", path);
1765
1766         fd = open(path, O_RDWR|O_CLOEXEC|O_NONBLOCK); //[RP] | O_NONBLOCK added here, in dbus added separately in section commented out below
1767         if (fd < 0)
1768         {
1769                 dbus_set_error(error, _dbus_error_from_errno (errno), "Failed to open file descriptor: %s", _dbus_strerror (errno));
1770                 _DBUS_ASSERT_ERROR_IS_SET(error);
1771                 return -1;  //[RP] not needed here if commented block below is removed
1772         }
1773
1774         /*if (!_dbus_set_fd_nonblocking (fd, error))
1775     {
1776                 _DBUS_ASSERT_ERROR_IS_SET (error);
1777                 _dbus_close (fd, NULL);
1778                 return -1;
1779     }*/
1780
1781         return fd;
1782 }
1783
1784 dbus_bool_t kdbus_mmap(DBusTransport* transport)
1785 {
1786         DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1787
1788         socket_transport->kdbus_mmap_ptr = mmap(NULL, POOL_SIZE, PROT_READ, MAP_SHARED, socket_transport->fd, 0);
1789         if (socket_transport->kdbus_mmap_ptr == MAP_FAILED)
1790                 return FALSE;
1791
1792         return TRUE;
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 domain socket.
1800  * @param error address where an error can be returned.
1801  * @returns a new transport, or #NULL on failure.
1802  */
1803 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_for_socket_kdbus (fd, NULL, &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.
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 }
1899
1900 struct kdbus_policy *make_policy_name(const char *name)
1901 {
1902         struct kdbus_policy *p;
1903         __u64 size;
1904
1905         size = offsetof(struct kdbus_policy, name) + strlen(name) + 1;
1906         p = malloc(size);
1907         if (!p)
1908                 return NULL;
1909         memset(p, 0, size);
1910         p->size = size;
1911         p->type = KDBUS_POLICY_NAME;
1912         strcpy(p->name, name);
1913
1914         return p;
1915 }
1916
1917 struct kdbus_policy *make_policy_access(__u64 type, __u64 bits, __u64 id)
1918 {
1919         struct kdbus_policy *p;
1920         __u64 size = sizeof(*p);
1921
1922         p = malloc(size);
1923         if (!p)
1924                 return NULL;
1925
1926         memset(p, 0, size);
1927         p->size = size;
1928         p->type = KDBUS_POLICY_ACCESS;
1929         p->access.type = type;
1930         p->access.bits = bits;
1931         p->access.id = id;
1932
1933         return p;
1934 }
1935
1936 void append_policy(struct kdbus_cmd_policy *cmd_policy, struct kdbus_policy *policy, __u64 max_size)
1937 {
1938         struct kdbus_policy *dst = (struct kdbus_policy *) ((char *) cmd_policy + cmd_policy->size);
1939
1940         if (cmd_policy->size + policy->size > max_size)
1941                 return;
1942
1943         memcpy(dst, policy, policy->size);
1944         cmd_policy->size += KDBUS_ALIGN8(policy->size);
1945         free(policy);
1946 }
1947
1948 dbus_bool_t bus_register_kdbus_policy(const char* name, DBusConnection *connection, DBusError *error)
1949 {
1950         struct kdbus_cmd_policy *cmd_policy;
1951         struct kdbus_policy *policy;
1952         int size = 0xffff;
1953         int fd;
1954
1955         if(!dbus_connection_get_socket(connection, &fd))
1956         {
1957                 dbus_set_error (error, "Failed to get fd for registering policy", NULL);
1958                 return FALSE;
1959         }
1960
1961         cmd_policy = (struct kdbus_cmd_policy *) alloca(size);
1962         memset(cmd_policy, 0, size);
1963
1964         policy = (struct kdbus_policy *) cmd_policy->policies;
1965         cmd_policy->size = offsetof(struct kdbus_cmd_policy, policies);
1966
1967         policy = make_policy_name(name);                //todo to be verified or changed when meaning will be known
1968         append_policy(cmd_policy, policy, size);
1969
1970         policy = make_policy_access(KDBUS_POLICY_ACCESS_USER, KDBUS_POLICY_OWN, getuid());
1971         append_policy(cmd_policy, policy, size);
1972
1973         policy = make_policy_access(KDBUS_POLICY_ACCESS_WORLD, KDBUS_POLICY_RECV, 0);
1974         append_policy(cmd_policy, policy, size);
1975
1976         policy = make_policy_access(KDBUS_POLICY_ACCESS_WORLD, KDBUS_POLICY_SEND, 0);
1977         append_policy(cmd_policy, policy, size);
1978
1979         if (ioctl(fd, KDBUS_CMD_EP_POLICY_SET, cmd_policy) < 0)
1980         {
1981                 dbus_set_error(error,_dbus_error_from_errno (errno), "Error setting EP policy: %s", _dbus_strerror (errno));
1982                 return FALSE;
1983         }
1984
1985         _dbus_verbose("Policy %s set correctly\n", name);
1986         return TRUE;
1987 }
1988
1989 dbus_bool_t bus_register_kdbus(char* name, DBusConnection *connection, DBusError *error)
1990 {
1991         struct kdbus_cmd_hello hello;
1992         int fd;
1993
1994         memset(&hello, 0, sizeof(hello));
1995         hello.conn_flags = KDBUS_HELLO_ACCEPT_FD |
1996                            KDBUS_HELLO_ATTACH_COMM |
1997                            KDBUS_HELLO_ATTACH_EXE |
1998                            KDBUS_HELLO_ATTACH_CMDLINE |
1999                            KDBUS_HELLO_ATTACH_CAPS |
2000                            KDBUS_HELLO_ATTACH_CGROUP |
2001                            KDBUS_HELLO_ATTACH_SECLABEL |
2002                            KDBUS_HELLO_ATTACH_AUDIT;
2003         hello.size = sizeof(struct kdbus_cmd_hello);
2004         hello.pool_size = POOL_SIZE;
2005
2006         if(!dbus_connection_get_socket(connection, &fd))
2007         {
2008                 dbus_set_error (error, "failed to get fd for bus registration", NULL);
2009                 return FALSE;
2010         }
2011         if (ioctl(fd, KDBUS_CMD_HELLO, &hello))
2012         {
2013                 dbus_set_error(error,_dbus_error_from_errno (errno), "Failed to send hello: %s", _dbus_strerror (errno));
2014                 return FALSE;
2015         }
2016
2017         _dbus_verbose("-- Our peer ID is: %llu\n", (unsigned long long)hello.id);
2018         sprintf(name, "%llu", (unsigned long long)hello.id);
2019
2020         if(!kdbus_mmap(dbus_connection_get_transport(connection)))
2021         {
2022                 dbus_set_error(error,_dbus_error_from_errno (errno), "Error when mmap: %s", _dbus_strerror (errno));
2023                 return FALSE;
2024         }
2025
2026         return TRUE;
2027 }
2028
2029 uint64_t bus_request_name_kdbus(DBusConnection *connection, const char *name, const uint64_t flags, DBusError *error)
2030 {
2031         struct kdbus_cmd_name *cmd_name;
2032         int fd;
2033         uint64_t size = sizeof(*cmd_name) + strlen(name) + 1;
2034         uint64_t flags_kdbus = 0;
2035
2036         cmd_name = alloca(size);
2037
2038         memset(cmd_name, 0, size);
2039         strcpy(cmd_name->name, name);
2040         cmd_name->size = size;
2041
2042         if(flags & DBUS_NAME_FLAG_ALLOW_REPLACEMENT)
2043                 flags_kdbus |= KDBUS_NAME_ALLOW_REPLACEMENT;
2044         if(!(flags & DBUS_NAME_FLAG_DO_NOT_QUEUE))
2045                 flags_kdbus |= KDBUS_NAME_QUEUE;
2046         if(flags & DBUS_NAME_FLAG_REPLACE_EXISTING)
2047                 flags_kdbus |= KDBUS_NAME_REPLACE_EXISTING;
2048
2049         cmd_name->conn_flags = flags_kdbus;
2050
2051         if(!dbus_connection_get_socket(connection, &fd))
2052         {
2053                 dbus_set_error (error, "failed to get fd for name request", NULL);
2054                 return FALSE;
2055         }
2056
2057         _dbus_verbose("Request name - flags sent: 0x%llx       !!!!!!!!!\n", cmd_name->conn_flags);
2058
2059         _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2060         if (ioctl(fd, KDBUS_CMD_NAME_ACQUIRE, cmd_name))
2061         {
2062                 dbus_set_error(error,_dbus_error_from_errno (errno), "error acquiring name: %s", _dbus_strerror (errno));
2063                 if(errno == EEXIST)
2064                         return DBUS_REQUEST_NAME_REPLY_EXISTS;
2065                 return FALSE;
2066         }
2067
2068         _dbus_verbose("Request name - received flag: 0x%llx       !!!!!!!!!\n", cmd_name->conn_flags);
2069
2070         if(cmd_name->conn_flags & KDBUS_NAME_IN_QUEUE)
2071                 return DBUS_REQUEST_NAME_REPLY_IN_QUEUE;
2072         else
2073                 return DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER;
2074         //todo now 1 codes are never returned -  DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER
2075 }
2076
2077 /**
2078  * Checks if the connection's transport is kdbus on the basis of its address
2079  *
2080  * @param pointer to the connection
2081  * @returns TRUE if kdbus transport, otherwise FALSE
2082  */
2083 dbus_bool_t dbus_transport_is_kdbus(DBusConnection *connection)
2084 {
2085         const char* address = _dbus_connection_get_address(connection);
2086
2087         //todo maybe assert here if address == NULL
2088         if(address == strstr(address, "kdbus:path="))
2089                 return TRUE;
2090         else
2091                 return FALSE;
2092 }
2093
2094 void dbus_bus_add_match_kdbus (DBusConnection *connection, const char *rule, DBusError *error)
2095 {
2096         struct kdbus_cmd_match cmd_match;
2097         int fd;
2098
2099         memset(&cmd_match, 0, sizeof(cmd_match));
2100
2101         if(!dbus_connection_get_socket(connection, &fd))
2102         {
2103                 dbus_set_error (error, "failed to get fd for add match", NULL);
2104                 return;
2105         }
2106
2107         cmd_match.size = sizeof(cmd_match);
2108
2109         //todo add matching rules from *rule when it will be docuemnted in kdbus
2110
2111
2112         cmd_match.src_id = KDBUS_MATCH_SRC_ID_ANY;
2113
2114         if (ioctl(fd, KDBUS_CMD_MATCH_ADD, &cmd_match))
2115                 dbus_set_error(error,_dbus_error_from_errno (errno), "error adding match: %s", _dbus_strerror (errno));
2116
2117         _dbus_verbose("Finished adding match bus rule %s             !!!!!!!!!\n", rule);
2118 }