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