72dac3ccc8f7e0f17c2641b82ed887d28d146278
[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 <fcntl.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <sys/ioctl.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27
28
29 #define KDBUS_ALIGN8(l) (((l) + 7) & ~7)
30
31
32 /*struct and type below copied from dbus_transport_socket.c
33  * needed for _dbus_transport_new_for_socket_kdbus and kdbus_vtable(?)
34  * todo maybe DBusTransportSocket and _dbus_transport_new_for_socket_kdbus not needed here -
35  * maybe only static const DBusTransportVTable implementation will be enough
36  */
37
38 /**
39  * Opaque object representing a socket file descriptor transport.
40  */
41 typedef struct DBusTransportSocket DBusTransportSocket;
42
43 /**
44  * Implementation details of DBusTransportSocket. All members are private.
45  */
46 struct DBusTransportSocket
47 {
48   DBusTransport base;                   /**< Parent instance */
49   int fd;                               /**< File descriptor. */
50   DBusWatch *read_watch;                /**< Watch for readability. */
51   DBusWatch *write_watch;               /**< Watch for writability. */
52
53   int max_bytes_read_per_iteration;     /**< To avoid blocking too long. */
54   int max_bytes_written_per_iteration;  /**< To avoid blocking too long. */
55
56   int message_bytes_written;            /**< Number of bytes of current
57                                          *   outgoing message that have
58                                          *   been written.
59                                          */
60   DBusString encoded_outgoing;          /**< Encoded version of current
61                                          *   outgoing message.
62                                          */
63   DBusString encoded_incoming;          /**< Encoded version of current
64                                          *   incoming data.
65                                          */
66 };
67
68
69
70 //prototypes of local functions, needed for compiler
71 int _dbus_connect_kdbus (const char *path, DBusError *error);
72 DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error);
73 DBusTransport* _dbus_transport_new_for_socket_kdbus (int fd, const DBusString *server_guid, const DBusString *address);
74 struct kdbus_policy *make_policy_name(const char *name);
75 struct kdbus_policy *make_policy_access(__u64 type, __u64 bits, __u64 id);
76 void append_policy(struct kdbus_cmd_policy *cmd_policy, struct kdbus_policy *policy, __u64 max_size);
77
78 /* Functions from dbus_transport_socket - to be modified or reused
79  *
80  */
81 static void
82 free_watches (DBusTransport *transport)
83 {
84   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
85
86   _dbus_verbose ("start\n");
87
88   if (socket_transport->read_watch)
89     {
90       if (transport->connection)
91         _dbus_connection_remove_watch_unlocked (transport->connection,
92                                                 socket_transport->read_watch);
93       _dbus_watch_invalidate (socket_transport->read_watch);
94       _dbus_watch_unref (socket_transport->read_watch);
95       socket_transport->read_watch = NULL;
96     }
97
98   if (socket_transport->write_watch)
99     {
100       if (transport->connection)
101         _dbus_connection_remove_watch_unlocked (transport->connection,
102                                                 socket_transport->write_watch);
103       _dbus_watch_invalidate (socket_transport->write_watch);
104       _dbus_watch_unref (socket_transport->write_watch);
105       socket_transport->write_watch = NULL;
106     }
107
108   _dbus_verbose ("end\n");
109 }
110
111 static void
112 socket_finalize (DBusTransport *transport)
113 {
114   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
115
116   _dbus_verbose ("\n");
117
118   free_watches (transport);
119
120   _dbus_string_free (&socket_transport->encoded_outgoing);
121   _dbus_string_free (&socket_transport->encoded_incoming);
122
123   _dbus_transport_finalize_base (transport);
124
125   _dbus_assert (socket_transport->read_watch == NULL);
126   _dbus_assert (socket_transport->write_watch == NULL);
127
128   dbus_free (transport);
129 }
130
131 static void
132 check_write_watch (DBusTransport *transport)
133 {
134   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
135   dbus_bool_t needed;
136
137   if (transport->connection == NULL)
138     return;
139
140   if (transport->disconnected)
141     {
142       _dbus_assert (socket_transport->write_watch == NULL);
143       return;
144     }
145
146   _dbus_transport_ref (transport);
147
148   if (_dbus_transport_get_is_authenticated (transport))
149     needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection);
150   else
151     {
152       if (transport->send_credentials_pending)
153         needed = TRUE;
154       else
155         {
156           DBusAuthState auth_state;
157
158           auth_state = _dbus_auth_do_work (transport->auth);
159
160           /* If we need memory we install the write watch just in case,
161            * if there's no need for it, it will get de-installed
162            * next time we try reading.
163            */
164           if (auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND ||
165               auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY)
166             needed = TRUE;
167           else
168             needed = FALSE;
169         }
170     }
171
172   _dbus_verbose ("check_write_watch(): needed = %d on connection %p watch %p fd = %d outgoing messages exist %d\n",
173                  needed, transport->connection, socket_transport->write_watch,
174                  socket_transport->fd,
175                  _dbus_connection_has_messages_to_send_unlocked (transport->connection));
176
177   _dbus_connection_toggle_watch_unlocked (transport->connection,
178                                           socket_transport->write_watch,
179                                           needed);
180
181   _dbus_transport_unref (transport);
182 }
183
184 static void
185 check_read_watch (DBusTransport *transport)
186 {
187   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
188   dbus_bool_t need_read_watch;
189
190   _dbus_verbose ("fd = %d\n",socket_transport->fd);
191
192   if (transport->connection == NULL)
193     return;
194
195   if (transport->disconnected)
196     {
197       _dbus_assert (socket_transport->read_watch == NULL);
198       return;
199     }
200
201   _dbus_transport_ref (transport);
202
203   if (_dbus_transport_get_is_authenticated (transport))
204     need_read_watch =
205       (_dbus_counter_get_size_value (transport->live_messages) < transport->max_live_messages_size) &&
206       (_dbus_counter_get_unix_fd_value (transport->live_messages) < transport->max_live_messages_unix_fds);
207   else
208     {
209       if (transport->receive_credentials_pending)
210         need_read_watch = TRUE;
211       else
212         {
213           /* The reason to disable need_read_watch when not WAITING_FOR_INPUT
214            * is to avoid spinning on the file descriptor when we're waiting
215            * to write or for some other part of the auth process
216            */
217           DBusAuthState auth_state;
218
219           auth_state = _dbus_auth_do_work (transport->auth);
220
221           /* If we need memory we install the read watch just in case,
222            * if there's no need for it, it will get de-installed
223            * next time we try reading. If we're authenticated we
224            * install it since we normally have it installed while
225            * authenticated.
226            */
227           if (auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT ||
228               auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY ||
229               auth_state == DBUS_AUTH_STATE_AUTHENTICATED)
230             need_read_watch = TRUE;
231           else
232             need_read_watch = FALSE;
233         }
234     }
235
236   _dbus_verbose ("  setting read watch enabled = %d\n", need_read_watch);
237   _dbus_connection_toggle_watch_unlocked (transport->connection,
238                                           socket_transport->read_watch,
239                                           need_read_watch);
240
241   _dbus_transport_unref (transport);
242 }
243
244 static void
245 do_io_error (DBusTransport *transport)
246 {
247   _dbus_transport_ref (transport);
248   _dbus_transport_disconnect (transport);
249   _dbus_transport_unref (transport);
250 }
251
252 /* return value is whether we successfully read any new data. */
253 static dbus_bool_t
254 read_data_into_auth (DBusTransport *transport,
255                      dbus_bool_t   *oom)
256 {
257   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
258   DBusString *buffer;
259   int bytes_read;
260
261   *oom = FALSE;
262
263   _dbus_auth_get_buffer (transport->auth, &buffer);
264
265   bytes_read = _dbus_read_socket (socket_transport->fd,
266                                   buffer, socket_transport->max_bytes_read_per_iteration);
267
268   _dbus_auth_return_buffer (transport->auth, buffer,
269                             bytes_read > 0 ? bytes_read : 0);
270
271   if (bytes_read > 0)
272     {
273       _dbus_verbose (" read %d bytes in auth phase\n", bytes_read);
274
275       return TRUE;
276     }
277   else if (bytes_read < 0)
278     {
279       /* EINTR already handled for us */
280
281       if (_dbus_get_is_errno_enomem ())
282         {
283           *oom = TRUE;
284         }
285       else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
286         ; /* do nothing, just return FALSE below */
287       else
288         {
289           _dbus_verbose ("Error reading from remote app: %s\n",
290                          _dbus_strerror_from_errno ());
291           do_io_error (transport);
292         }
293
294       return FALSE;
295     }
296   else
297     {
298       _dbus_assert (bytes_read == 0);
299
300       _dbus_verbose ("Disconnected from remote app\n");
301       do_io_error (transport);
302
303       return FALSE;
304     }
305 }
306
307 /* Return value is whether we successfully wrote any bytes */
308 static dbus_bool_t
309 write_data_from_auth (DBusTransport *transport)
310 {
311   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
312   int bytes_written;
313   const DBusString *buffer;
314
315   if (!_dbus_auth_get_bytes_to_send (transport->auth,
316                                      &buffer))
317     return FALSE;
318
319   bytes_written = _dbus_write_socket (socket_transport->fd,
320                                       buffer,
321                                       0, _dbus_string_get_length (buffer));
322
323   if (bytes_written > 0)
324     {
325       _dbus_auth_bytes_sent (transport->auth, bytes_written);
326       return TRUE;
327     }
328   else if (bytes_written < 0)
329     {
330       /* EINTR already handled for us */
331
332       if (_dbus_get_is_errno_eagain_or_ewouldblock ())
333         ;
334       else
335         {
336           _dbus_verbose ("Error writing to remote app: %s\n",
337                          _dbus_strerror_from_errno ());
338           do_io_error (transport);
339         }
340     }
341
342   return FALSE;
343 }
344
345 /* FALSE on OOM */
346 static dbus_bool_t
347 exchange_credentials (DBusTransport *transport,
348                       dbus_bool_t    do_reading,
349                       dbus_bool_t    do_writing)
350 {
351   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
352   DBusError error = DBUS_ERROR_INIT;
353
354   _dbus_verbose ("exchange_credentials: do_reading = %d, do_writing = %d\n",
355                   do_reading, do_writing);
356
357   if (do_writing && transport->send_credentials_pending)
358     {
359       if (_dbus_send_credentials_socket (socket_transport->fd,
360                                          &error))
361         {
362           transport->send_credentials_pending = FALSE;
363         }
364       else
365         {
366           _dbus_verbose ("Failed to write credentials: %s\n", error.message);
367           dbus_error_free (&error);
368           do_io_error (transport);
369         }
370     }
371
372   if (do_reading && transport->receive_credentials_pending)
373     {
374       /* FIXME this can fail due to IO error _or_ OOM, broken
375        * (somewhat tricky to fix since the OOM error can be set after
376        * we already read the credentials byte, so basically we need to
377        * separate reading the byte and storing it in the
378        * transport->credentials). Does not really matter for now
379        * because storing in credentials never actually fails on unix.
380        */
381       if (_dbus_read_credentials_socket (socket_transport->fd,
382                                          transport->credentials,
383                                          &error))
384         {
385           transport->receive_credentials_pending = FALSE;
386         }
387       else
388         {
389           _dbus_verbose ("Failed to read credentials %s\n", error.message);
390           dbus_error_free (&error);
391           do_io_error (transport);
392         }
393     }
394
395   if (!(transport->send_credentials_pending ||
396         transport->receive_credentials_pending))
397     {
398       if (!_dbus_auth_set_credentials (transport->auth,
399                                        transport->credentials))
400         return FALSE;
401     }
402
403   return TRUE;
404 }
405
406 static dbus_bool_t
407 do_authentication (DBusTransport *transport,
408                    dbus_bool_t    do_reading,
409                    dbus_bool_t    do_writing,
410                    dbus_bool_t   *auth_completed)
411 {
412   dbus_bool_t oom;
413   dbus_bool_t orig_auth_state;
414
415   oom = FALSE;
416
417   orig_auth_state = _dbus_transport_get_is_authenticated (transport);
418
419   /* This is essential to avoid the check_write_watch() at the end,
420    * we don't want to add a write watch in do_iteration before
421    * we try writing and get EAGAIN
422    */
423   if (orig_auth_state)
424     {
425       if (auth_completed)
426         *auth_completed = FALSE;
427       return TRUE;
428     }
429
430   _dbus_transport_ref (transport);
431
432   while (!_dbus_transport_get_is_authenticated (transport) &&
433          _dbus_transport_get_is_connected (transport))
434     {
435       if (!exchange_credentials (transport, do_reading, do_writing))
436         {
437           /* OOM */
438           oom = TRUE;
439           goto out;
440         }
441
442       if (transport->send_credentials_pending ||
443           transport->receive_credentials_pending)
444         {
445           _dbus_verbose ("send_credentials_pending = %d receive_credentials_pending = %d\n",
446                          transport->send_credentials_pending,
447                          transport->receive_credentials_pending);
448           goto out;
449         }
450
451 #define TRANSPORT_SIDE(t) ((t)->is_server ? "server" : "client")
452       switch (_dbus_auth_do_work (transport->auth))
453         {
454         case DBUS_AUTH_STATE_WAITING_FOR_INPUT:
455           _dbus_verbose (" %s auth state: waiting for input\n",
456                          TRANSPORT_SIDE (transport));
457           if (!do_reading || !read_data_into_auth (transport, &oom))
458             goto out;
459           break;
460
461         case DBUS_AUTH_STATE_WAITING_FOR_MEMORY:
462           _dbus_verbose (" %s auth state: waiting for memory\n",
463                          TRANSPORT_SIDE (transport));
464           oom = TRUE;
465           goto out;
466           break;
467
468         case DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND:
469           _dbus_verbose (" %s auth state: bytes to send\n",
470                          TRANSPORT_SIDE (transport));
471           if (!do_writing || !write_data_from_auth (transport))
472             goto out;
473           break;
474
475         case DBUS_AUTH_STATE_NEED_DISCONNECT:
476           _dbus_verbose (" %s auth state: need to disconnect\n",
477                          TRANSPORT_SIDE (transport));
478           do_io_error (transport);
479           break;
480
481         case DBUS_AUTH_STATE_AUTHENTICATED:
482           _dbus_verbose (" %s auth state: authenticated\n",
483                          TRANSPORT_SIDE (transport));
484           break;
485         }
486     }
487
488  out:
489   if (auth_completed)
490     *auth_completed = (orig_auth_state != _dbus_transport_get_is_authenticated (transport));
491
492   check_read_watch (transport);
493   check_write_watch (transport);
494   _dbus_transport_unref (transport);
495
496   if (oom)
497     return FALSE;
498   else
499     return TRUE;
500 }
501
502 /* returns false on oom */
503 static dbus_bool_t
504 do_writing (DBusTransport *transport)
505 {
506   int total;
507   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
508   dbus_bool_t oom;
509
510   /* No messages without authentication! */
511   if (!_dbus_transport_get_is_authenticated (transport))
512     {
513       _dbus_verbose ("Not authenticated, not writing anything\n");
514       return TRUE;
515     }
516
517   if (transport->disconnected)
518     {
519       _dbus_verbose ("Not connected, not writing anything\n");
520       return TRUE;
521     }
522
523 #if 1
524   _dbus_verbose ("do_writing(), have_messages = %d, fd = %d\n",
525                  _dbus_connection_has_messages_to_send_unlocked (transport->connection),
526                  socket_transport->fd);
527 #endif
528
529   oom = FALSE;
530   total = 0;
531
532   while (!transport->disconnected &&
533          _dbus_connection_has_messages_to_send_unlocked (transport->connection))
534     {
535       int bytes_written;
536       DBusMessage *message;
537       const DBusString *header;
538       const DBusString *body;
539       int header_len, body_len;
540       int total_bytes_to_write;
541
542       if (total > socket_transport->max_bytes_written_per_iteration)
543         {
544           _dbus_verbose ("%d bytes exceeds %d bytes written per iteration, returning\n",
545                          total, socket_transport->max_bytes_written_per_iteration);
546           goto out;
547         }
548
549       message = _dbus_connection_get_message_to_send (transport->connection);
550       _dbus_assert (message != NULL);
551       dbus_message_lock (message);
552
553 #if 0
554       _dbus_verbose ("writing message %p\n", message);
555 #endif
556
557       _dbus_message_get_network_data (message,
558                                       &header, &body);
559
560       header_len = _dbus_string_get_length (header);
561       body_len = _dbus_string_get_length (body);
562
563       if (_dbus_auth_needs_encoding (transport->auth))
564         {
565           /* Does fd passing even make sense with encoded data? */
566           _dbus_assert(!DBUS_TRANSPORT_CAN_SEND_UNIX_FD(transport));
567
568           if (_dbus_string_get_length (&socket_transport->encoded_outgoing) == 0)
569             {
570               if (!_dbus_auth_encode_data (transport->auth,
571                                            header, &socket_transport->encoded_outgoing))
572                 {
573                   oom = TRUE;
574                   goto out;
575                 }
576
577               if (!_dbus_auth_encode_data (transport->auth,
578                                            body, &socket_transport->encoded_outgoing))
579                 {
580                   _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
581                   oom = TRUE;
582                   goto out;
583                 }
584             }
585
586           total_bytes_to_write = _dbus_string_get_length (&socket_transport->encoded_outgoing);
587
588 #if 0
589           _dbus_verbose ("encoded message is %d bytes\n",
590                          total_bytes_to_write);
591 #endif
592
593           bytes_written =
594             _dbus_write_socket (socket_transport->fd,
595                                 &socket_transport->encoded_outgoing,
596                                 socket_transport->message_bytes_written,
597                                 total_bytes_to_write - socket_transport->message_bytes_written);
598         }
599       else
600         {
601           total_bytes_to_write = header_len + body_len;
602
603 #if 0
604           _dbus_verbose ("message is %d bytes\n",
605                          total_bytes_to_write);
606 #endif
607
608 #ifdef HAVE_UNIX_FD_PASSING
609           if (socket_transport->message_bytes_written <= 0 && DBUS_TRANSPORT_CAN_SEND_UNIX_FD(transport))
610             {
611               /* Send the fds along with the first byte of the message */
612               const int *unix_fds;
613               unsigned n;
614
615               _dbus_message_get_unix_fds(message, &unix_fds, &n);
616
617               bytes_written =
618                 _dbus_write_socket_with_unix_fds_two (socket_transport->fd,
619                                                       header,
620                                                       socket_transport->message_bytes_written,
621                                                       header_len - socket_transport->message_bytes_written,
622                                                       body,
623                                                       0, body_len,
624                                                       unix_fds,
625                                                       n);
626
627               if (bytes_written > 0 && n > 0)
628                 _dbus_verbose("Wrote %i unix fds\n", n);
629             }
630           else
631 #endif
632             {
633               if (socket_transport->message_bytes_written < header_len)
634                 {
635                   bytes_written =
636                     _dbus_write_socket_two (socket_transport->fd,
637                                             header,
638                                             socket_transport->message_bytes_written,
639                                             header_len - socket_transport->message_bytes_written,
640                                             body,
641                                             0, body_len);
642                 }
643               else
644                 {
645                   bytes_written =
646                     _dbus_write_socket (socket_transport->fd,
647                                         body,
648                                         (socket_transport->message_bytes_written - header_len),
649                                         body_len -
650                                         (socket_transport->message_bytes_written - header_len));
651                 }
652             }
653         }
654
655       if (bytes_written < 0)
656         {
657           /* EINTR already handled for us */
658
659           /* For some discussion of why we also ignore EPIPE here, see
660            * http://lists.freedesktop.org/archives/dbus/2008-March/009526.html
661            */
662
663           if (_dbus_get_is_errno_eagain_or_ewouldblock () || _dbus_get_is_errno_epipe ())
664             goto out;
665           else
666             {
667               _dbus_verbose ("Error writing to remote app: %s\n",
668                              _dbus_strerror_from_errno ());
669               do_io_error (transport);
670               goto out;
671             }
672         }
673       else
674         {
675           _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
676                          total_bytes_to_write);
677
678           total += bytes_written;
679           socket_transport->message_bytes_written += bytes_written;
680
681           _dbus_assert (socket_transport->message_bytes_written <=
682                         total_bytes_to_write);
683
684           if (socket_transport->message_bytes_written == total_bytes_to_write)
685             {
686               socket_transport->message_bytes_written = 0;
687               _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
688               _dbus_string_compact (&socket_transport->encoded_outgoing, 2048);
689
690               _dbus_connection_message_sent_unlocked (transport->connection,
691                                                       message);
692             }
693         }
694     }
695
696  out:
697   if (oom)
698     return FALSE;
699   else
700     return TRUE;
701 }
702
703 /* returns false on out-of-memory */
704 static dbus_bool_t
705 do_reading (DBusTransport *transport)
706 {
707   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
708   DBusString *buffer;
709   int bytes_read;
710   int total;
711   dbus_bool_t oom;
712
713   _dbus_verbose ("fd = %d\n",socket_transport->fd);
714
715   /* No messages without authentication! */
716   if (!_dbus_transport_get_is_authenticated (transport))
717     return TRUE;
718
719   oom = FALSE;
720
721   total = 0;
722
723  again:
724
725   /* See if we've exceeded max messages and need to disable reading */
726   check_read_watch (transport);
727
728   if (total > socket_transport->max_bytes_read_per_iteration)
729     {
730       _dbus_verbose ("%d bytes exceeds %d bytes read per iteration, returning\n",
731                      total, socket_transport->max_bytes_read_per_iteration);
732       goto out;
733     }
734
735   _dbus_assert (socket_transport->read_watch != NULL ||
736                 transport->disconnected);
737
738   if (transport->disconnected)
739     goto out;
740
741   if (!dbus_watch_get_enabled (socket_transport->read_watch))
742     return TRUE;
743
744   if (_dbus_auth_needs_decoding (transport->auth))
745     {
746       /* Does fd passing even make sense with encoded data? */
747       _dbus_assert(!DBUS_TRANSPORT_CAN_SEND_UNIX_FD(transport));
748
749       if (_dbus_string_get_length (&socket_transport->encoded_incoming) > 0)
750         bytes_read = _dbus_string_get_length (&socket_transport->encoded_incoming);
751       else
752         bytes_read = _dbus_read_socket (socket_transport->fd,
753                                         &socket_transport->encoded_incoming,
754                                         socket_transport->max_bytes_read_per_iteration);
755
756       _dbus_assert (_dbus_string_get_length (&socket_transport->encoded_incoming) ==
757                     bytes_read);
758
759       if (bytes_read > 0)
760         {
761           int orig_len;
762
763           _dbus_message_loader_get_buffer (transport->loader,
764                                            &buffer);
765
766           orig_len = _dbus_string_get_length (buffer);
767
768           if (!_dbus_auth_decode_data (transport->auth,
769                                        &socket_transport->encoded_incoming,
770                                        buffer))
771             {
772               _dbus_verbose ("Out of memory decoding incoming data\n");
773               _dbus_message_loader_return_buffer (transport->loader,
774                                               buffer,
775                                               _dbus_string_get_length (buffer) - orig_len);
776
777               oom = TRUE;
778               goto out;
779             }
780
781           _dbus_message_loader_return_buffer (transport->loader,
782                                               buffer,
783                                               _dbus_string_get_length (buffer) - orig_len);
784
785           _dbus_string_set_length (&socket_transport->encoded_incoming, 0);
786           _dbus_string_compact (&socket_transport->encoded_incoming, 2048);
787         }
788     }
789   else
790     {
791       _dbus_message_loader_get_buffer (transport->loader,
792                                        &buffer);
793
794 #ifdef HAVE_UNIX_FD_PASSING
795       if (DBUS_TRANSPORT_CAN_SEND_UNIX_FD(transport))
796         {
797           int *fds, n_fds;
798
799           if (!_dbus_message_loader_get_unix_fds(transport->loader, &fds, &n_fds))
800             {
801               _dbus_verbose ("Out of memory reading file descriptors\n");
802               _dbus_message_loader_return_buffer (transport->loader, buffer, 0);
803               oom = TRUE;
804               goto out;
805             }
806
807           bytes_read = _dbus_read_socket_with_unix_fds(socket_transport->fd,
808                                                        buffer,
809                                                        socket_transport->max_bytes_read_per_iteration,
810                                                        fds, &n_fds);
811
812           if (bytes_read >= 0 && n_fds > 0)
813             _dbus_verbose("Read %i unix fds\n", n_fds);
814
815           _dbus_message_loader_return_unix_fds(transport->loader, fds, bytes_read < 0 ? 0 : n_fds);
816         }
817       else
818 #endif
819         {
820           bytes_read = _dbus_read_socket (socket_transport->fd,
821                                           buffer, socket_transport->max_bytes_read_per_iteration);
822         }
823
824       _dbus_message_loader_return_buffer (transport->loader,
825                                           buffer,
826                                           bytes_read < 0 ? 0 : bytes_read);
827     }
828
829   if (bytes_read < 0)
830     {
831       /* EINTR already handled for us */
832
833       if (_dbus_get_is_errno_enomem ())
834         {
835           _dbus_verbose ("Out of memory in read()/do_reading()\n");
836           oom = TRUE;
837           goto out;
838         }
839       else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
840         goto out;
841       else
842         {
843           _dbus_verbose ("Error reading from remote app: %s\n",
844                          _dbus_strerror_from_errno ());
845           do_io_error (transport);
846           goto out;
847         }
848     }
849   else if (bytes_read == 0)
850     {
851       _dbus_verbose ("Disconnected from remote app\n");
852       do_io_error (transport);
853       goto out;
854     }
855   else
856     {
857       _dbus_verbose (" read %d bytes\n", bytes_read);
858
859       total += bytes_read;
860
861       if (!_dbus_transport_queue_messages (transport))
862         {
863           oom = TRUE;
864           _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
865           goto out;
866         }
867
868       /* Try reading more data until we get EAGAIN and return, or
869        * exceed max bytes per iteration.  If in blocking mode of
870        * course we'll block instead of returning.
871        */
872       goto again;
873     }
874
875  out:
876   if (oom)
877     return FALSE;
878   else
879     return TRUE;
880 }
881
882 static dbus_bool_t
883 unix_error_with_read_to_come (DBusTransport *itransport,
884                               DBusWatch     *watch,
885                               unsigned int   flags)
886 {
887   DBusTransportSocket *transport = (DBusTransportSocket *) itransport;
888
889   if (!(flags & DBUS_WATCH_HANGUP || flags & DBUS_WATCH_ERROR))
890     return FALSE;
891
892   /* If we have a read watch enabled ...
893      we -might have data incoming ... => handle the HANGUP there */
894   if (watch != transport->read_watch &&
895       _dbus_watch_get_enabled (transport->read_watch))
896     return FALSE;
897
898   return TRUE;
899 }
900
901 static dbus_bool_t
902 socket_handle_watch (DBusTransport *transport,
903                    DBusWatch     *watch,
904                    unsigned int   flags)
905 {
906   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
907
908   _dbus_assert (watch == socket_transport->read_watch ||
909                 watch == socket_transport->write_watch);
910   _dbus_assert (watch != NULL);
911
912   /* If we hit an error here on a write watch, don't disconnect the transport yet because data can
913    * still be in the buffer and do_reading may need several iteration to read
914    * it all (because of its max_bytes_read_per_iteration limit).
915    */
916   if (!(flags & DBUS_WATCH_READABLE) && unix_error_with_read_to_come (transport, watch, flags))
917     {
918       _dbus_verbose ("Hang up or error on watch\n");
919       _dbus_transport_disconnect (transport);
920       return TRUE;
921     }
922
923   if (watch == socket_transport->read_watch &&
924       (flags & DBUS_WATCH_READABLE))
925     {
926       dbus_bool_t auth_finished;
927 #if 1
928       _dbus_verbose ("handling read watch %p flags = %x\n",
929                      watch, flags);
930 #endif
931       if (!do_authentication (transport, TRUE, FALSE, &auth_finished))
932         return FALSE;
933
934       /* We don't want to do a read immediately following
935        * a successful authentication.  This is so we
936        * have a chance to propagate the authentication
937        * state further up.  Specifically, we need to
938        * process any pending data from the auth object.
939        */
940       if (!auth_finished)
941         {
942           if (!do_reading (transport))
943             {
944               _dbus_verbose ("no memory to read\n");
945               return FALSE;
946             }
947         }
948       else
949         {
950           _dbus_verbose ("Not reading anything since we just completed the authentication\n");
951         }
952     }
953   else if (watch == socket_transport->write_watch &&
954            (flags & DBUS_WATCH_WRITABLE))
955     {
956 #if 1
957       _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n",
958                      _dbus_connection_has_messages_to_send_unlocked (transport->connection));
959 #endif
960       if (!do_authentication (transport, FALSE, TRUE, NULL))
961         return FALSE;
962
963       if (!do_writing (transport))
964         {
965           _dbus_verbose ("no memory to write\n");
966           return FALSE;
967         }
968
969       /* See if we still need the write watch */
970       check_write_watch (transport);
971     }
972 #ifdef DBUS_ENABLE_VERBOSE_MODE
973   else
974     {
975       if (watch == socket_transport->read_watch)
976         _dbus_verbose ("asked to handle read watch with non-read condition 0x%x\n",
977                        flags);
978       else if (watch == socket_transport->write_watch)
979         _dbus_verbose ("asked to handle write watch with non-write condition 0x%x\n",
980                        flags);
981       else
982         _dbus_verbose ("asked to handle watch %p on fd %d that we don't recognize\n",
983                        watch, dbus_watch_get_socket (watch));
984     }
985 #endif /* DBUS_ENABLE_VERBOSE_MODE */
986
987   return TRUE;
988 }
989
990 static void
991 socket_disconnect (DBusTransport *transport)
992 {
993   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
994
995   _dbus_verbose ("\n");
996
997   free_watches (transport);
998
999   _dbus_close_socket (socket_transport->fd, NULL);
1000   socket_transport->fd = -1;
1001 }
1002
1003 static dbus_bool_t
1004 socket_connection_set (DBusTransport *transport)
1005 {
1006   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1007
1008   _dbus_watch_set_handler (socket_transport->write_watch,
1009                            _dbus_connection_handle_watch,
1010                            transport->connection, NULL);
1011
1012   _dbus_watch_set_handler (socket_transport->read_watch,
1013                            _dbus_connection_handle_watch,
1014                            transport->connection, NULL);
1015
1016   if (!_dbus_connection_add_watch_unlocked (transport->connection,
1017                                             socket_transport->write_watch))
1018     return FALSE;
1019
1020   if (!_dbus_connection_add_watch_unlocked (transport->connection,
1021                                             socket_transport->read_watch))
1022     {
1023       _dbus_connection_remove_watch_unlocked (transport->connection,
1024                                               socket_transport->write_watch);
1025       return FALSE;
1026     }
1027
1028   check_read_watch (transport);
1029   check_write_watch (transport);
1030
1031   return TRUE;
1032 }
1033
1034 /**
1035  * @todo We need to have a way to wake up the select sleep if
1036  * a new iteration request comes in with a flag (read/write) that
1037  * we're not currently serving. Otherwise a call that just reads
1038  * could block a write call forever (if there are no incoming
1039  * messages).
1040  */
1041 static  void
1042 socket_do_iteration (DBusTransport *transport,
1043                    unsigned int   flags,
1044                    int            timeout_milliseconds)
1045 {
1046   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1047   DBusPollFD poll_fd;
1048   int poll_res;
1049   int poll_timeout;
1050
1051   _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p fd = %d\n",
1052                  flags & DBUS_ITERATION_DO_READING ? "read" : "",
1053                  flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
1054                  timeout_milliseconds,
1055                  socket_transport->read_watch,
1056                  socket_transport->write_watch,
1057                  socket_transport->fd);
1058
1059   /* the passed in DO_READING/DO_WRITING flags indicate whether to
1060    * read/write messages, but regardless of those we may need to block
1061    * for reading/writing to do auth.  But if we do reading for auth,
1062    * we don't want to read any messages yet if not given DO_READING.
1063    */
1064
1065   poll_fd.fd = socket_transport->fd;
1066   poll_fd.events = 0;
1067
1068   if (_dbus_transport_get_is_authenticated (transport))
1069     {
1070       /* This is kind of a hack; if we have stuff to write, then try
1071        * to avoid the poll. This is probably about a 5% speedup on an
1072        * echo client/server.
1073        *
1074        * If both reading and writing were requested, we want to avoid this
1075        * since it could have funky effects:
1076        *   - both ends spinning waiting for the other one to read
1077        *     data so they can finish writing
1078        *   - prioritizing all writing ahead of reading
1079        */
1080       if ((flags & DBUS_ITERATION_DO_WRITING) &&
1081           !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) &&
1082           !transport->disconnected &&
1083           _dbus_connection_has_messages_to_send_unlocked (transport->connection))
1084         {
1085           do_writing (transport);
1086
1087           if (transport->disconnected ||
1088               !_dbus_connection_has_messages_to_send_unlocked (transport->connection))
1089             goto out;
1090         }
1091
1092       /* If we get here, we decided to do the poll() after all */
1093       _dbus_assert (socket_transport->read_watch);
1094       if (flags & DBUS_ITERATION_DO_READING)
1095         poll_fd.events |= _DBUS_POLLIN;
1096
1097       _dbus_assert (socket_transport->write_watch);
1098       if (flags & DBUS_ITERATION_DO_WRITING)
1099         poll_fd.events |= _DBUS_POLLOUT;
1100     }
1101   else
1102     {
1103       DBusAuthState auth_state;
1104
1105       auth_state = _dbus_auth_do_work (transport->auth);
1106
1107       if (transport->receive_credentials_pending ||
1108           auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT)
1109         poll_fd.events |= _DBUS_POLLIN;
1110
1111       if (transport->send_credentials_pending ||
1112           auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND)
1113         poll_fd.events |= _DBUS_POLLOUT;
1114     }
1115
1116   if (poll_fd.events)
1117     {
1118       if (flags & DBUS_ITERATION_BLOCK)
1119         poll_timeout = timeout_milliseconds;
1120       else
1121         poll_timeout = 0;
1122
1123       /* For blocking selects we drop the connection lock here
1124        * to avoid blocking out connection access during a potentially
1125        * indefinite blocking call. The io path is still protected
1126        * by the io_path_cond condvar, so we won't reenter this.
1127        */
1128       if (flags & DBUS_ITERATION_BLOCK)
1129         {
1130           _dbus_verbose ("unlock pre poll\n");
1131           _dbus_connection_unlock (transport->connection);
1132         }
1133
1134     again:
1135       poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
1136
1137       if (poll_res < 0 && _dbus_get_is_errno_eintr ())
1138         goto again;
1139
1140       if (flags & DBUS_ITERATION_BLOCK)
1141         {
1142           _dbus_verbose ("lock post poll\n");
1143           _dbus_connection_lock (transport->connection);
1144         }
1145
1146       if (poll_res >= 0)
1147         {
1148           if (poll_res == 0)
1149             poll_fd.revents = 0; /* some concern that posix does not guarantee this;
1150                                   * valgrind flags it as an error. though it probably
1151                                   * is guaranteed on linux at least.
1152                                   */
1153
1154           if (poll_fd.revents & _DBUS_POLLERR)
1155             do_io_error (transport);
1156           else
1157             {
1158               dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
1159               dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0;
1160               dbus_bool_t authentication_completed;
1161
1162               _dbus_verbose ("in iteration, need_read=%d need_write=%d\n",
1163                              need_read, need_write);
1164               do_authentication (transport, need_read, need_write,
1165                                  &authentication_completed);
1166
1167               /* See comment in socket_handle_watch. */
1168               if (authentication_completed)
1169                 goto out;
1170
1171               if (need_read && (flags & DBUS_ITERATION_DO_READING))
1172                 do_reading (transport);
1173               if (need_write && (flags & DBUS_ITERATION_DO_WRITING))
1174                 do_writing (transport);
1175             }
1176         }
1177       else
1178         {
1179           _dbus_verbose ("Error from _dbus_poll(): %s\n",
1180                          _dbus_strerror_from_errno ());
1181         }
1182     }
1183
1184
1185  out:
1186   /* We need to install the write watch only if we did not
1187    * successfully write everything. Note we need to be careful that we
1188    * don't call check_write_watch *before* do_writing, since it's
1189    * inefficient to add the write watch, and we can avoid it most of
1190    * the time since we can write immediately.
1191    *
1192    * However, we MUST always call check_write_watch(); DBusConnection code
1193    * relies on the fact that running an iteration will notice that
1194    * messages are pending.
1195    */
1196   check_write_watch (transport);
1197
1198   _dbus_verbose (" ... leaving do_iteration()\n");
1199 }
1200
1201 static void
1202 socket_live_messages_changed (DBusTransport *transport)
1203 {
1204   /* See if we should look for incoming messages again */
1205   check_read_watch (transport);
1206 }
1207
1208
1209 static dbus_bool_t
1210 socket_get_socket_fd (DBusTransport *transport,
1211                       int           *fd_p)
1212 {
1213   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1214
1215   *fd_p = socket_transport->fd;
1216
1217   return TRUE;
1218 }
1219
1220 static const DBusTransportVTable kdbus_vtable = {
1221   socket_finalize,
1222   socket_handle_watch,
1223   socket_disconnect,
1224   socket_connection_set,
1225   socket_do_iteration,
1226   socket_live_messages_changed,
1227   socket_get_socket_fd
1228 };
1229
1230 /**
1231  * Creates a new transport for the given kdbus file descriptor.  The file
1232  * descriptor must be nonblocking (use _dbus_set_fd_nonblocking() to
1233  * make it so).
1234  *
1235  * @param fd the file descriptor.
1236  * @param server_guid non-#NULL if this transport is on the server side of a connection
1237  * @param address the transport's address
1238  * @returns the new transport, or #NULL if no memory.
1239  */
1240 DBusTransport*
1241 _dbus_transport_new_for_socket_kdbus (int       fd,
1242                                           const DBusString *server_guid,
1243                                           const DBusString *address)
1244 {
1245         DBusTransportSocket *socket_transport;
1246
1247   socket_transport = dbus_new0 (DBusTransportSocket, 1);
1248   if (socket_transport == NULL)
1249     return NULL;
1250
1251   if (!_dbus_string_init (&socket_transport->encoded_outgoing))
1252     goto failed_0;
1253
1254   if (!_dbus_string_init (&socket_transport->encoded_incoming))
1255     goto failed_1;
1256
1257   socket_transport->write_watch = _dbus_watch_new (fd,
1258                                                  DBUS_WATCH_WRITABLE,
1259                                                  FALSE,
1260                                                  NULL, NULL, NULL);
1261   if (socket_transport->write_watch == NULL)
1262     goto failed_2;
1263
1264   socket_transport->read_watch = _dbus_watch_new (fd,
1265                                                 DBUS_WATCH_READABLE,
1266                                                 FALSE,
1267                                                 NULL, NULL, NULL);
1268   if (socket_transport->read_watch == NULL)
1269     goto failed_3;
1270
1271   if (!_dbus_transport_init_base (&socket_transport->base,
1272                                   &kdbus_vtable,
1273                                   server_guid, address))
1274     goto failed_4;
1275
1276 #ifdef HAVE_UNIX_FD_PASSING
1277   _dbus_auth_set_unix_fd_possible(socket_transport->base.auth, _dbus_socket_can_pass_unix_fd(fd));
1278 #endif
1279
1280   socket_transport->fd = fd;
1281   socket_transport->message_bytes_written = 0;
1282
1283   /* These values should probably be tunable or something. */
1284   socket_transport->max_bytes_read_per_iteration = 2048;
1285   socket_transport->max_bytes_written_per_iteration = 2048;
1286
1287   return (DBusTransport*) socket_transport;
1288
1289  failed_4:
1290   _dbus_watch_invalidate (socket_transport->read_watch);
1291   _dbus_watch_unref (socket_transport->read_watch);
1292  failed_3:
1293   _dbus_watch_invalidate (socket_transport->write_watch);
1294   _dbus_watch_unref (socket_transport->write_watch);
1295  failed_2:
1296   _dbus_string_free (&socket_transport->encoded_incoming);
1297  failed_1:
1298   _dbus_string_free (&socket_transport->encoded_outgoing);
1299  failed_0:
1300   dbus_free (socket_transport);
1301   return NULL;
1302 }
1303
1304
1305 /**
1306  * Creates a connection to the kdbus bus
1307   *
1308  * This will set FD_CLOEXEC for the socket returned.
1309  *
1310  * @param path the path to UNIX domain socket
1311  * @param error return location for error code
1312  * @returns connection file descriptor or -1 on error
1313  */
1314 int _dbus_connect_kdbus (const char *path, DBusError *error)
1315 {
1316         int fd;
1317
1318         _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1319         _dbus_verbose ("connecting to kdbus bus %s\n", path);
1320
1321         fd = open(path, O_RDWR|O_CLOEXEC|O_NONBLOCK); //[RP] | O_NONBLOCK added here, in dbus added separately in section commented out below
1322         if (fd < 0)
1323         {
1324                 dbus_set_error(error, _dbus_error_from_errno (errno), "Failed to open file descriptor: %s", _dbus_strerror (errno));
1325                 _DBUS_ASSERT_ERROR_IS_SET(error);
1326                 return -1;  //[RP] not needed here if commented block below is removed
1327         }
1328
1329         /*if (!_dbus_set_fd_nonblocking (fd, error))
1330     {
1331                 _DBUS_ASSERT_ERROR_IS_SET (error);
1332                 _dbus_close (fd, NULL);
1333                 return -1;
1334     }*/
1335
1336         return fd;
1337 }
1338
1339
1340 /**
1341  * Creates a new transport for kdbus.
1342  * This creates a client-side of a transport.
1343  *
1344  * @param path the path to the domain socket.
1345  * @param error address where an error can be returned.
1346  * @returns a new transport, or #NULL on failure.
1347  */
1348 DBusTransport* _dbus_transport_new_for_kdbus (const char *path, DBusError *error)
1349 {
1350         int fd;
1351         DBusTransport *transport;
1352         DBusString address;
1353
1354         _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1355
1356         if (!_dbus_string_init (&address))
1357     {
1358                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1359                 return NULL;
1360     }
1361
1362         fd = -1;
1363
1364         if ((!_dbus_string_append (&address, "kdbus:path=")) || (!_dbus_string_append (&address, path)))
1365     {
1366                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1367                 goto failed_0;
1368     }
1369
1370         fd = _dbus_connect_kdbus (path, error);
1371 //      fd = _dbus_connect_unix_socket (path, error);
1372         if (fd < 0)
1373     {
1374                 _DBUS_ASSERT_ERROR_IS_SET (error);
1375                 goto failed_0;
1376     }
1377
1378         _dbus_verbose ("Successfully connected to kdbus bus %s\n", path);
1379
1380         transport = _dbus_transport_new_for_socket_kdbus (fd, NULL, &address);  //todo
1381         if (transport == NULL)
1382     {
1383                 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1384                 goto failed_1;
1385     }
1386
1387         _dbus_string_free (&address);
1388
1389         return transport;
1390
1391         failed_1:
1392                 _dbus_close_socket (fd, NULL);
1393         failed_0:
1394                 _dbus_string_free (&address);
1395         return NULL;
1396 }
1397
1398
1399 /**
1400  * Opens kdbus transport.
1401  *
1402  * @param entry the address entry to try opening
1403  * @param transport_p return location for the opened transport
1404  * @param error error to be set
1405  * @returns result of the attempt
1406  */
1407 DBusTransportOpenResult _dbus_transport_open_kdbus(DBusAddressEntry  *entry,
1408                                                            DBusTransport    **transport_p,
1409                                                            DBusError         *error)
1410 {
1411         const char *method;
1412
1413         method = dbus_address_entry_get_method (entry);
1414         _dbus_assert (method != NULL);
1415
1416         if (strcmp (method, "kdbus") == 0)
1417     {
1418                 const char *path = dbus_address_entry_get_value (entry, "path");
1419
1420                 if (path == NULL)
1421         {
1422                         _dbus_set_bad_address (error, "kdbus", "path", NULL);
1423                         return DBUS_TRANSPORT_OPEN_BAD_ADDRESS;
1424         }
1425
1426         *transport_p = _dbus_transport_new_for_kdbus (path, error);
1427
1428         if (*transport_p == NULL)
1429         {
1430                 _DBUS_ASSERT_ERROR_IS_SET (error);
1431                 return DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT;
1432         }
1433         else
1434         {
1435                 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1436                 return DBUS_TRANSPORT_OPEN_OK;
1437         }
1438     }
1439         else
1440     {
1441                 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1442                 return DBUS_TRANSPORT_OPEN_NOT_HANDLED;
1443     }
1444 }
1445
1446 struct kdbus_policy *make_policy_name(const char *name)
1447 {
1448         struct kdbus_policy *p;
1449         __u64 size;
1450
1451         size = offsetof(struct kdbus_policy, name) + strlen(name) + 1;
1452         p = malloc(size);
1453         if (!p)
1454                 return NULL;
1455         memset(p, 0, size);
1456         p->size = size;
1457         p->type = KDBUS_POLICY_NAME;
1458         strcpy(p->name, name);
1459
1460         return p;
1461 }
1462
1463 struct kdbus_policy *make_policy_access(__u64 type, __u64 bits, __u64 id)
1464 {
1465         struct kdbus_policy *p;
1466         __u64 size = sizeof(*p);
1467
1468         p = malloc(size);
1469         if (!p)
1470                 return NULL;
1471
1472         memset(p, 0, size);
1473         p->size = size;
1474         p->type = KDBUS_POLICY_ACCESS;
1475         p->access.type = type;
1476         p->access.bits = bits;
1477         p->access.id = id;
1478
1479         return p;
1480 }
1481
1482 void append_policy(struct kdbus_cmd_policy *cmd_policy, struct kdbus_policy *policy, __u64 max_size)
1483 {
1484         struct kdbus_policy *dst = (struct kdbus_policy *) ((char *) cmd_policy + cmd_policy->size);
1485
1486         if (cmd_policy->size + policy->size > max_size)
1487                 return;
1488
1489         memcpy(dst, policy, policy->size);
1490         cmd_policy->size += KDBUS_ALIGN8(policy->size);
1491         free(policy);
1492 }
1493
1494 dbus_bool_t bus_register_kdbus_policy(const char* name, DBusConnection *connection, DBusError *error)
1495 {
1496         struct kdbus_cmd_policy *cmd_policy;
1497         struct kdbus_policy *policy;
1498         int size = 0xffff;
1499         int fd;
1500
1501         if(!dbus_connection_get_socket(connection, &fd))
1502         {
1503                 dbus_set_error (error, "Failed to get fd for registering policy", NULL);
1504                 return FALSE;
1505         }
1506
1507         cmd_policy = (struct kdbus_cmd_policy *) alloca(size);
1508         memset(cmd_policy, 0, size);
1509
1510         policy = (struct kdbus_policy *) cmd_policy->policies;
1511         cmd_policy->size = offsetof(struct kdbus_cmd_policy, policies);
1512
1513         policy = make_policy_name(name);                //todo to be verified or changed when meaning will be known
1514         append_policy(cmd_policy, policy, size);
1515
1516         policy = make_policy_access(KDBUS_POLICY_ACCESS_USER, KDBUS_POLICY_OWN, getuid());
1517         append_policy(cmd_policy, policy, size);
1518
1519         policy = make_policy_access(KDBUS_POLICY_ACCESS_WORLD, KDBUS_POLICY_RECV, 0);
1520         append_policy(cmd_policy, policy, size);
1521
1522         policy = make_policy_access(KDBUS_POLICY_ACCESS_WORLD, KDBUS_POLICY_SEND, 0);
1523         append_policy(cmd_policy, policy, size);
1524
1525         if (ioctl(fd, KDBUS_CMD_EP_POLICY_SET, cmd_policy) < 0)
1526         {
1527                 dbus_set_error(error,_dbus_error_from_errno (errno), "Error setting EP policy: %s", _dbus_strerror (errno));
1528                 return FALSE;
1529         }
1530
1531         _dbus_verbose("Policy %s set correctly\n", name);
1532         return TRUE;
1533 }
1534
1535 dbus_bool_t bus_register_kdbus(char** unique_name, DBusConnection *connection, DBusError *error)
1536 {
1537         char name[18];
1538         struct kdbus_cmd_hello hello;
1539         int fd;
1540
1541         memset(&hello, 0, sizeof(hello));
1542         hello.conn_flags = KDBUS_HELLO_ACCEPT_FD |
1543                            KDBUS_HELLO_ATTACH_COMM |
1544                            KDBUS_HELLO_ATTACH_EXE |
1545                            KDBUS_HELLO_ATTACH_CMDLINE |
1546                            KDBUS_HELLO_ATTACH_CAPS |
1547                            KDBUS_HELLO_ATTACH_CGROUP |
1548                            KDBUS_HELLO_ATTACH_SECLABEL |
1549                            KDBUS_HELLO_ATTACH_AUDIT;
1550         hello.size = sizeof(struct kdbus_cmd_hello);
1551         hello.pool_size = (16 * 1024LU * 1024LU);  //todo was: #define POOL_SIZE
1552
1553         if(!dbus_connection_get_socket(connection, &fd))
1554         {
1555                 dbus_set_error (error, "failed to get fd for bus registration", NULL);
1556                 return FALSE;
1557         }
1558         if (ioctl(fd, KDBUS_CMD_HELLO, &hello))
1559         {
1560                 dbus_set_error(error,_dbus_error_from_errno (errno), "Failed to send hello: %s", _dbus_strerror (errno));
1561                 return FALSE;
1562         }
1563
1564         _dbus_verbose("-- Our peer ID is: %llu\n", (unsigned long long)hello.id);
1565         sprintf(name, "%llx", (unsigned long long)hello.id);
1566         *unique_name = _dbus_strdup(name);
1567         if (*unique_name == NULL)
1568         {
1569           _DBUS_SET_OOM (error);
1570           return FALSE;
1571         }
1572
1573         return TRUE;
1574 }
1575
1576 uint64_t bus_request_name_kdbus(DBusConnection *connection, const char *name, const uint64_t flags, DBusError *error)
1577 {
1578         struct kdbus_cmd_name *cmd_name;
1579         int fd;
1580         uint64_t size = sizeof(*cmd_name) + strlen(name) + 1;
1581         uint64_t flags_kdbus = 0;
1582
1583         cmd_name = alloca(size);
1584
1585         memset(cmd_name, 0, size);
1586         strcpy(cmd_name->name, name);
1587         cmd_name->size = size;
1588
1589         if(flags & DBUS_NAME_FLAG_ALLOW_REPLACEMENT)
1590                 flags_kdbus |= KDBUS_NAME_ALLOW_REPLACEMENT;
1591         if(!(flags & DBUS_NAME_FLAG_DO_NOT_QUEUE))
1592                 flags_kdbus |= KDBUS_NAME_QUEUE;
1593         if(flags & DBUS_NAME_FLAG_REPLACE_EXISTING)
1594                 flags_kdbus |= KDBUS_NAME_REPLACE_EXISTING;
1595
1596         cmd_name->conn_flags = flags_kdbus;
1597
1598         if(!dbus_connection_get_socket(connection, &fd))
1599         {
1600                 dbus_set_error (error, "failed to get fd for name request", NULL);
1601                 return FALSE;
1602         }
1603
1604         _dbus_verbose("Request name - flags sent: 0x%llx       !!!!!!!!!\n", cmd_name->conn_flags);
1605
1606         _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1607         if (ioctl(fd, KDBUS_CMD_NAME_ACQUIRE, cmd_name))
1608         {
1609                 dbus_set_error(error,_dbus_error_from_errno (errno), "error acquiring name: %s", _dbus_strerror (errno));
1610                 if(errno == EEXIST)
1611                         return DBUS_REQUEST_NAME_REPLY_EXISTS;
1612                 return FALSE;
1613         }
1614
1615         _dbus_verbose("Request name - received flag: 0x%llx       !!!!!!!!!\n", cmd_name->conn_flags);
1616
1617         if(cmd_name->conn_flags & KDBUS_NAME_IN_QUEUE)
1618                 return DBUS_REQUEST_NAME_REPLY_IN_QUEUE;
1619         else
1620                 return DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER;
1621         //todo now 1 codes are never returned -  DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER
1622 }
1623
1624 /**
1625  * Checks if the connection's transport is kdbus on the basis of its address
1626  *
1627  * @param pointer to the connection
1628  * @returns TRUE if kdbus transport, otherwise FALSE
1629  */
1630 dbus_bool_t dbus_transport_is_kdbus(DBusConnection *connection)
1631 {
1632         const char* address = _dbus_connection_get_address(connection);
1633
1634         if(address == strstr(address, "kdbus:path="))
1635                 return TRUE;
1636         else
1637                 return FALSE;
1638 }
1639
1640 void dbus_bus_add_match_kdbus (DBusConnection *connection, const char *rule, DBusError *error)
1641 {
1642         struct kdbus_cmd_match cmd_match;
1643         int fd;
1644
1645         memset(&cmd_match, 0, sizeof(cmd_match));
1646
1647         if(!dbus_connection_get_socket(connection, &fd))
1648         {
1649                 dbus_set_error (error, "failed to get fd for add match", NULL);
1650                 return;
1651         }
1652
1653         cmd_match.size = sizeof(cmd_match);
1654
1655         //todo add matching rules from *rule when it will be docuemnted in kdbus
1656
1657
1658         cmd_match.src_id = KDBUS_MATCH_SRC_ID_ANY;
1659
1660         if (ioctl(fd, KDBUS_CMD_MATCH_ADD, &cmd_match))
1661                 dbus_set_error(error,_dbus_error_from_errno (errno), "error adding match: %s", _dbus_strerror (errno));
1662
1663         _dbus_verbose("Finished adding match bus rule %s             !!!!!!!!!\n", rule);
1664 }